@arcgis/ai-components 5.2.0-next.106 → 5.2.0-next.107

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 (285) hide show
  1. package/dist/agent-utils/BaseAgent.js +1 -1
  2. package/dist/agent-utils/FunctionAgent.js +1 -1
  3. package/dist/agent-utils/LLMAgent.js +1 -1
  4. package/dist/agent-utils/WorkflowAgent.js +1 -1
  5. package/dist/agent-utils/index.js +1 -1
  6. package/dist/agent-utils/middlewares/humanInTheLoop.js +1 -1
  7. package/dist/agent-utils/middlewares/middleware.js +1 -1
  8. package/dist/agent-utils/middlewares/trace.js +1 -1
  9. package/dist/agent-utils/middlewares/types.js +1 -1
  10. package/dist/agent-utils/tools/FunctionTool.js +1 -1
  11. package/dist/agent-utils/workflows/ConditionalWorkflow.js +1 -1
  12. package/dist/agent-utils/workflows/LoopWorkflow.js +1 -1
  13. package/dist/agent-utils/workflows/ParallelWorkflow.js +1 -1
  14. package/dist/agent-utils/workflows/RouterWorkflow.js +1 -1
  15. package/dist/agent-utils/workflows/SequentialWorkflow.js +1 -1
  16. package/dist/agent-utils/workflows/SwitchWorkflow.js +1 -1
  17. package/dist/agents/runtime/skill/createSkillAgent.d.ts +1 -1
  18. package/dist/agents/runtime/skill/createSkillAgent.js +42 -44
  19. package/dist/agents/runtime/skill/types.d.ts +1 -1
  20. package/dist/agents/runtime/skill/types.js +1 -1
  21. package/dist/agents/tools/filter/clearFilters/adapter.js +1 -1
  22. package/dist/agents/tools/filter/resetMap/adapter.js +1 -1
  23. package/dist/agents/tools/filter/setFeatureEffect/adapter.js +1 -1
  24. package/dist/agents/tools/help/listFields/adapter.js +1 -1
  25. package/dist/agents/tools/navigation/goToAddress/adapter.js +1 -1
  26. package/dist/agents/tools/navigation/goToBookmark/adapter.js +1 -1
  27. package/dist/agents/tools/navigation/goToFeatures/adapter.js +1 -1
  28. package/dist/agents/tools/navigation/goToFullExtent/adapter.js +1 -1
  29. package/dist/agents/tools/navigation/goToHomeExtent/adapter.js +1 -1
  30. package/dist/agents/tools/navigation/goToLayer/adapter.js +1 -1
  31. package/dist/agents/tools/navigation/goToScale/adapter.js +1 -1
  32. package/dist/agents/tools/navigation/goToViewpoint/adapter.js +1 -1
  33. package/dist/agents/tools/navigation/goToZoom/adapter.js +1 -1
  34. package/dist/agents/tools/query/getAttribute/adapter.js +1 -1
  35. package/dist/agents/tools/query/getStatistics/adapter.js +1 -1
  36. package/dist/agents/tools/query/getTopFeatures/adapter.js +1 -1
  37. package/dist/agents/tools/query/queryFeatures/adapter.js +1 -1
  38. package/dist/agents/tools/search/findRelevantFields/adapter.js +1 -1
  39. package/dist/agents/tools/search/findRelevantLayers/adapter.js +1 -1
  40. package/dist/agents/tools/shared/resolveToolArtifact.js +1 -1
  41. package/dist/agents/tools/shared/types.js +1 -1
  42. package/dist/cdn/25MBI4PD.js +2 -0
  43. package/dist/cdn/{3XDT7MWI.js → 275FFTBE.js} +2 -2
  44. package/dist/cdn/{XQ3NBBQ3.js → 2F4TPWZQ.js} +1 -1
  45. package/dist/cdn/{KJLLN4P4.js → 2LVYAXHG.js} +3 -3
  46. package/dist/cdn/{5MK44FNO.js → 2NRCE53B.js} +2 -2
  47. package/dist/cdn/{XKH37FLY.js → 2WXXSZP5.js} +2 -2
  48. package/dist/cdn/{APFZY4PI.js → 3KNLFIM3.js} +2 -2
  49. package/dist/cdn/{VMZZR7MY.js → 3PPXAIRE.js} +2 -2
  50. package/dist/cdn/{JMNHFKGL.js → 45BDE3MG.js} +2 -2
  51. package/dist/cdn/{S4LELUBK.js → 477I66FH.js} +2 -2
  52. package/dist/cdn/4CFCV47G.js +2 -0
  53. package/dist/cdn/{TPULIO6I.js → 4IWDBEMN.js} +2 -2
  54. package/dist/cdn/{HHBNLCJP.js → 4OI4QEV7.js} +2 -2
  55. package/dist/cdn/{2W7LK4HA.js → 4UAREC76.js} +2 -2
  56. package/dist/cdn/{TEI6WXW7.js → 4VBOTWC3.js} +2 -2
  57. package/dist/cdn/{RLEHNAIA.js → 4YOG5F3W.js} +1 -1
  58. package/dist/cdn/5X23DDDZ.js +2 -0
  59. package/dist/cdn/65ZACLYB.js +2 -0
  60. package/dist/cdn/{D5EKX26R.js → 6KWGSXIN.js} +2 -2
  61. package/dist/cdn/{O4NVW75A.js → 6MRTZ4OM.js} +2 -2
  62. package/dist/cdn/{6YZGKVYB.js → 77NAJM5H.js} +2 -2
  63. package/dist/cdn/{NEV6OZN3.js → 7DOYUO7L.js} +2 -2
  64. package/dist/cdn/{EYOWRGDP.js → 7JJX6VGI.js} +2 -2
  65. package/dist/cdn/{ONQ6JSBJ.js → A6LBMS7A.js} +1 -1
  66. package/dist/cdn/{EOD5PNOL.js → AP3KPOHN.js} +2 -2
  67. package/dist/cdn/AUCKEB52.js +2 -0
  68. package/dist/cdn/B3HXSEBN.js +2 -0
  69. package/dist/cdn/{6ECRQVHY.js → BAKJLCYO.js} +2 -2
  70. package/dist/cdn/{74CVYM72.js → BJMGT6GV.js} +2 -2
  71. package/dist/cdn/{5LMYUEK7.js → BTOBEN7Q.js} +2 -2
  72. package/dist/cdn/BTTCBEPW.js +2 -0
  73. package/dist/cdn/{UZLQALHY.js → BVUCNXC5.js} +1 -1
  74. package/dist/cdn/{RFVZ7KCG.js → CAOMMQSY.js} +1 -1
  75. package/dist/cdn/{P4GFYBBO.js → CBYBFBD3.js} +2 -2
  76. package/dist/cdn/{725MBCQF.js → CKUUYQLO.js} +2 -2
  77. package/dist/cdn/{MWYBF3F3.js → CSE6BHOJ.js} +2 -2
  78. package/dist/cdn/{XTCLJEID.js → CX2HJ67C.js} +2 -2
  79. package/dist/cdn/EELMDCPV.js +2 -0
  80. package/dist/cdn/{6RAWG2KQ.js → EGRRZTF6.js} +2 -2
  81. package/dist/cdn/EHYDAEGL.js +2 -0
  82. package/dist/cdn/{TBYDZN4H.js → EK3PM4L5.js} +2 -2
  83. package/dist/cdn/{PYGX4HN7.js → ENAEE4UU.js} +2 -2
  84. package/dist/cdn/EXMEB4X2.js +2 -0
  85. package/dist/cdn/{AGQ5ADFU.js → EYGZJKVD.js} +2 -2
  86. package/dist/cdn/{BTTBKTFM.js → FK2CVSXW.js} +2 -2
  87. package/dist/cdn/FLUI6GCU.js +2 -0
  88. package/dist/cdn/{ZU2FHVNK.js → FPH52WOH.js} +2 -2
  89. package/dist/cdn/FRYS2PZJ.js +2 -0
  90. package/dist/cdn/FSLQCZRN.js +2 -0
  91. package/dist/cdn/{PQ2DPOFM.js → FTTLFIBV.js} +2 -2
  92. package/dist/cdn/{2AMUOR7X.js → FV6FHLYW.js} +2 -2
  93. package/dist/cdn/{TFRWUAB6.js → G24MNC7D.js} +2 -2
  94. package/dist/cdn/{6OOZSZRJ.js → GN56DOYL.js} +2 -2
  95. package/dist/cdn/{ROQGPAR5.js → HIJGY4GU.js} +2 -2
  96. package/dist/cdn/{BL273EGZ.js → HMMYCSOK.js} +2 -2
  97. package/dist/cdn/{ES6D4UD6.js → HNTSDY3J.js} +2 -2
  98. package/dist/cdn/HQOK6DDH.js +2 -0
  99. package/dist/cdn/{HB72YIII.js → HV7MVIQV.js} +2 -2
  100. package/dist/cdn/I3SUE2TR.js +2 -0
  101. package/dist/cdn/{VAXH6RUQ.js → I72ST4JR.js} +2 -2
  102. package/dist/cdn/{FYZATVB3.js → IHUWQOMK.js} +2 -2
  103. package/dist/cdn/{J6A4AS7E.js → JMXXRRKQ.js} +2 -2
  104. package/dist/cdn/{5HBAJ57P.js → JPXEMNPR.js} +2 -2
  105. package/dist/cdn/{UHEYPSOR.js → JYNHWJUZ.js} +2 -2
  106. package/dist/cdn/KAX4A7SF.js +2 -0
  107. package/dist/cdn/{BQYF37UD.js → KBSXHSBX.js} +2 -2
  108. package/dist/cdn/{CCC6LBMY.js → KKCLHXHG.js} +1 -1
  109. package/dist/cdn/{7UF3WRLO.js → L2HLFWCV.js} +2 -2
  110. package/dist/cdn/{LK7ZIQW6.js → L3BTURBA.js} +2 -2
  111. package/dist/cdn/{IRSJXHRN.js → LBTGOMCT.js} +2 -2
  112. package/dist/cdn/{34O57OGV.js → LLY5A2E2.js} +1 -1
  113. package/dist/cdn/{OOGADOKQ.js → LXIKAXUT.js} +2 -2
  114. package/dist/cdn/{S627D4K7.js → M2U456J5.js} +2 -2
  115. package/dist/cdn/{UAG6GDUG.js → M3KKORBG.js} +2 -2
  116. package/dist/cdn/M5B6X46F.js +2 -0
  117. package/dist/cdn/{SDWWUWAF.js → MZUDIQQH.js} +2 -2
  118. package/dist/cdn/{CEKOEHB3.js → NNPA3NLK.js} +2 -2
  119. package/dist/cdn/{MXTXJKFE.js → NPWLYHMU.js} +2 -2
  120. package/dist/cdn/NV7CL4S3.js +2 -0
  121. package/dist/cdn/{3UEKINYC.js → OALQBAZR.js} +2 -2
  122. package/dist/cdn/{RHYNE5OE.js → OF3TAARW.js} +1 -1
  123. package/dist/cdn/{F5NIRETW.js → P53TDER7.js} +2 -2
  124. package/dist/cdn/{SXM4NUT5.js → PJLGCS33.js} +2 -2
  125. package/dist/cdn/{EJJFG5DE.js → PJPP6LOS.js} +2 -2
  126. package/dist/cdn/PUZ6RAFQ.js +2 -0
  127. package/dist/cdn/{IHP25JWI.js → QAX6UF4L.js} +2 -2
  128. package/dist/cdn/{JEBRN3EU.js → QTEPFTAU.js} +2 -2
  129. package/dist/cdn/ROS22KOA.js +2 -0
  130. package/dist/cdn/RPOFBIE7.js +2 -0
  131. package/dist/cdn/{COH3QXWG.js → S5GFNIHC.js} +3 -3
  132. package/dist/cdn/{A7BKHIMA.js → SBNNJ5WA.js} +2 -2
  133. package/dist/cdn/SI22EJLC.js +2 -0
  134. package/dist/cdn/{7QIX4PZR.js → SJMAKF4P.js} +2 -2
  135. package/dist/cdn/{6P44KOKX.js → SKCUGZ7G.js} +2 -2
  136. package/dist/cdn/{V6HOUZPZ.js → SNG3WODY.js} +2 -2
  137. package/dist/cdn/{JWZD3D5E.js → STOGCXJH.js} +2 -2
  138. package/dist/cdn/{OMF6ITSG.js → SUC2MIGE.js} +2 -2
  139. package/dist/cdn/SXYKNDOF.js +2 -0
  140. package/dist/cdn/SZ2L5556.js +2 -0
  141. package/dist/cdn/{4ALF2CJY.js → T6W6F4TF.js} +2 -2
  142. package/dist/cdn/{RN6WMVZX.js → TFAJNKBC.js} +2 -2
  143. package/dist/cdn/{R74ZHFA6.js → TLPZELG3.js} +1 -1
  144. package/dist/cdn/{2O4DON37.js → TNLFUXIB.js} +2 -2
  145. package/dist/cdn/{RLB6TK6B.js → TXZQZR3I.js} +2 -2
  146. package/dist/cdn/UGIHS7OA.js +2 -0
  147. package/dist/cdn/{UDRKUVZP.js → UX457AQR.js} +2 -2
  148. package/dist/cdn/{ICBIUFK7.js → V266DJ5V.js} +2 -2
  149. package/dist/cdn/{FDOMMK2M.js → V4PJMCJZ.js} +1 -1
  150. package/dist/cdn/{3VCPN2KW.js → V52GSTOC.js} +2 -2
  151. package/dist/cdn/{UHICISBZ.js → VGLBH473.js} +2 -2
  152. package/dist/cdn/{WSWB3B7B.js → VHNTHPH7.js} +2 -2
  153. package/dist/cdn/{OZ2CM3J2.js → VK6CCPTG.js} +2 -2
  154. package/dist/cdn/{AOVJ34QE.js → VLPELJUS.js} +2 -2
  155. package/dist/cdn/VT5EWFH7.js +2 -0
  156. package/dist/cdn/{Y7LGFSHO.js → VXLKTQ36.js} +2 -2
  157. package/dist/cdn/{CFAC4FN3.js → W54XYT2A.js} +2 -2
  158. package/dist/cdn/{RZIXMISL.js → X42ACC66.js} +2 -2
  159. package/dist/cdn/{7EOS4SGJ.js → XNUWVZN7.js} +2 -2
  160. package/dist/cdn/{2OUIRKTV.js → XOTPSCNF.js} +2 -2
  161. package/dist/cdn/{ZZZB3GES.js → XRVGYRXL.js} +2 -2
  162. package/dist/cdn/{JKKU4K4C.js → XV7RMYLR.js} +2 -2
  163. package/dist/cdn/{3SD47V7G.js → XVJFPZTW.js} +2 -2
  164. package/dist/cdn/XZF7Y6B2.js +2 -0
  165. package/dist/cdn/Y4ZOB6UH.js +2 -0
  166. package/dist/cdn/{ZFOG3KXV.js → Y6CV2NZR.js} +2 -2
  167. package/dist/cdn/YMJKT5OK.js +2 -0
  168. package/dist/cdn/{6GODC6RU.js → YOW3YKWR.js} +2 -2
  169. package/dist/cdn/{OKVLGJAG.js → ZA7ZU2F7.js} +2 -2
  170. package/dist/cdn/{OL7QBAGS.js → ZJWR4W2S.js} +2 -2
  171. package/dist/cdn/ZWIKFBOU.js +2 -0
  172. package/dist/cdn/{MXAZE2VM.js → ZY3JQCZQ.js} +36 -36
  173. package/dist/cdn/agent-utils/index.js +2 -2
  174. package/dist/cdn/agent-utils/middlewares/humanInTheLoop.js +2 -2
  175. package/dist/cdn/agent-utils/middlewares/middleware.js +2 -2
  176. package/dist/cdn/agent-utils/middlewares/trace.js +2 -2
  177. package/dist/cdn/index.js +2 -2
  178. package/dist/chunks/BaseWorkflow.js +1 -1
  179. package/dist/chunks/SKILL.js +1 -1
  180. package/dist/chunks/SKILL2.js +1 -1
  181. package/dist/chunks/SKILL3.js +1 -1
  182. package/dist/chunks/SKILL4.js +1 -1
  183. package/dist/chunks/adapter.js +1 -1
  184. package/dist/chunks/aiFactory.js +1 -1
  185. package/dist/chunks/arcgisKnowledgeGraph.js +1 -1
  186. package/dist/chunks/arcgisToolRegistry.js +88 -0
  187. package/dist/chunks/arcgis_knowledge_current_lc_context.js +1 -1
  188. package/dist/chunks/arcgis_knowledge_current_map_context.js +1 -1
  189. package/dist/chunks/arcgis_knowledge_cypher_query_prompt.js +1 -1
  190. package/dist/chunks/arcgis_knowledge_lucene_generation_prompt.js +1 -1
  191. package/dist/chunks/arcgis_knowledge_summarize_result_prompt.js +1 -1
  192. package/dist/chunks/arcgis_knowledge_tool_prompt.js +1 -1
  193. package/dist/chunks/baseAgentState.js +1 -1
  194. package/dist/chunks/converterUtils.js +1 -1
  195. package/dist/chunks/dataExplorationAgent.js +3 -14
  196. package/dist/chunks/data_explore_filter_prompt.js +1 -1
  197. package/dist/chunks/data_explore_query_prompt.js +1 -1
  198. package/dist/chunks/embeddings.worker.js +1 -1
  199. package/dist/chunks/fetchAgentContext.js +1 -1
  200. package/dist/chunks/fetchService.js +1 -1
  201. package/dist/chunks/fieldStatistics.js +1 -1
  202. package/dist/chunks/field_descriptions_prompt.js +1 -1
  203. package/dist/chunks/formatFeatureAttributes.js +1 -1
  204. package/dist/chunks/generateLayerDescriptions.js +1 -1
  205. package/dist/chunks/graph.js +1 -1
  206. package/dist/chunks/helpAgent.js +11 -14
  207. package/dist/chunks/help_prompt.js +1 -1
  208. package/dist/chunks/index.js +1 -1
  209. package/dist/chunks/intent_prompt.js +1 -1
  210. package/dist/chunks/layerStylingGraph.js +1 -1
  211. package/dist/chunks/layer_descriptions_prompt.js +1 -1
  212. package/dist/chunks/layer_styling_prompt.js +1 -1
  213. package/dist/chunks/mergeWhereClauses.js +1 -1
  214. package/dist/chunks/navigationAgent.js +7 -20
  215. package/dist/chunks/navigation_intent_prompt.js +1 -1
  216. package/dist/chunks/navigation_tool_prompt.js +1 -1
  217. package/dist/chunks/orchestrator.js +1 -1
  218. package/dist/chunks/requireAgentServices.js +1 -1
  219. package/dist/chunks/resolvePointGeometryFilter.js +1 -1
  220. package/dist/chunks/runtime.js +2 -2
  221. package/dist/chunks/slottableRequestUtils.js +1 -1
  222. package/dist/chunks/state.js +1 -1
  223. package/dist/chunks/summarize_query_response_prompt.js +1 -1
  224. package/dist/chunks/useT9n.js +1 -1
  225. package/dist/chunks/utils.js +1 -1
  226. package/dist/chunks/utils2.js +1 -1
  227. package/dist/chunks/utils3.js +1 -1
  228. package/dist/components/arcgis-assistant/customElement.js +1 -1
  229. package/dist/components/arcgis-assistant-agent/customElement.js +130 -212
  230. package/dist/components/arcgis-assistant-chat/customElement.js +1 -1
  231. package/dist/components/arcgis-assistant-chat-entry/customElement.js +1 -1
  232. package/dist/components/arcgis-assistant-data-exploration-agent/customElement.js +1 -1
  233. package/dist/components/arcgis-assistant-help-agent/customElement.js +1 -1
  234. package/dist/components/arcgis-assistant-interrupt/customElement.js +1 -1
  235. package/dist/components/arcgis-assistant-interrupt-preview/customElement.js +1 -1
  236. package/dist/components/arcgis-assistant-knowledge-agent/customElement.js +1 -1
  237. package/dist/components/arcgis-assistant-layer-styling-agent/customElement.js +1 -1
  238. package/dist/components/arcgis-assistant-message/customElement.js +1 -1
  239. package/dist/components/arcgis-assistant-message-block/customElement.js +1 -1
  240. package/dist/components/arcgis-assistant-message-feedback/customElement.js +1 -1
  241. package/dist/components/arcgis-assistant-message-footer/customElement.js +1 -1
  242. package/dist/components/arcgis-assistant-message-loading/customElement.js +1 -1
  243. package/dist/components/arcgis-assistant-message-log/customElement.js +1 -1
  244. package/dist/components/arcgis-assistant-message-read-aloud/customElement.js +1 -1
  245. package/dist/components/arcgis-assistant-message-text/customElement.js +1 -1
  246. package/dist/components/arcgis-assistant-navigation-agent/customElement.js +1 -1
  247. package/dist/components/arcgis-assistant-speech-input/customElement.js +1 -1
  248. package/dist/components/arcgis-assistant-suggested-prompts/customElement.js +1 -1
  249. package/dist/components/arcgis-assistant-user-message/customElement.js +1 -1
  250. package/dist/docs/api.json +1 -1
  251. package/dist/docs/docs.json +1 -1
  252. package/dist/docs/web-types.json +1 -1
  253. package/dist/index.js +1 -1
  254. package/dist/loader.js +1 -1
  255. package/dist/utils/index.js +1 -1
  256. package/package.json +5 -5
  257. package/dist/cdn/23C34FEU.js +0 -2
  258. package/dist/cdn/2OHRNRNT.js +0 -2
  259. package/dist/cdn/2S6L3P4Q.js +0 -2
  260. package/dist/cdn/3IOP64NG.js +0 -2
  261. package/dist/cdn/3OH35VXS.js +0 -2
  262. package/dist/cdn/434TAA3J.js +0 -2
  263. package/dist/cdn/AFSBL4ZP.js +0 -2
  264. package/dist/cdn/BVSK2GWP.js +0 -2
  265. package/dist/cdn/EGN5BCHV.js +0 -2
  266. package/dist/cdn/HLN5675C.js +0 -2
  267. package/dist/cdn/IFFOSSNB.js +0 -2
  268. package/dist/cdn/IO7DYFL2.js +0 -2
  269. package/dist/cdn/JD2TB7H4.js +0 -2
  270. package/dist/cdn/KZ73TZOB.js +0 -2
  271. package/dist/cdn/LEO3USHH.js +0 -2
  272. package/dist/cdn/LNIMGXB4.js +0 -2
  273. package/dist/cdn/MG2W2ZF3.js +0 -2
  274. package/dist/cdn/MSXMHRI7.js +0 -2
  275. package/dist/cdn/PK5KI2XF.js +0 -2
  276. package/dist/cdn/PWFUEBTT.js +0 -2
  277. package/dist/cdn/RSJSRETN.js +0 -2
  278. package/dist/cdn/RSR66KB4.js +0 -2
  279. package/dist/cdn/SL4Y7IRG.js +0 -2
  280. package/dist/cdn/STUBN3L5.js +0 -2
  281. package/dist/cdn/T2OYKP3V.js +0 -2
  282. package/dist/cdn/U3ETGDT7.js +0 -2
  283. package/dist/cdn/VXFQANGJ.js +0 -2
  284. package/dist/cdn/WW4BEFDF.js +0 -2
  285. package/dist/cdn/XGCQS3N4.js +0 -2
@@ -1,5 +1,5 @@
1
- /* COPYRIGHT Esri - https://js.arcgis.com/5.2/LICENSE.txt */
2
- import{a as ls,b as ki,c as vi,d as Ti}from"./HHBNLCJP.js";import{b as ri}from"./R74ZHFA6.js";import{a as st}from"./3VCPN2KW.js";import{b as Ci,c as Ri,d as Ei}from"./S4LELUBK.js";import{$ as Oi,aa as Xn,b as gi,d as yi,e as Ai,f as Zs,g as Vn,h as Kt,i as Jn,j as Ii,k as bi,ka as ke,m as xi,n as wi,o as Vs,p as Gn,q as Pi}from"./OL7QBAGS.js";import{$ as ai,Da as ci,Ea as re,O as Fs,P as ni,Pb as E,R as oi,Sb as Zn,W as Bs,Wb as Lt,X as ii,d as rt,da as ui,ec as _i,g as si,h as Ls,ia as Hn,jb as as,la as li,mb as di,n as qn,nb as fi,o as Wn,oc as Ws,p as Ks,pb as us,ta as ae,ua as qs,wa as Dt,xb as hi,zc as Hs}from"./S627D4K7.js";import{a as ue}from"./VXFQANGJ.js";import{$ as mi,Dd as b,j as pi}from"./MWYBF3F3.js";export default $arcgis.t(([rl,sl,Yp,Qp])=>{function cs(t,e){return t.lc_error_code=e,t.message=`${t.message}
1
+ /* COPYRIGHT Esri - https://js.arcgis.com/1.0/LICENSE.txt */
2
+ import{a as ls,b as ki,c as vi,d as Ti}from"./4OI4QEV7.js";import{b as ri}from"./TLPZELG3.js";import{a as st}from"./V52GSTOC.js";import{b as Ci,c as Ri,d as Ei}from"./477I66FH.js";import{$ as Oi,aa as Xn,b as gi,d as yi,e as Ai,f as Zs,g as Vn,h as Kt,i as Jn,j as Ii,k as bi,ka as ke,m as xi,n as wi,o as Vs,p as Gn,q as Pi}from"./ZJWR4W2S.js";import{$ as ai,Da as ci,Ea as re,O as Fs,P as ni,Pb as E,R as oi,Sb as Zn,W as Bs,Wb as Lt,X as ii,d as rt,da as ui,ec as _i,g as si,h as Ls,ia as Hn,jb as as,la as li,mb as di,n as qn,nb as fi,o as Wn,oc as Ws,p as Ks,pb as us,ta as ae,ua as qs,wa as Dt,xb as hi,zc as Hs}from"./M2U456J5.js";import{a as ue}from"./5X23DDDZ.js";import{$ as mi,Dd as b,j as pi}from"./CSE6BHOJ.js";export default $arcgis.t(([rl,sl,Yp,Qp])=>{function cs(t,e){return t.lc_error_code=e,t.message=`${t.message}
3
3
 
4
4
  Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/
5
5
  `,t}function k(t,e,r,s,n){if(s==="m")throw new TypeError("Private method is not writable");if(s==="a"&&!n)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return s==="a"?n.call(t,r):n?n.value=r:e.set(t,r),r}function d(t,e,r,s){if(r==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?s:r==="a"?s.call(t):s?s.value:e.get(t)}var Yn=function(){let{crypto:t}=globalThis;if(t?.randomUUID)return Yn=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^r()&15>>+s/4).toString(16))};function ps(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var ms=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};var P=class extends Error{},j=class t extends P{constructor(e,r,s,n){super(`${t.makeMessage(e,r,s)}`),this.status=e,this.headers=n,this.requestID=n?.get("x-request-id"),this.error=r;let o=r;this.code=o?.code,this.param=o?.param,this.type=o?.type}static makeMessage(e,r,s){let n=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):s;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,r,s,n){if(!e||!n)return new Le({message:s,cause:ms(r)});let o=r?.error;return e===400?new Ft(e,o,s,n):e===401?new Bt(e,o,s,n):e===403?new qt(e,o,s,n):e===404?new Wt(e,o,s,n):e===409?new Ht(e,o,s,n):e===422?new Zt(e,o,s,n):e===429?new Vt(e,o,s,n):e>=500?new Jt(e,o,s,n):new t(e,o,s,n)}},D=class extends j{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Le=class extends j{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},ye=class extends Le{constructor({message:e}={}){super({message:e??"Request timed out."})}},Ft=class extends j{},Bt=class extends j{},qt=class extends j{},Wt=class extends j{},Ht=class extends j{},Zt=class extends j{},Vt=class extends j{},Jt=class extends j{},Gt=class extends P{constructor(){super("Could not parse response content as the length limit was reached")}},Xt=class extends P{constructor(){super("Could not parse response content as the request was rejected by the content filter")}},Ae=class extends Error{constructor(e){super(e)}},nt=class extends j{constructor(e,r,s){let n="OAuth2 authentication error",o;if(r&&typeof r=="object"){let i=r;o=i.error;let a=i.error_description;a&&typeof a=="string"?n=a:o&&(n=o)}super(e,r,n,s),this.error_code=o}},ds=class extends P{constructor(e,r,s){super(e),this.provider=r,this.cause=s}};var dl=/^[a-z][a-z0-9+.-]*:/i,Si=t=>dl.test(t),Y=t=>(Y=Array.isArray,Y(t)),Qn=Y;function Js(t){return typeof t!="object"?{}:t??{}}function eo(t){if(!t)return!0;for(let e in t)return!1;return!0}function $i(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function fs(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var Mi=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new P(`${t} must be an integer`);if(e<0)throw new P(`${t} must be a positive integer`);return e};var Ni=t=>{try{return JSON.parse(t)}catch{return}};var Ie=t=>new Promise(e=>setTimeout(e,t));var Ke="6.45.0";var Di=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function fl(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}var hl=()=>{let t=fl();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":Ui(Deno.build.os),"X-Stainless-Arch":zi(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":Ui(globalThis.process.platform??"unknown"),"X-Stainless-Arch":zi(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=_l();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ke,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _l(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let s=r.exec(navigator.userAgent);if(s){let n=s[1]||0,o=s[2]||0,i=s[3]||0;return{browser:e,version:`${n}.${o}.${i}`}}}return null}var zi=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Ui=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),ji,Li=()=>ji??(ji=hl());function Gs(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function to(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Xs(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return to({start(){},async pull(r){let{done:s,value:n}=await e.next();s?r.close():r.enqueue(n)},async cancel(){await e.return?.()}})}function ro(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r?.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function so(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var Fi=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var no="RFC3986",oo=t=>String(t),io={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:oo},Bi="RFC1738";var Ys=(t,e)=>(Ys=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Ys(t,e)),be=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var ao=1024,qi=(t,e,r,s,n)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=ao){let c=o.length>=ao?o.slice(a,a+ao):o,u=[];for(let f=0;f<c.length;++f){let h=c.charCodeAt(f);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||n===Bi&&(h===40||h===41)){u[u.length]=c.charAt(f);continue}if(h<128){u[u.length]=be[h];continue}if(h<2048){u[u.length]=be[192|h>>6]+be[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=be[224|h>>12]+be[128|h>>6&63]+be[128|h&63];continue}f+=1,h=65536+((h&1023)<<10|c.charCodeAt(f)&1023),u[u.length]=be[240|h>>18]+be[128|h>>12&63]+be[128|h>>6&63]+be[128|h&63]}i+=u.join("")}return i};function Wi(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function uo(t,e){if(Y(t)){let r=[];for(let s=0;s<t.length;s+=1)r.push(e(t[s]));return r}return e(t)}var Zi={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Vi=function(t,e){Array.prototype.push.apply(t,Y(e)?e:[e])},Hi,W={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qi,encodeValuesOnly:!1,format:no,formatter:oo,indices:!1,serializeDate(t){return(Hi??(Hi=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function yl(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var lo={};function Ji(t,e,r,s,n,o,i,a,c,u,f,h,g,y,I,x,_,v){let p=t,A=v,O=0,z=!1;for(;(A=A.get(lo))!==void 0&&!z;){let F=A.get(t);if(O+=1,typeof F<"u"){if(F===O)throw new RangeError("Cyclic object value");z=!0}typeof A.get(lo)>"u"&&(O=0)}if(typeof u=="function"?p=u(e,p):p instanceof Date?p=g?.(p):r==="comma"&&Y(p)&&(p=uo(p,function(F){return F instanceof Date?g?.(F):F})),p===null){if(o)return c&&!x?c(e,W.encoder,_,"key",y):e;p=""}if(yl(p)||Wi(p)){if(c){let F=x?e:c(e,W.encoder,_,"key",y);return[I?.(F)+"="+I?.(c(p,W.encoder,_,"value",y))]}return[I?.(e)+"="+I?.(String(p))]}let N=[];if(typeof p>"u")return N;let U;if(r==="comma"&&Y(p))x&&c&&(p=uo(p,c)),U=[{value:p.length>0?p.join(",")||null:void 0}];else if(Y(u))U=u;else{let F=Object.keys(p);U=f?F.sort(f):F}let L=a?String(e).replace(/\./g,"%2E"):String(e),X=s&&Y(p)&&p.length===1?L+"[]":L;if(n&&Y(p)&&p.length===0)return X+"[]";for(let F=0;F<U.length;++F){let q=U[F],ei=typeof q=="object"&&typeof q.value<"u"?q.value:p[q];if(i&&ei===null)continue;let Bn=h&&a?q.replace(/\./g,"%2E"):q,pl=Y(p)?typeof r=="function"?r(X,Bn):X:X+(h?"."+Bn:"["+Bn+"]");v.set(t,O);let ti=new WeakMap;ti.set(lo,v),Vi(N,Ji(ei,pl,r,s,n,o,i,a,r==="comma"&&x&&Y(p)?null:c,u,f,h,g,y,I,x,_,ti))}return N}function Al(t=W){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||W.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=no;if(typeof t.format<"u"){if(!Ys(io,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let s=io[r],n=W.filter;(typeof t.filter=="function"||Y(t.filter))&&(n=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in Zi?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=W.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:W.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:W.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:W.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:W.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?W.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:W.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:W.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:W.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:W.encodeValuesOnly,filter:n,format:r,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:W.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:W.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:W.strictNullHandling}}function Gi(t,e={}){let r=t,s=Al(e),n,o;typeof s.filter=="function"?(o=s.filter,r=o("",r)):Y(s.filter)&&(o=s.filter,n=o);let i=[];if(typeof r!="object"||r===null)return"";let a=Zi[s.arrayFormat],c=a==="comma"&&s.commaRoundTrip;n||(n=Object.keys(r)),s.sort&&n.sort(s.sort);let u=new WeakMap;for(let g=0;g<n.length;++g){let y=n[g];s.skipNulls&&r[y]===null||Vi(i,Ji(r[y],y,a,c,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,u))}let f=i.join(s.delimiter),h=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),f.length>0?h+f:""}function Xi(t){return Gi(t,{arrayFormat:"brackets"})}function ea(t){let e=0;for(let n of t)e+=n.length;let r=new Uint8Array(e),s=0;for(let n of t)r.set(n,s),s+=n.length;return r}var Yi;function Yt(t){let e;return(Yi??(e=new globalThis.TextEncoder,Yi=e.encode.bind(e)))(t)}var Qi;function co(t){let e;return(Qi??(e=new globalThis.TextDecoder,Qi=e.decode.bind(e)))(t)}var se,ne,ot=class{constructor(){se.set(this,void 0),ne.set(this,void 0),k(this,se,new Uint8Array,"f"),k(this,ne,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Yt(e):e;k(this,se,ea([d(this,se,"f"),r]),"f");let s=[],n;for(;(n=bl(d(this,se,"f"),d(this,ne,"f")))!=null;){if(n.carriage&&d(this,ne,"f")==null){k(this,ne,n.index,"f");continue}if(d(this,ne,"f")!=null&&(n.index!==d(this,ne,"f")+1||n.carriage)){s.push(co(d(this,se,"f").subarray(0,d(this,ne,"f")-1))),k(this,se,d(this,se,"f").subarray(d(this,ne,"f")),"f"),k(this,ne,null,"f");continue}let o=d(this,ne,"f")!==null?n.preceding-1:n.preceding,i=co(d(this,se,"f").subarray(0,o));s.push(i),k(this,se,d(this,se,"f").subarray(n.index),"f"),k(this,ne,null,"f")}return s}flush(){return d(this,se,"f").length?this.decode(`
@@ -32,7 +32,7 @@ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
32
32
  ]))`;continue}else if(n[u]==="$"){o+=`($|(?=[\r
33
33
  ]))`;continue}}if(s.s&&n[u]==="."){o+=a?`${n[u]}\r
34
34
  `:`[${n[u]}\r
35
- ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function Rn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(Cn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function wu(t,e){if(e.mapStrategy==="record")return Rn(t,e);let r=C(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=C(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}function Pu(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function Ou(){return{not:{}}}function ku(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Tu(t,e){if(e.target==="openApi3")return vu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in zs&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=zs[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return vu(t,e)}var vu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>C(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function Cu(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:zs[t.innerType._def.typeName],nullable:!0}:{type:[zs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=C(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function Ru(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",Do(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function Ap(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Eu(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=C(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Ap(t,e)};return r.required.length||delete r.required,r}var Su=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return C(t.innerType._def,{...e,currentPath:e.currentPath},r);let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return s?{anyOf:[{not:{}},s]}:{}};var $u=(t,e,r)=>{if(e.pipeStrategy==="input")return C(t.in._def,e,r);if(e.pipeStrategy==="output")return C(t.out._def,e,r);let s=C(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=C(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(o=>o!==void 0)}};function Mu(t,e,r){return C(t.type._def,e,r)}function Nu(t,e){let s={type:"array",uniqueItems:!0,items:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function zu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:C(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function Uu(){return{not:{}}}function ju(){return{}}var Du=(t,e,r)=>C(t.innerType._def,e,r);function C(t,e,r=!1){let s=e.seen.get(t);if(e.override){let o=e.override?.(t,e,s,r);if(o!==au)return o}if(s&&!r){let o=Ip(s,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let o=wp(t,t.typeName,e,r);return o&&Pp(t,e,o),n.jsonSchema=o,o}finally{r&&s&&e.seen.set(t,s)}}var Ip=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((s,n)=>n===0?s:bp(s)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:xp(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Lu="_x_",bp=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Lu))return t;let e=Lu;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},xp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},wp=(t,e,r,s)=>{switch(e){case E.ZodString:return Cn(t,r);case E.ZodNumber:return Ru(t,r);case E.ZodObject:return Eu(t,r);case E.ZodBigInt:return du(t,r);case E.ZodBoolean:return fu();case E.ZodDate:return Lo(t,r);case E.ZodUndefined:return Uu();case E.ZodNull:return ku(r);case E.ZodArray:return mu(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Tu(t,r);case E.ZodIntersection:return Iu(t,r);case E.ZodTuple:return zu(t,r);case E.ZodRecord:return Rn(t,r);case E.ZodLiteral:return bu(t,r);case E.ZodEnum:return Au(t);case E.ZodNativeEnum:return Pu(t);case E.ZodNullable:return Cu(t,r,s);case E.ZodOptional:return Su(t,r,s);case E.ZodMap:return wu(t,r);case E.ZodSet:return Nu(t,r);case E.ZodLazy:return C(t.getter()._def,r,s);case E.ZodPromise:return Mu(t,r,s);case E.ZodNaN:case E.ZodNever:return Ou();case E.ZodEffects:return yu(t,r,s);case E.ZodAny:return pu();case E.ZodUnknown:return ju();case E.ZodDefault:return gu(t,r,s);case E.ZodBranded:return hu(t,r,s);case E.ZodReadonly:return Du(t,r,s);case E.ZodCatch:return _u(t,r,s);case E.ZodPipeline:return $u(t,r,s);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}},Pp=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Fo=(t,e)=>{let r=cu(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=C(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(lu(r.definitions))return;let c={},u=new Set;for(let f=0;f<500;f++){let h=Object.entries(r.definitions).filter(([g])=>!u.has(g));if(h.length===0)break;for(let[g,y]of h)c[g]=C(Ns(y),{...r,currentPath:[...r.basePath,r.definitionPath,g]},!0)??{},u.add(g)}return c})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function Ku(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return De(e,[],e)}function Bo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Bo(e))return!0;for(let e of t.anyOf??[])if(Bo(e))return!0;return!1}function De(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!zt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(zt(s))for(let[g,y]of Object.entries(s))De(y,[...e,"$defs",g],r);let n=t.definitions;if(zt(n))for(let[g,y]of Object.entries(n))De(y,[...e,"definitions",g],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(zt(a)){for(let[g,y]of Object.entries(a))if(!Bo(y)&&!i.includes(g))throw new Error(`Zod field at \`${[...e,"properties",g].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([g,y])=>[g,De(y,[...e,"properties",g],r)]))}let c=t.items;zt(c)&&(t.items=De(c,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((g,y)=>De(g,[...e,"anyOf",String(y)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let g=De(f[0],[...e,"allOf","0"],r);Object.assign(t,g),delete t.allOf}else t.allOf=f.map((g,y)=>De(g,[...e,"allOf",String(y)],r));t.default===null&&delete t.default;let h=t.$ref;if(h&&kp(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);let g=Op(r,h);if(typeof g=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!zt(g))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(g)}`);return Object.assign(t,{...g,...t}),delete t.$ref,De(t,e,r)}return t}function Op(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!zt(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kp(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function vp(t,e){return Fo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Tp(t){return Ku(mi(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let s=e._zod.def;if(s.type==="union"&&"discriminator"in s&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function Cp(t){return"_zod"in t}function Fu(t,e,r){return ca({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Cp(t)?Tp(t):vp(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var Bu=["jsonSchema","functionCalling","jsonMode"];function qu(t,e){if(typeof e<"u"&&!Bu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Bu.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Rp(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Wu(t,e,r){if(fi(t))return Fu(t,e,r);if(di(t))return Rp({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Lt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>pi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function Hu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var Zu={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};var En="**REDACTED**";function ss(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Ut=class extends wi{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:t}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0,r=yi({baseURL:t?.configuration?.baseURL??(re("OPENAI_API_BASE")||re("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??re("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??re("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration,baseURL:r.baseURL},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.8")}_getReasoningParams(t){if(!Ne(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&us(t.json_schema.schema)?Wu(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=Ue({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=je(r.defaultHeaders),this.client=new T(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Mt(t)?ou(t.metadata.customTool):Hs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ja(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(rs(s)||Mt(s))return s;if(Ya(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ws(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens(ze(o))]),c=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+c,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Ga(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw ce(n)}})}get profile(){return Zu[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,s,{schema:n,name:o,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=qu(this.model,e?.method);if(a==="jsonMode"){s=Jn(n);let c=Lt(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...c}}})}else if(a==="jsonSchema"){let c=Lt(n),u={name:o??"extract",description:hi(c),schema:us(n)?n:c,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...c}}}),us(n)||Zn(n)){let f=Jn(n);s=_i.from(async h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:f.invoke(h.content))}else s=new Ai}else{let c=o??"extract",u=Lt(n),f;us(n)||Zn(n)?f={name:c,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,c=n.name):(c=n.title??c,f={name:c,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=Ii(n,c)}return bi(r,s,i)}};var Us={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Wn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",s;try{s=qn(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=qn(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Wn({dataUrl:t.url}),r=$t(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=$t(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Sn=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Zs(u,{returnId:!0}))}catch(f){i.push(Kt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let c={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:Hu(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Bs(t.content||"",t.role??"unknown")}},$n=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new ui({content:o,response_metadata:a});if(n==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new Dt({content:o,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new Hn({content:o,response_metadata:a}):n==="developer"?new Hn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new ai({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new ni({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new ii({content:o,role:n,response_metadata:a})},qo=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=li(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=$t(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Wo=({message:t,model:e})=>{let r=ze(t);if(r==="system"&&Ne(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};return ae.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Vn):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&Fs.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=qo(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},jt=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Wo({message:r});let s=ze(r);s==="system"&&Ne(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>Ls(i)?Ks(i,Us):typeof i=="object"&&i!==null&&"type"in i&&(i.type==="tool_use"||i.type==="tool_call"||i.type==="reasoning"||i.type==="reasoning_content"||i.type==="thinking")?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ae.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(Vn):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),Fs.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var Mn=class extends Ut{constructor(t,e){super(ss(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});let n={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:vn(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Ne(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=jt({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let y of i){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};let I=y.generationInfo?.completion??0;a[I]===void 0?a[I]=y:a[I]=a[I].concat(y)}let c=Object.entries(a).sort(([y],[I])=>parseInt(y,10)-parseInt(I,10)).map(([y,I])=>I),{functions:u,function_call:f}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,u,f),g=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=g,s.total_tokens=h+g,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:h}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),c&&(s.input_tokens=(s.input_tokens??0)+c),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});let g=[];for(let y of i?.choices??[]){let I={text:y.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},i)};I.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},qs(I.message)&&(I.message.usage_metadata=s),I.message=new ae(Object.fromEntries(Object.entries(I.message).filter(([x])=>!x.startsWith("lc_")))),g.push(I)}return{generations:g,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let s=jt({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o=await this.completionWithRetry(n,e),i=this.streamUsage??e.streamUsage;yield*Vs(async function*(c,u){for await(let f of c){if(u?.aborted)return;yield f}}(o,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=jt({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let c of i){if(e.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:f}=u;if(!f)continue;let h=this._convertCompletionsDeltaToBaseMessageChunk(f,c,o);o=f.role??o;let g={prompt:e.promptIndex??0,completion:u.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let y={...g};u.finish_reason!=null&&(y.finish_reason=u.finish_reason,y.system_fingerprint=c.system_fingerprint,y.model_name=c.model,y.service_tier=c.service_tier),this.logprobs&&(y.logprobs=u.logprobs);let I=new as({message:h,text:h.content,generationInfo:y});yield I,await r?.handleLLMNewToken(I.text??"",g,void 0,void 0,void 0,{chunk:I})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new as({message:new Dt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s),o=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return o&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(i){throw ce(i)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return $n({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Sn({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Nn="__openai_function_call_ids__",zn="__openai_custom_tool_call_ids__";function el(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Sp(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var ns=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},js=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],s=[],n=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),o={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(el),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Zs(c,{returnId:!0}))}catch(u){let f;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(f=u.message),s.push(Kt(c,f))}i[Nn]??={},a.id&&(i[Nn][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=eu(a);c?(r.push(c),i[zn]??={},a.id&&a.call_id&&(i[zn][a.call_id]=a.id)):s.push(Kt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=tu(a);c?r.push(c):s.push(Kt(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new ae({id:t.id,content:e,tool_calls:r,invalid_tool_calls:s,usage_metadata:ns(t.usage),additional_kwargs:i,response_metadata:o})},Ho=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},Un=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[el(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Nn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[zn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=js(t.response);if(s=ns(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=c.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,u]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:u}}}else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((f,h)=>({...f,index:h})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new as({text:e.map(c=>c.text).join(""),message:new Dt({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Zo=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=he(()=>{try{let p=ze(t);return p==="system"||p==="developer"||p==="assistant"||p==="user"?p:"assistant"}catch{return"assistant"}}),n=p=>s==="assistant"?{type:"output_text",text:p,annotations:[]}:{type:"input_text",text:p},o,i=new Set,a=new Set,c=new Map,u=new Map;function*f(){if(!o)return;let p=o.content;(typeof p=="string"&&p.length>0||Array.isArray(p)&&p.length>0)&&(yield o),o=void 0}let h=(p,A)=>{o||(o={type:"message",role:s,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[n(o.content),...p]:[...p]:o.content.push(...p)},g=p=>{if(typeof p=="string")return p;try{return JSON.stringify(p??{})}catch{return"{}"}},y=p=>{let A=he(()=>{let O=p.metadata?.detail;return O==="low"||O==="high"||O==="auto"?O:"auto"});if(p.fileId)return{type:"input_image",detail:A,file_id:p.fileId};if(p.url)return{type:"input_image",detail:A,image_url:p.url};if(p.data){let O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${p.mimeType??"image/png"};base64,${O}`}}},I=p=>{if(p.fileId){let A=On(p);return{type:"input_file",file_id:p.fileId,...A?{filename:A}:{}}}if(p.url){let A=On(p);return{...A?{filename:A}:{},type:"input_file",file_url:p.url}}if(p.data){let A=$t(p),O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_file",file_data:`data:${p.mimeType??"application/octet-stream"};base64,${O}`,filename:A}}},x=p=>{let A=he(()=>{if(Array.isArray(p.summary)){let z=p.summary?.map(N=>N?.text).filter(N=>typeof N=="string")??[];if(z.length>0)return z}return p.reasoning?[p.reasoning]:[]}),O=A.length>0?A.map(z=>({type:"summary_text",text:z})):[{type:"summary_text",text:""}];return{type:"reasoning",...p.id?{id:p.id}:{},summary:O}},_=p=>({type:"function_call",name:p.name??"",call_id:p.id??"",arguments:g(p.args)}),v=p=>{let A=g(p.output),O=p.status==="success"?"completed":p.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:p.toolCallId??"",output:A,...O?{status:O}:{}}};for(let p of t.contentBlocks)if(p.type==="text"){let A=he(()=>{if("extras"in p&&typeof p.extras=="object"&&p.extras!==null&&"phase"in p.extras)return p.extras.phase});h([n(p.text)],A)}else if(p.type!=="invalid_tool_call"){if(p.type==="reasoning")yield*f(),yield x(p);else if(p.type==="tool_call"){yield*f();let A=p.id??"";A&&(i.add(A),c.delete(A)),yield _(p)}else if(p.type==="tool_call_chunk"){if(p.id){let A=c.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),c.set(p.id,A)}}else if(p.type==="server_tool_call"){yield*f();let A=p.id??"";A&&(a.add(A),u.delete(A)),yield _(p)}else if(p.type==="server_tool_call_chunk"){if(p.id){let A=u.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),u.set(p.id,A)}}else if(p.type==="server_tool_call_result")yield*f(),yield v(p);else if(p.type!=="audio")if(p.type==="file"){let A=I(p);A&&h([A])}else if(p.type==="image"){let A=y(p);A&&h([A])}else if(p.type==="video"){let A=I(p);A&&h([A])}else p.type==="text-plain"?p.text&&h([n(p.text)]):p.type==="non_standard"&&e&&(yield*f(),yield p.value)}yield*f();for(let[p,A]of c){if(!p||i.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}for(let[p,A]of u){if(!p||a.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}}return Array.from(r())},os=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Zo(s);let o=s.additional_kwargs,i=ze(s);if(i==="system"&&Ne(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(g=>g.type==="input_image");if(u)return u;let f=a.content.find(g=>g.type==="computer_screenshot");if(f)return f;let h=a.content.find(g=>g.type==="image_url");if(h)return{type:"input_image",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(x=>"type"in x))return n?.output;let a=[],c=o?.reasoning,u=!!c?.encrypted_content;if(c&&(!e||u)){let x=Ho(c);a.push(x)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let x={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:he(()=>typeof f=="string"?f:f.flatMap(_=>{if(_.type==="text"){let v=_;return{type:"output_text",text:v.text,annotations:(v.annotations??[]).map(Sp)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:he(()=>{if(Array.isArray(f))return f.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(x)}let h=o?.[Nn],g=o?.[zn];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(x=>su(x,g)?{type:"custom_tool_call",id:"call_id"in x&&typeof x.call_id=="string"?x.call_id:g?.[x.id??""]??"",call_id:x.id??"",input:x.args.input,name:x.name}:ru(x)?{type:"computer_call",id:x.call_id,call_id:x.id??"",action:x.args.action}:{type:"function_call",name:x.name,arguments:JSON.stringify(x.args),call_id:x.id,...e?{}:{id:h?.[x.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(x=>({type:"function_call",name:x.function.name,call_id:x.id,arguments:x.function.arguments,...e?{}:{id:h?.[x.id]}})));let y=n?.output?.length?n?.output:o.tool_outputs,I=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){let x=y?.filter(_=>I.includes(_.type));x.length>0&&a.push(...x)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],c=s.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Ls(u)){if(u.type==="file"){let f=On(u);if(u.source_type==="url")return{type:"input_file",file_url:u.url,...f?{filename:f}:{}};if(u.source_type==="id")return{type:"input_file",file_id:u.id,...f?{filename:f}:{}};if(u.source_type==="base64")return{type:"input_file",file_data:`data:${u.mime_type??""};base64,${u.data}`,filename:$t(u)}}return Ks(u,Us)}return u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:he(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:he(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Vo(t,e={}){let r=e.streamUsage??!0,s=e.provider??"openai",n=new Map,o=new Map,i=0,a=!1,c,u,f,h,g=new Set,y=(_,v)=>{let p=o.get(_);if(p!==void 0)return{index:p,isNew:!1};let A=i++;return o.set(_,A),n.set(A,{...v}),{index:A,isNew:!0}},I=function*(){a||(a=!0,yield{event:"message-start",id:c})},x=function*(_){if(g.has(_))return;let v=n.get(_);v&&(g.add(_),yield{event:"content-block-finish",index:_,content:xi(v)})};for await(let _ of t){if(_.type==="response.created"){c=_.response.id,yield*I(),yield{event:"provider",provider:s,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*I();let{index:v,isNew:p}=y(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});p&&(yield{event:"content-block-start",index:v,content:{type:"text",text:""}});let A=n.get(v);A.text=(A.text??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*I();let{index:v,isNew:p}=y(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});p&&(yield{event:"content-block-start",index:v,content:{type:"reasoning",reasoning:""}});let A=n.get(v);A.reasoning=(A.reasoning??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let v=`tool:${_.output_index}`,p=_.item.type==="custom_tool_call",A=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:O,isNew:z}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index,...p?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index}}),A){let N=n.get(O);yield{event:"content-block-delta",index:O,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...N.id!=null?{id:N.id}:{},...N.name!=null?{name:N.name}:{},args:N.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*I();let{index:v,isNew:p}=y(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});p&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let A=n.get(v);A.args=(A.args??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...A.id!=null?{id:A.id}:{},...A.name!=null?{name:A.name}:{},args:A.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let v=`tool:${_.output_index}`,p=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:A,isNew:O}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index});if(O)yield{event:"content-block-start",index:A,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index}};else{let z=n.get(A);z.args=p,z.id=_.item.call_id,z.name=_.item.name}yield*x(A);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*I(),c=_.response.id,f=$p(_.response.status,_.type),h={model_provider:s,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(u=ns(_.response.usage),yield{event:"usage",usage:u});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*I(),yield{event:"provider",provider:s,name:_.type,payload:_})}a||(yield{event:"message-start"});for(let[_]of n)g.has(_)||(yield*x(_));yield{event:"message-finish",reason:f,...u?{usage:u}:{},...h?{responseMetadata:h}:{}}}function $p(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var jn=class extends Ut{constructor(t,e){super(ss(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Qa(t?.tool_choice)?t?.tool_choice:(()=>{let n=vn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:js(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Vo(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(s,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of s){if(e.signal?.aborted)return;let o=Un(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}catch(n){throw ce(n)}}async completionWithRetry(t,e){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(o){throw ce(o)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(rs(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if(Mt(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Hs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else Tn(s)&&r.push(nu(s));return r}};var Dn=class tl extends Ut{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=ss(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new jn(s),this.completions=s?.completions??new Mn(s)}_useResponsesApi(e){let r=e?.tools?.some(rs),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(Tn)||e?.tools?.some(Mt);return this.useResponsesApi||r||s||n||Ha(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamChatModelEvents(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),s);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new tl(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ln=class extends Pi{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??re("OPENAI_API_KEY");this.organization=e?.configuration?.organization??re("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Gn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let c=0;c<i.length;c+=1)n.push(a[c].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Ue({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=je(s.defaultHeaders),this.client=new T(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw ce(r)}})}};var Up=b.object({type:b.literal("screenshot")}),jp=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Dp=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Lp=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),Kp=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),Fp=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),Bp=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),qp=b.object({type:b.literal("type"),text:b.string()}),Wp=b.object({type:b.literal("wait"),duration:b.number().optional()}),Hp=b.union([Up,jp,Dp,Lp,Kp,Fp,Bp,qp,Wp]),aT=b.object({action:Hp});var Zp=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),pT=b.union([Zp]);var hT=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var Vp=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Jp=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Gp=b.object({type:b.literal("delete_file"),path:b.string()}),AT=b.union([Vp,Jp,Gp]);var nl={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Fn={default:"text-embedding-ada-002"},Go=new Map,Kn=null,em=()=>{let t=rl.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},ol=async t=>{let e=em();Go.size===0&&(Kn||(Kn=(async()=>{try{(await sl(`${e}/models`)).data.models.forEach(s=>Go.set(s.name,s))}catch(s){throw Kn=null,s}})()),await Kn);let r=Go.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},tm=async(t="default")=>await ol(nl[t]),rm=async(t="default")=>await ol(Fn[t]),sm=t=>typeof t=="string"&&t.length>0?t:void 0,nm=()=>ri(),om=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,im=t=>{let e=t?.configurable;return{conversationId:sm(e?.thread_id),abortSignal:t?.signal,requestId:nm(),requestSource:om(Qp.applicationName)}},am=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},il=async({config:t})=>{let e=rl.getDefault(),r=await Yp.getCredential(`${e.url}/sharing`);return async(s,n)=>{let{conversationId:o,abortSignal:i,requestId:a,requestSource:c}=im(t),u=new Headers(n?.headers);for(let g of[...u.keys()]){let y=g.toLowerCase();(y==="authorization"||y==="api-key"||y.startsWith("x-stainless-"))&&u.delete(g)}let f=r?.token;f&&f.length>0&&u.set("X-Esri-Authorization",`Bearer ${f}`),e.isPortal||(c&&c.length>0&&u.set("X-Esri-Request-Source",c),o&&o.length>0&&u.set("X-Esri-Conversation-Id",o),a.length>0&&u.set("X-Esri-Request-Id",a));let h=i&&n?.signal?AbortSignal.any([i,n.signal]):n?.signal??i;return(await sl(s instanceof Request?s.url:s.toString(),{body:am(n?.body),headers:Object.fromEntries(u),responseType:"native",signal:h})).data}},is=async(t={})=>{let{modelTier:e="default",config:r}=t,s=nl[e],n=await tm(e);return new Dn({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await il({config:r})}})},LC=async(t={})=>{let{tier:e="default",config:r}=t,s=Fn[e],n=await rm(e);return new Ln({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await il({config:r})},batchSize:2048,maxConcurrency:10})};var GC=ke.Root({agentExecutionContext:ke({default:Ti,reducer:ki}),currentIntent:ke({default:()=>"none",reducer:ls}),routing:ke({default:()=>({mode:"auto"}),reducer:ls}),lastExecutedAgent:ke({default:()=>"",reducer:ls}),requiresFollowUp:ke({default:()=>!0,reducer:ls}),stepCount:ke({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:ke({default:()=>"",reducer:vi})}),um=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},lm=t=>{let e=t?.configurable;return um(e)?e:void 0},cm=(t,e,r)=>{let s=t[e];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Yo=async t=>(await cm(Object.assign({"./field_descriptions_prompt.md":()=>import("./ZU2FHVNK.js"),"./intent_prompt.md":()=>import("./BL273EGZ.js"),"./layer_descriptions_prompt.md":()=>import("./LK7ZIQW6.js")}),`./${t}.md`,2)).default,pm=async t=>{let{agent:e,messages:r,config:s}=t;return{structuredResponse:(await e.invoke({messages:r},s)).structuredResponse}},mm=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(mm);var al=t=>JSON.stringify(t,null,2),dm=t=>{let e=t.map(s=>s.id),r=b.enum(e);return b.object({intent:r.nullable(),assignedTask:b.string().nullable(),requiresFollowUp:b.boolean()})},XC=async(t,e)=>{let r=lm(e);if(e?.signal?.aborted)return await st({text:"Run cancelled; skipping intent routing"},e),{...t,currentIntent:"none",finalOutputMessage:"Operation cancelled.",requiresFollowUp:!1};try{await st({text:"Asking LLM to route to an agent"},e);let s=r.services.agentRegistry?.list()??[],n=s.map(({agent:x})=>({id:x.id,name:x.name,description:x.description}));if(!n.length)return await st({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none",finalOutputMessage:"No agents registered; skipping intent detection."};let o=await Yo("intent_prompt"),i=al(n),a=dm(n),c={registeredAgents:i,priorSteps:al(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},u=await Xn.fromTemplate(o).format(c),f=Ci({model:await is({modelTier:"fast",config:e}),tools:[],systemPrompt:u,responseFormat:a,middleware:[Ri({model:await is({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),Ei({runLimit:2})]}),{structuredResponse:h}=await pm({agent:f,messages:t.agentExecutionContext.messages,config:e}),g=a.parse(h??{intent:null,assignedTask:null,requiresFollowUp:!1}),y=g.intent??"none",I={...t,currentIntent:y,requiresFollowUp:g.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:g.assignedTask??""}};if(y==="none"){let x=`I could not find an agent that can handle that request. I have access to the following agents: ${s.map(({agent:_})=>_.name).join(", ")}.
35
+ ]`;continue}o+=n[u],n[u]==="\\"?i=!0:a&&n[u]==="]"?a=!1:!a&&n[u]==="["&&(a=!0)}try{let u=new RegExp(o)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),r.source}return o};function Rn(t,e){if(e.target==="openApi3"&&t.keyType?._def.typeName===E.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((s,n)=>({...s,[n]:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",n]})??{}}),{}),additionalProperties:!1};let r={type:"object",additionalProperties:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return r;if(t.keyType?._def.typeName===E.ZodString&&t.keyType._def.checks?.length){let s=Object.entries(Cn(t.keyType._def,e)).reduce((n,[o,i])=>o==="type"?n:{...n,[o]:i},{});return{...r,propertyNames:s}}else if(t.keyType?._def.typeName===E.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};return r}function wu(t,e){if(e.mapStrategy==="record")return Rn(t,e);let r=C(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},s=C(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[r,s],minItems:2,maxItems:2}}}function Pu(t){let e=t.values,s=Object.keys(t.values).filter(o=>typeof e[e[o]]!="number").map(o=>e[o]),n=Array.from(new Set(s.map(o=>typeof o)));return{type:n.length===1?n[0]==="string"?"string":"number":["string","number"],enum:s}}function Ou(){return{not:{}}}function ku(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var zs={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Tu(t,e){if(e.target==="openApi3")return vu(t,e);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every(s=>s._def.typeName in zs&&(!s._def.checks||!s._def.checks.length))){let s=r.reduce((n,o)=>{let i=zs[o._def.typeName];return i&&!n.includes(i)?[...n,i]:n},[]);return{type:s.length>1?s:s[0]}}else if(r.every(s=>s._def.typeName==="ZodLiteral"&&!s.description)){let s=r.reduce((n,o)=>{let i=typeof o._def.value;switch(i){case"string":case"number":case"boolean":return[...n,i];case"bigint":return[...n,"integer"];case"object":if(o._def.value===null)return[...n,"null"];default:return n}},[]);if(s.length===r.length){let n=s.filter((o,i,a)=>a.indexOf(o)===i);return{type:n.length>1?n:n[0],enum:r.reduce((o,i)=>o.includes(i._def.value)?o:[...o,i._def.value],[])}}}else if(r.every(s=>s._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((s,n)=>[...s,...n._def.values.filter(o=>!s.includes(o))],[])};return vu(t,e)}var vu=(t,e)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((s,n)=>C(s._def,{...e,currentPath:[...e.currentPath,"anyOf",`${n}`]})).filter(s=>!!s&&(!e.strictUnions||typeof s=="object"&&Object.keys(s).length>0));return r.length?{anyOf:r}:void 0};function Cu(t,e,r){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:zs[t.innerType._def.typeName],nullable:!0}:{type:[zs[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let n=C(t.innerType._def,{...e,currentPath:[...e.currentPath]},r);return n&&"$ref"in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return s&&{anyOf:[s,{type:"null"}]}}function Ru(t,e){let r={type:"number"};if(!t.checks)return r;for(let s of t.checks)switch(s.kind){case"int":r.type="integer",Do(r,"type",s.message,e);break;case"min":e.target==="jsonSchema7"?s.inclusive?M(r,"minimum",s.value,s.message,e):M(r,"exclusiveMinimum",s.value,s.message,e):(s.inclusive||(r.exclusiveMinimum=!0),M(r,"minimum",s.value,s.message,e));break;case"max":e.target==="jsonSchema7"?s.inclusive?M(r,"maximum",s.value,s.message,e):M(r,"exclusiveMaximum",s.value,s.message,e):(s.inclusive||(r.exclusiveMaximum=!0),M(r,"maximum",s.value,s.message,e));break;case"multipleOf":M(r,"multipleOf",s.value,s.message,e);break}return r}function Ap(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":C(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Eu(t,e){let r={type:"object",...Object.entries(t.shape()).reduce((s,[n,o])=>{if(o===void 0||o._def===void 0)return s;let i=[...e.currentPath,"properties",n],a=C(o._def,{...e,currentPath:i,propertyPath:i});if(a===void 0)return s;if(e.openaiStrictMode&&o.isOptional()&&!o.isNullable()&&typeof o._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...s.properties,[n]:a},required:o.isOptional()&&!e.openaiStrictMode?s.required:[...s.required,n]}},{properties:{},required:[]}),additionalProperties:Ap(t,e)};return r.required.length||delete r.required,r}var Su=(t,e,r)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return C(t.innerType._def,{...e,currentPath:e.currentPath},r);let s=C(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]},r);return s?{anyOf:[{not:{}},s]}:{}};var $u=(t,e,r)=>{if(e.pipeStrategy==="input")return C(t.in._def,e,r);if(e.pipeStrategy==="output")return C(t.out._def,e,r);let s=C(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),n=C(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",s?"1":"0"]});return{allOf:[s,n].filter(o=>o!==void 0)}};function Mu(t,e,r){return C(t.type._def,e,r)}function Nu(t,e){let s={type:"array",uniqueItems:!0,items:C(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&M(s,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&M(s,"maxItems",t.maxSize.value,t.maxSize.message,e),s}function zu(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[]),additionalItems:C(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,s)=>C(r._def,{...e,currentPath:[...e.currentPath,"items",`${s}`]})).reduce((r,s)=>s===void 0?r:[...r,s],[])}}function Uu(){return{not:{}}}function ju(){return{}}var Du=(t,e,r)=>C(t.innerType._def,e,r);function C(t,e,r=!1){let s=e.seen.get(t);if(e.override){let o=e.override?.(t,e,s,r);if(o!==au)return o}if(s&&!r){let o=Ip(s,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}let n={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,n);try{let o=wp(t,t.typeName,e,r);return o&&Pp(t,e,o),n.jsonSchema=o,o}finally{r&&s&&e.seen.set(t,s)}}var Ip=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":let r=t.path.slice(e.basePath.length+1).map((s,n)=>n===0?s:bp(s)).join("_");return r!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[r]=t.def),{$ref:[...e.basePath,e.definitionPath,r].join("/")};case"relative":return{$ref:xp(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((s,n)=>e.currentPath[n]===s)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Lu="_x_",bp=t=>{if(/^[A-Za-z0-9_-]*$/.test(t)&&!t.startsWith(Lu))return t;let e=Lu;for(let r=0;r<t.length;r++)e+=t.charCodeAt(r).toString(16).padStart(4,"0");return e},xp=(t,e)=>{let r=0;for(;r<t.length&&r<e.length&&t[r]===e[r];r++);return[(t.length-r).toString(),...e.slice(r)].join("/")},wp=(t,e,r,s)=>{switch(e){case E.ZodString:return Cn(t,r);case E.ZodNumber:return Ru(t,r);case E.ZodObject:return Eu(t,r);case E.ZodBigInt:return du(t,r);case E.ZodBoolean:return fu();case E.ZodDate:return Lo(t,r);case E.ZodUndefined:return Uu();case E.ZodNull:return ku(r);case E.ZodArray:return mu(t,r);case E.ZodUnion:case E.ZodDiscriminatedUnion:return Tu(t,r);case E.ZodIntersection:return Iu(t,r);case E.ZodTuple:return zu(t,r);case E.ZodRecord:return Rn(t,r);case E.ZodLiteral:return bu(t,r);case E.ZodEnum:return Au(t);case E.ZodNativeEnum:return Pu(t);case E.ZodNullable:return Cu(t,r,s);case E.ZodOptional:return Su(t,r,s);case E.ZodMap:return wu(t,r);case E.ZodSet:return Nu(t,r);case E.ZodLazy:return C(t.getter()._def,r,s);case E.ZodPromise:return Mu(t,r,s);case E.ZodNaN:case E.ZodNever:return Ou();case E.ZodEffects:return yu(t,r,s);case E.ZodAny:return pu();case E.ZodUnknown:return ju();case E.ZodDefault:return gu(t,r,s);case E.ZodBranded:return hu(t,r,s);case E.ZodReadonly:return Du(t,r,s);case E.ZodCatch:return _u(t,r,s);case E.ZodPipeline:return $u(t,r,s);case E.ZodFunction:case E.ZodVoid:case E.ZodSymbol:return;default:return(n=>{})(e)}},Pp=(t,e,r)=>(t.description&&(r.description=t.description,e.markdownDescription&&(r.markdownDescription=t.description)),r);var Fo=(t,e)=>{let r=cu(e),s=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=C(t._def,s===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,s]},!1)??{},o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o);let i=(()=>{if(lu(r.definitions))return;let c={},u=new Set;for(let f=0;f<500;f++){let h=Object.entries(r.definitions).filter(([g])=>!u.has(g));if(h.length===0)break;for(let[g,y]of h)c[g]=C(Ns(y),{...r,currentPath:[...r.basePath,r.definitionPath,g]},!0)??{},u.add(g)}return c})(),a=s===void 0?i?{...n,[r.definitionPath]:i}:n:r.nameStrategy==="duplicate-ref"?{...n,...i||r.seenRefs.size?{[r.definitionPath]:{...i,...r.seenRefs.size?{[s]:n}:void 0}}:void 0}:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,s].join("/"),[r.definitionPath]:{...i,[s]:n}};return r.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":r.target==="jsonSchema2019-09"&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),a};function Ku(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);let e=structuredClone(t);return De(e,[],e)}function Bo(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(let e of t.oneOf??[])if(Bo(e))return!0;for(let e of t.anyOf??[])if(Bo(e))return!0;return!1}function De(t,e,r){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!zt(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);let s=t.$defs;if(zt(s))for(let[g,y]of Object.entries(s))De(y,[...e,"$defs",g],r);let n=t.definitions;if(zt(n))for(let[g,y]of Object.entries(n))De(y,[...e,"definitions",g],r);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);let i=t.required??[],a=t.properties;if(zt(a)){for(let[g,y]of Object.entries(a))if(!Bo(y)&&!i.includes(g))throw new Error(`Zod field at \`${[...e,"properties",g].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(a),t.properties=Object.fromEntries(Object.entries(a).map(([g,y])=>[g,De(y,[...e,"properties",g],r)]))}let c=t.items;zt(c)&&(t.items=De(c,[...e,"items"],r));let u=t.anyOf;Array.isArray(u)&&(t.anyOf=u.map((g,y)=>De(g,[...e,"anyOf",String(y)],r)));let f=t.allOf;if(Array.isArray(f))if(f.length===1){let g=De(f[0],[...e,"allOf","0"],r);Object.assign(t,g),delete t.allOf}else t.allOf=f.map((g,y)=>De(g,[...e,"allOf",String(y)],r));t.default===null&&delete t.default;let h=t.$ref;if(h&&kp(t,1)){if(typeof h!="string")throw new TypeError(`Received non-string $ref - ${h}; path=${e.join("/")}`);let g=Op(r,h);if(typeof g=="boolean")throw new Error(`Expected \`$ref: ${h}\` to resolve to an object schema but got boolean`);if(!zt(g))throw new Error(`Expected \`$ref: ${h}\` to resolve to an object but got ${JSON.stringify(g)}`);return Object.assign(t,{...g,...t}),delete t.$ref,De(t,e,r)}return t}function Op(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);let r=e.slice(2).split("/"),s=t;for(let n of r){if(!zt(s))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(s)}`);let o=s[n];if(o===void 0)throw new Error(`Key ${n} not found while resolving ${e}`);s=o}return s}function zt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function kp(t,e){let r=0;for(let s in t)if(r++,r>e)return!0;return!1}function vp(t,e){return Fo(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Tp(t){return Ku(mi(t,{target:"draft-7",override:({zodSchema:e,jsonSchema:r})=>{let s=e._zod.def;if(s.type==="union"&&"discriminator"in s&&Array.isArray(r.oneOf)){if(r.anyOf!==void 0)throw new Error("Zod discriminated union generated both `anyOf` and `oneOf`, which cannot be represented in an OpenAI strict schema");r.anyOf=r.oneOf,delete r.oneOf}}}))}function Cp(t){return"_zod"in t}function Fu(t,e,r){return ca({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Cp(t)?Tp(t):vp(t,{name:e})}},s=>t.parse(JSON.parse(s)))}var Bu=["jsonSchema","functionCalling","jsonMode"];function qu(t,e){if(typeof e<"u"&&!Bu.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Bu.join(", ")}`);let r=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(r&&!e)return"jsonSchema";if(!r&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function Rp(t,e){let r={...t};return Object.defineProperties(r,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),r}function Wu(t,e,r){if(fi(t))return Fu(t,e,r);if(di(t))return Rp({type:"json_schema",json_schema:{...r,name:e,strict:!0,schema:Lt(t,{cycles:"ref",reused:"ref",override(s){s.jsonSchema.title=e}})}},s=>pi(t,JSON.parse(s)));throw new Error("Unsupported schema response format")}function Hu(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){let r=e.images.filter(s=>typeof s?.image_url?.url=="string").map(s=>({type:"image",url:s.image_url.url}));return[{type:"text",text:t},...r]}return t}var Zu={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};var En="**REDACTED**";function ss(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var Ut=class extends wi{temperature;topP;frequencyPenalty;presencePenalty;n;logitBias;model="gpt-3.5-turbo";modelKwargs;stop;stopSequences;user;timeout;streaming=!1;streamUsage=!0;maxTokens;logprobs;topLogprobs;apiKey;organization;__includeRawResponse;client;clientConfig;supportsStrictToolCalling;audio;modalities;reasoning;zdrEnabled;service_tier;promptCacheKey;promptCacheRetention;verbosity;defaultOptions;_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}lc_serializable=!0;get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(t){let e=this.invocationParams(t);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:e.temperature??void 0,ls_max_tokens:e.max_tokens??void 0,ls_stop:t.stop}}_getInvocationParamsForTracing(t){let e=this.invocationParams(t);return Array.isArray(e.tools)?{...e,tools:e.tools.map(r=>{if(r?.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:e}_getCallOptionsForTracing(t,e){return Array.isArray(t.tools)?{...t,tools:t.tools.map(r=>{if(typeof r!="object"||r===null||!("type"in r)||r.type!=="mcp")return r;let s={...r};return"headers"in s&&(s.headers=En),"authorization"in s&&(s.authorization=En),s})}:t}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(t){super(t??{});let e=typeof t?.configuration?.apiKey=="string"||typeof t?.configuration?.apiKey=="function"?t?.configuration?.apiKey:void 0,r=yi({baseURL:t?.configuration?.baseURL??(re("OPENAI_API_BASE")||re("OPENAI_BASE_URL")||void 0),providerPath:"openai/v1"});this.apiKey=t?.apiKey??e??r.apiKey??re("OPENAI_API_KEY"),this.organization=t?.configuration?.organization??re("OPENAI_ORGANIZATION"),this.model=t?.model??t?.modelName??this.model,this.modelKwargs=t?.modelKwargs??{},this.timeout=t?.timeout,this.temperature=t?.temperature??this.temperature,this.topP=t?.topP??this.topP,this.frequencyPenalty=t?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=t?.presencePenalty??this.presencePenalty,this.logprobs=t?.logprobs,this.topLogprobs=t?.topLogprobs,this.n=t?.n??this.n,this.logitBias=t?.logitBias,this.stop=t?.stopSequences??t?.stop,this.stopSequences=this.stop,this.user=t?.user,this.__includeRawResponse=t?.__includeRawResponse,this.audio=t?.audio,this.modalities=t?.modalities,this.reasoning=t?.reasoning,this.maxTokens=t?.maxCompletionTokens??t?.maxTokens,this.promptCacheKey=t?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=t?.promptCacheRetention??this.promptCacheRetention,this.verbosity=t?.verbosity??this.verbosity,this.disableStreaming=t?.disableStreaming===!0,this.streaming=t?.streaming===!0,this.disableStreaming&&(this.streaming=!1),t?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=t?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration,baseURL:r.baseURL},t?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=t.supportsStrictToolCalling),t?.service_tier!==void 0&&(this.service_tier=t.service_tier),this.zdrEnabled=t?.zdrEnabled??!1,this._addVersion("@langchain/openai","1.5.8")}_getReasoningParams(t){if(!Ne(this.model))return;let e;return this.reasoning!==void 0&&(e={...e,...this.reasoning}),t?.reasoning!==void 0&&(e={...e,...t.reasoning}),t?.reasoningEffort!==void 0&&e?.effort===void 0&&(e={...e,effort:t.reasoningEffort}),e}_getResponseFormat(t){return t&&t.type==="json_schema"&&t.json_schema.schema&&us(t.json_schema.schema)?Wu(t.json_schema.schema,t.json_schema.name,{description:t.json_schema.description}):t}_combineCallOptions(t){return{...this.defaultOptions,...t??{}}}_getClientOptions(t){if(!this.client){let e=Ue({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=je(r.defaultHeaders),this.client=new T(r)}return{...this.clientConfig,...t}}_convertChatOpenAIToolToCompletionsTool(t,e){return Mt(t)?ou(t.metadata.customTool):Hs(t)?e?.strict!==void 0?{...t,function:{...t.function,strict:e.strict}}:t:Ja(t,e)}bindTools(t,e){let r;return e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:t.map(s=>{if(rs(s)||Mt(s))return s;if(Ya(s))return s.extras.providerToolDefinition;let n=this._convertChatOpenAIToolToCompletionsTool(s,{strict:r});return Ws(s)&&s.extras?.defer_loading===!0?{...n,defer_loading:!0}:n}),...e})}async stream(t,e){return super.stream(t,this._combineCallOptions(e))}async invoke(t,e){return super.invoke(t,this._combineCallOptions(e))}_combineLLMOutput(...t){return t.reduce((e,r)=>(r&&r.tokenUsage&&(e.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(t){let e=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);let n=await Promise.all(t.map(async o=>{let[i,a]=await Promise.all([this.getNumTokens(o.content),this.getNumTokens(ze(o))]),c=o.name!==void 0?s+await this.getNumTokens(o.name):0,u=i+r+a+c,f=o;if(f._getType()==="function"&&(u-=2),f.additional_kwargs?.function_call&&(u+=3),f?.additional_kwargs.function_call?.name&&(u+=await this.getNumTokens(f.additional_kwargs.function_call?.name)),f.additional_kwargs.function_call?.arguments)try{u+=await this.getNumTokens(JSON.stringify(JSON.parse(f.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(f.additional_kwargs.function_call)),u+=await this.getNumTokens(f.additional_kwargs.function_call?.arguments)}return e+=u,u}));return e+=3,{totalCount:e,countPerMessage:n}}async _getNumTokensFromGenerations(t){return(await Promise.all(t.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,r)=>e+r,0)}async _getEstimatedTokenCountFromPrompt(t,e,r){let s=(await this.getNumTokensFromMessages(t)).totalCount;if(e&&r!=="auto"){let n=Ga(e);s+=await this.getNumTokens(n),s+=9}return e&&t.find(n=>n._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}async moderateContent(t,e){let r=this._getClientOptions(e?.options),s={input:t,model:e?.model??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(s,r)}catch(n){throw ce(n)}})}get profile(){return Zu[this.model]??{}}_getStructuredOutputMethod(t){let e={...t};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(e?.method===void 0)return"jsonSchema"}else e.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return e.method}withStructuredOutput(t,e){let r,s,{schema:n,name:o,includeRaw:i}={...e,schema:t};if(e?.strict!==void 0&&e.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");let a=qu(this.model,e?.method);if(a==="jsonMode"){s=Jn(n);let c=Lt(n);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:o??"extract",...c}}})}else if(a==="jsonSchema"){let c=Lt(n),u={name:o??"extract",description:hi(c),schema:us(n)?n:c,strict:e?.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:u},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:u.name,description:u.description,...c}}}),us(n)||Zn(n)){let f=Jn(n);s=_i.from(async h=>"parsed"in h.additional_kwargs?h.additional_kwargs.parsed:f.invoke(h.content))}else s=new Ai}else{let c=o??"extract",u=Lt(n),f;us(n)||Zn(n)?f={name:c,description:u.description,parameters:u}:typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,c=n.name):(c=n.title??c,f={name:c,description:n.description??"",parameters:n}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:c}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:c,...u}},...e?.strict!==void 0?{strict:e.strict}:{}}),s=Ii(n,c)}return bi(r,s,i)}};var Us={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...t.metadata?.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){let e=Wn({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);let r=e.mime_type||t.mime_type||"",s;try{s=qn(r)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(s.type!=="audio"||s.subtype!=="wav"&&s.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:s.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=qn(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){let e=Wn({dataUrl:t.url}),r=$t(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:r}}}if(t.source_type==="base64"){let e=$t(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},Sn=({message:t,rawResponse:e,includeRawResponse:r})=>{let s=t.tool_calls,n=t.reasoning_content;switch(t.role){case"assistant":{let o=[],i=[];for(let u of s??[])try{o.push(Zs(u,{returnId:!0}))}catch(f){i.push(Kt(u,f.message))}let a={function_call:t.function_call,tool_calls:s};r!==void 0&&(a.__raw_response=e),n!==void 0&&(a.reasoning_content=n);let c={model_provider:"openai",model_name:e.model,usage:{...e.usage},...e.system_fingerprint?{system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(a.audio=t.audio),new ae({content:Hu(t.content||"",e.choices?.[0]?.message),tool_calls:o,invalid_tool_calls:i,additional_kwargs:a,response_metadata:c,id:e.id})}default:return new Bs(t.content||"",t.role??"unknown")}},$n=({delta:t,rawResponse:e,includeRawResponse:r,defaultRole:s})=>{let n=t.role??s,o=t.content??"",i;t.function_call?i={function_call:t.function_call}:t.tool_calls?i={tool_calls:t.tool_calls}:i={},r&&(i.__raw_response=e),t.reasoning_content!==void 0&&(i.reasoning_content=t.reasoning_content),t.audio&&(i.audio={...t.audio,index:e.choices[0].index});let a={model_provider:"openai",usage:{...e.usage}};if(n==="user")return new ui({content:o,response_metadata:a});if(n==="assistant"){let c=[];if(Array.isArray(t.tool_calls))for(let u of t.tool_calls)c.push({name:u.function?.name,args:u.function?.arguments,id:u.id,index:u.index,type:"tool_call_chunk"});return new Dt({content:o,tool_call_chunks:c,additional_kwargs:i,id:e.id,response_metadata:a})}else return n==="system"?new Hn({content:o,response_metadata:a}):n==="developer"?new Hn({content:o,response_metadata:a,additional_kwargs:{__openai_role__:"developer"}}):n==="function"?new ai({content:o,additional_kwargs:i,name:t.name,response_metadata:a}):n==="tool"?new ni({content:o,additional_kwargs:i,tool_call_id:t.tool_call_id,response_metadata:a}):new ii({content:o,role:n,response_metadata:a})},qo=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){let e=li(()=>{let[,r]=t.mimeType.split("/");return r==="wav"||r==="mp3"?r:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){let e=$t(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},Wo=({message:t,model:e})=>{let r=ze(t);if(r==="system"&&Ne(e)&&(r="developer"),r==="developer")return{role:"developer",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="system")return{role:"system",content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="assistant"){let n={role:"assistant",content:t.contentBlocks.filter(o=>o.type==="text")};return ae.isInstance(t)&&t.tool_calls?.length?n.tool_calls=t.tool_calls.map(Vn):t.additional_kwargs.tool_calls!=null&&(n.tool_calls=t.additional_kwargs.tool_calls),n}else{if(r==="tool"&&Fs.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(n=>n.type==="text")};if(r==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(n=>n.type==="text").join("")}}function*s(n){for(let o of n){o.type==="text"&&(yield{type:"text",text:o.text});let i=qo(o);i&&(yield i)}}return{role:"user",content:Array.from(s(t.contentBlocks))}},jt=({messages:t,model:e})=>t.flatMap(r=>{if("output_version"in r.response_metadata&&r.response_metadata?.output_version==="v1")return Wo({message:r});let s=ze(r);s==="system"&&Ne(e)&&(s="developer");let n=typeof r.content=="string"?r.content:r.content.flatMap(i=>Ls(i)?Ks(i,Us):typeof i=="object"&&i!==null&&"type"in i&&(i.type==="tool_use"||i.type==="tool_call"||i.type==="reasoning"||i.type==="reasoning_content"||i.type==="thinking")?[]:i),o={role:s,content:n};return r.name!=null&&(o.name=r.name),r.additional_kwargs.function_call!=null&&(o.function_call=r.additional_kwargs.function_call),ae.isInstance(r)&&r.tool_calls?.length?o.tool_calls=r.tool_calls.map(Vn):(r.additional_kwargs.tool_calls!=null&&(o.tool_calls=r.additional_kwargs.tool_calls),Fs.isInstance(r)&&r.tool_call_id!=null&&(o.tool_call_id=r.tool_call_id)),r.additional_kwargs.audio&&typeof r.additional_kwargs.audio=="object"&&"id"in r.additional_kwargs.audio?[o,{role:"assistant",audio:{id:r.additional_kwargs.audio.id}}]:o});var Mn=class extends Ut{constructor(t,e){super(ss(t,e))}invocationParams(t,e){let r;t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),!(this.streaming||e?.streaming)&&t?.response_format?.type==="json_schema"&&r!==!1&&(r=!0);let s={};t?.stream_options!==void 0?s={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e?.streaming)&&(s={stream_options:{include_usage:!0}});let n={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:t?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:t?.functions,function_call:t?.function_call,tools:t?.tools?.length?t.tools.map(i=>this._convertChatOpenAIToolToCompletionsTool(i,{strict:r})):void 0,tool_choice:vn(t?.tool_choice),response_format:this._getResponseFormat(t?.response_format),seed:t?.seed,...s,parallel_tool_calls:t?.parallel_tool_calls,...this.audio||t?.audio?{audio:this.audio||t?.audio}:{},...this.modalities||t?.modalities?{modalities:this.modalities||t?.modalities}:{},...this.modelKwargs,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,verbosity:t?.verbosity??this.verbosity};t?.prediction!==void 0&&(n.prediction=t.prediction),this.service_tier!==void 0&&(n.service_tier=this.service_tier),t?.service_tier!==void 0&&(n.service_tier=t.service_tier);let o=this._getReasoningParams(t);return o!==void 0&&o.effort!==void 0&&(n.reasoning_effort=o.effort),Ne(n.model)?n.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:n.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,n}async _generate(t,e,r){e.signal?.throwIfAborted();let s={},n=this.invocationParams(e),o=jt({messages:t,model:this.model});if(n.stream){let i=this._streamResponseChunks(t,e,r),a={};for await(let y of i){y.message.response_metadata={...y.generationInfo,...y.message.response_metadata};let I=y.generationInfo?.completion??0;a[I]===void 0?a[I]=y:a[I]=a[I].concat(y)}let c=Object.entries(a).sort(([y],[I])=>parseInt(y,10)-parseInt(I,10)).map(([y,I])=>I),{functions:u,function_call:f}=this.invocationParams(e),h=await this._getEstimatedTokenCountFromPrompt(t,u,f),g=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=g,s.total_tokens=h+g,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{let i=await this.completionWithRetry({...n,stream:!1,messages:o},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options}),{completion_tokens:a,prompt_tokens:c,total_tokens:u,prompt_tokens_details:f,completion_tokens_details:h}=i?.usage??{};a&&(s.output_tokens=(s.output_tokens??0)+a),c&&(s.input_tokens=(s.input_tokens??0)+c),u&&(s.total_tokens=(s.total_tokens??0)+u),(f?.audio_tokens!==null||f?.cached_tokens!==null)&&(s.input_token_details={...f?.audio_tokens!==null&&{audio:f?.audio_tokens},...f?.cached_tokens!==null&&{cache_read:f?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});let g=[];for(let y of i?.choices??[]){let I={text:y.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(y.message??{role:"assistant"},i)};I.generationInfo={...y.finish_reason?{finish_reason:y.finish_reason}:{},...y.logprobs?{logprobs:y.logprobs}:{}},qs(I.message)&&(I.message.usage_metadata=s),I.message=new ae(Object.fromEntries(Object.entries(I.message).filter(([x])=>!x.startsWith("lc_")))),g.push(I)}return{generations:g,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamChatModelEvents(t,e,r){let s=jt({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o=await this.completionWithRetry(n,e),i=this.streamUsage??e.streamUsage;yield*Vs(async function*(c,u){for await(let f of c){if(u?.aborted)return;yield f}}(o,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=jt({messages:t,model:this.model}),n={...this.invocationParams(e,{streaming:!0}),messages:s,stream:!0},o,i=await this.completionWithRetry(n,e),a;for await(let c of i){if(e.signal?.aborted)return;let u=c?.choices?.[0];if(c.usage&&(a=c.usage),!u)continue;let{delta:f}=u;if(!f)continue;let h=this._convertCompletionsDeltaToBaseMessageChunk(f,c,o);o=f.role??o;let g={prompt:e.promptIndex??0,completion:u.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}let y={...g};u.finish_reason!=null&&(y.finish_reason=u.finish_reason,y.system_fingerprint=c.system_fingerprint,y.model_name=c.model,y.service_tier=c.service_tier),this.logprobs&&(y.logprobs=u.logprobs);let I=new as({message:h,text:h.content,generationInfo:y});yield I,await r?.handleLLMNewToken(I.text??"",g,void 0,void 0,void 0,{chunk:I})}if(a){let c={...a.prompt_tokens_details?.audio_tokens!==null&&{audio:a.prompt_tokens_details?.audio_tokens},...a.prompt_tokens_details?.cached_tokens!==null&&{cache_read:a.prompt_tokens_details?.cached_tokens}},u={...a.completion_tokens_details?.audio_tokens!==null&&{audio:a.completion_tokens_details?.audio_tokens},...a.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:a.completion_tokens_details?.reasoning_tokens}},f=new as({message:new Dt({content:"",response_metadata:{usage:{...a}},usage_metadata:{input_tokens:a.prompt_tokens,output_tokens:a.completion_tokens,total_tokens:a.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(u).length>0&&{output_token_details:u}}}),text:""});yield f,await r?.handleLLMNewToken(f.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:f})}if(e.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s),o=t.response_format&&t.response_format.type==="json_schema";return this.caller.callWithOptions({maxRetries:r},async()=>{try{return o&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(i){throw ce(i)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,r){return $n({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:r})}_convertCompletionsMessageToBaseMessage(t,e){return Sn({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};var Nn="__openai_function_call_ids__",zn="__openai_custom_tool_call_ids__";function el(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function Sp(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){let e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}var ns=t=>{let e={...t?.input_tokens_details?.cached_tokens!=null&&{cache_read:t?.input_tokens_details?.cached_tokens}},r={...t?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:t?.output_tokens_details?.reasoning_tokens}};return{input_tokens:t?.input_tokens??0,output_tokens:t?.output_tokens??0,total_tokens:t?.total_tokens??0,input_token_details:e,output_token_details:r}},js=t=>{if(t.error){let a=new Error(t.error.message);throw a.name=t.error.code,a}let e=[],r=[],s=[],n=t.output.map(a=>{if(a.type==="function_call"&&"parsed_arguments"in a){let c={...a};return delete c.parsed_arguments,c}return a}),o={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:n,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},i={};for(let a of t.output)if(a.type==="message")e.push(...a.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(i.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations.map(el),...a.phase!==null?{phase:a.phase}:{}}):c.type==="refusal"?(i.refusal=c.refusal,[]):c));else if(a.type==="function_call"){let c={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(Zs(c,{returnId:!0}))}catch(u){let f;typeof u=="object"&&u!=null&&"message"in u&&typeof u.message=="string"&&(f=u.message),s.push(Kt(c,f))}i[Nn]??={},a.id&&(i[Nn][a.call_id]=a.id)}else if(a.type==="reasoning"){i.reasoning=a;let c=a.summary?.map(u=>u.text).filter(Boolean).join("");c&&e.push({type:"reasoning",reasoning:c})}else if(a.type==="custom_tool_call"){let c=eu(a);c?(r.push(c),i[zn]??={},a.id&&a.call_id&&(i[zn][a.call_id]=a.id)):s.push(Kt(a,"Malformed custom tool call"))}else if(a.type==="computer_call"){let c=tu(a);c?r.push(c):s.push(Kt(a,"Malformed computer call"))}else a.type==="image_generation_call"?(a.result&&e.push({type:"image",mimeType:"image/png",data:a.result,id:a.id,metadata:{status:a.status}}),i.tool_outputs??=[],i.tool_outputs.push(a)):(i.tool_outputs??=[],i.tool_outputs.push(a));return new ae({id:t.id,content:e,tool_calls:r,invalid_tool_calls:s,usage_metadata:ns(t.usage),additional_kwargs:i,response_metadata:o})},Ho=t=>{let e=(t.summary.length>1?t.summary.reduce((r,s)=>{let n=r[r.length-1];return n.index===s.index?n.text+=s.text:r.push(s),r},[{...t.summary[0]}]):t.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...t,summary:e}},Un=t=>{let e=[],r={},s,n=[],o={model_provider:"openai"},i={},a;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[el(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){let c="phase"in t.item?t.item.phase:void 0;c&&e.push({type:"text",text:"",phase:c,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")n.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),i[Nn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")n.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),i[zn]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")n.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),i.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))i.tool_outputs=[t.item];else if(t.type==="response.created")a=t.response.id,o.id=t.response.id,o.model_name=t.response.model,o.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){a=t.response.id;let c=js(t.response);if(s=ns(t.response.usage),t.response.text?.format?.type==="json_schema"&&c.text)try{i.parsed??=JSON.parse(c.text)}catch{}for(let[u,f]of Object.entries(t.response))u!=="id"&&(u==="output"?o[u]=c.response_metadata.output:o[u]=f)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")n.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){let[,c,u]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];r={tool_outputs:{id:t.item_id,type:c,status:u}}}else if(t.type==="response.refusal.done")i.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){let c=t.item.summary?t.item.summary.map((f,h)=>({...f,index:h})):void 0;i.reasoning={id:t.item.id,type:t.item.type,...c?{summary:c}:{}};let u=t.item.summary?.map(f=>f.text).filter(Boolean).join("");u&&e.push({type:"reasoning",reasoning:u})}else if(t.type==="response.reasoning_summary_part.added")i.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")i.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new as({text:e.map(c=>c.text).join(""),message:new Dt({id:a,content:e,tool_call_chunks:n,usage_metadata:s,additional_kwargs:i,response_metadata:o}),generationInfo:r})},Zo=t=>{let e=ae.isInstance(t)&&t.response_metadata?.model_provider==="openai";function*r(){let s=he(()=>{try{let p=ze(t);return p==="system"||p==="developer"||p==="assistant"||p==="user"?p:"assistant"}catch{return"assistant"}}),n=p=>s==="assistant"?{type:"output_text",text:p,annotations:[]}:{type:"input_text",text:p},o,i=new Set,a=new Set,c=new Map,u=new Map;function*f(){if(!o)return;let p=o.content;(typeof p=="string"&&p.length>0||Array.isArray(p)&&p.length>0)&&(yield o),o=void 0}let h=(p,A)=>{o||(o={type:"message",role:s,content:[],...A?{phase:A}:{}}),typeof o.content=="string"?o.content=o.content.length>0?[n(o.content),...p]:[...p]:o.content.push(...p)},g=p=>{if(typeof p=="string")return p;try{return JSON.stringify(p??{})}catch{return"{}"}},y=p=>{let A=he(()=>{let O=p.metadata?.detail;return O==="low"||O==="high"||O==="auto"?O:"auto"});if(p.fileId)return{type:"input_image",detail:A,file_id:p.fileId};if(p.url)return{type:"input_image",detail:A,image_url:p.url};if(p.data){let O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_image",detail:A,image_url:`data:${p.mimeType??"image/png"};base64,${O}`}}},I=p=>{if(p.fileId){let A=On(p);return{type:"input_file",file_id:p.fileId,...A?{filename:A}:{}}}if(p.url){let A=On(p);return{...A?{filename:A}:{},type:"input_file",file_url:p.url}}if(p.data){let A=$t(p),O=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_file",file_data:`data:${p.mimeType??"application/octet-stream"};base64,${O}`,filename:A}}},x=p=>{let A=he(()=>{if(Array.isArray(p.summary)){let z=p.summary?.map(N=>N?.text).filter(N=>typeof N=="string")??[];if(z.length>0)return z}return p.reasoning?[p.reasoning]:[]}),O=A.length>0?A.map(z=>({type:"summary_text",text:z})):[{type:"summary_text",text:""}];return{type:"reasoning",...p.id?{id:p.id}:{},summary:O}},_=p=>({type:"function_call",name:p.name??"",call_id:p.id??"",arguments:g(p.args)}),v=p=>{let A=g(p.output),O=p.status==="success"?"completed":p.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:p.toolCallId??"",output:A,...O?{status:O}:{}}};for(let p of t.contentBlocks)if(p.type==="text"){let A=he(()=>{if("extras"in p&&typeof p.extras=="object"&&p.extras!==null&&"phase"in p.extras)return p.extras.phase});h([n(p.text)],A)}else if(p.type!=="invalid_tool_call"){if(p.type==="reasoning")yield*f(),yield x(p);else if(p.type==="tool_call"){yield*f();let A=p.id??"";A&&(i.add(A),c.delete(A)),yield _(p)}else if(p.type==="tool_call_chunk"){if(p.id){let A=c.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),c.set(p.id,A)}}else if(p.type==="server_tool_call"){yield*f();let A=p.id??"";A&&(a.add(A),u.delete(A)),yield _(p)}else if(p.type==="server_tool_call_chunk"){if(p.id){let A=u.get(p.id)??{name:p.name,args:[]};p.name&&(A.name=p.name),p.args&&A.args.push(p.args),u.set(p.id,A)}}else if(p.type==="server_tool_call_result")yield*f(),yield v(p);else if(p.type!=="audio")if(p.type==="file"){let A=I(p);A&&h([A])}else if(p.type==="image"){let A=y(p);A&&h([A])}else if(p.type==="video"){let A=I(p);A&&h([A])}else p.type==="text-plain"?p.text&&h([n(p.text)]):p.type==="non_standard"&&e&&(yield*f(),yield p.value)}yield*f();for(let[p,A]of c){if(!p||i.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}for(let[p,A]of u){if(!p||a.has(p))continue;let O=A.args.join("");!A.name&&!O||(yield{type:"function_call",call_id:p,name:A.name??"",arguments:O})}}return Array.from(r())},os=({messages:t,zdrEnabled:e,model:r})=>t.flatMap(s=>{let n=s.response_metadata;if(n?.output_version==="v1")return Zo(s);let o=s.additional_kwargs,i=ze(s);if(i==="system"&&Ne(r)&&(i="developer"),i==="function")throw new Error("Function messages are not supported in Responses API");if(i==="tool"){let a=s;if(o?.type==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"input_image",image_url:a.content};if(Array.isArray(a.content)){let u=a.content.find(g=>g.type==="input_image");if(u)return u;let f=a.content.find(g=>g.type==="computer_screenshot");if(f)return f;let h=a.content.find(g=>g.type==="image_url");if(h)return{type:"input_image",image_url:typeof h.image_url=="string"?h.image_url:h.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id};if(a.additional_kwargs?.customTool)return{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content};let c=Array.isArray(a.content)&&a.content.every(u=>typeof u=="object"&&u!==null&&"type"in u&&(u.type==="input_file"||u.type==="input_image"||u.type==="input_text"));return{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:c?a.content:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(i==="assistant"){if(!e&&n?.output!=null&&Array.isArray(n?.output)&&n?.output.length>0&&n?.output.every(x=>"type"in x))return n?.output;let a=[],c=o?.reasoning,u=!!c?.encrypted_content;if(c&&(!e||u)){let x=Ho(c);a.push(x)}let{content:f}=s;if(o?.refusal&&(typeof f=="string"&&(f=[{type:"output_text",text:f,annotations:[]}]),f=[...f,{type:"refusal",refusal:o.refusal}]),typeof f=="string"||f.length>0){let x={type:"message",role:"assistant",...s.id&&!e&&s.id.startsWith("msg_")?{id:s.id}:{},content:he(()=>typeof f=="string"?f:f.flatMap(_=>{if(_.type==="text"){let v=_;return{type:"output_text",text:v.text,annotations:(v.annotations??[]).map(Sp)}}return _.type==="output_text"||_.type==="refusal"?_:[]})),phase:he(()=>{if(Array.isArray(f))return f.find(_=>"phase"in _&&typeof _.phase=="string")?.phase})};a.push(x)}let h=o?.[Nn],g=o?.[zn];ae.isInstance(s)&&s.tool_calls?.length?a.push(...s.tool_calls.map(x=>su(x,g)?{type:"custom_tool_call",id:"call_id"in x&&typeof x.call_id=="string"?x.call_id:g?.[x.id??""]??"",call_id:x.id??"",input:x.args.input,name:x.name}:ru(x)?{type:"computer_call",id:x.call_id,call_id:x.id??"",action:x.args.action}:{type:"function_call",name:x.name,arguments:JSON.stringify(x.args),call_id:x.id,...e?{}:{id:h?.[x.id]}})):o?.tool_calls&&a.push(...o.tool_calls.map(x=>({type:"function_call",name:x.function.name,call_id:x.id,arguments:x.function.arguments,...e?{}:{id:h?.[x.id]}})));let y=n?.output?.length?n?.output:o.tool_outputs,I=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){let x=y?.filter(_=>I.includes(_.type));x.length>0&&a.push(...x)}return a}if(i==="user"||i==="system"||i==="developer"){if(typeof s.content=="string")return{type:"message",role:i,content:s.content};let a=[],c=s.content.flatMap(u=>{if(u.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:u.approval_request_id,approve:u.approve}),Ls(u)){if(u.type==="file"){let f=On(u);if(u.source_type==="url")return{type:"input_file",file_url:u.url,...f?{filename:f}:{}};if(u.source_type==="id")return{type:"input_file",file_id:u.id,...f?{filename:f}:{}};if(u.source_type==="base64")return{type:"input_file",file_data:`data:${u.mime_type??""};base64,${u.data}`,filename:$t(u)}}return Ks(u,Us)}return u.type==="text"?{type:"input_text",text:u.text}:u.type==="image_url"?{type:"input_image",image_url:he(()=>{if(typeof u.image_url=="string")return u.image_url;if(typeof u.image_url=="object"&&u.image_url!==null&&"url"in u.image_url)return u.image_url.url}),detail:he(()=>{if(typeof u.image_url=="string")return"auto";if(typeof u.image_url=="object"&&u.image_url!==null&&"detail"in u.image_url)return u.image_url.detail})}:u.type==="input_text"||u.type==="input_image"||u.type==="input_file"?u:[]});return c.length>0&&a.push({type:"message",role:i,content:c}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${i}`),[]});async function*Vo(t,e={}){let r=e.streamUsage??!0,s=e.provider??"openai",n=new Map,o=new Map,i=0,a=!1,c,u,f,h,g=new Set,y=(_,v)=>{let p=o.get(_);if(p!==void 0)return{index:p,isNew:!1};let A=i++;return o.set(_,A),n.set(A,{...v}),{index:A,isNew:!0}},I=function*(){a||(a=!0,yield{event:"message-start",id:c})},x=function*(_){if(g.has(_))return;let v=n.get(_);v&&(g.add(_),yield{event:"content-block-finish",index:_,content:xi(v)})};for await(let _ of t){if(_.type==="response.created"){c=_.response.id,yield*I(),yield{event:"provider",provider:s,name:"response.created",payload:{model:_.response.model,id:_.response.id}};continue}if(_.type==="response.output_text.delta"){yield*I();let{index:v,isNew:p}=y(`text:${_.output_index}:${_.content_index}`,{type:"text",text:""});p&&(yield{event:"content-block-start",index:v,content:{type:"text",text:""}});let A=n.get(v);A.text=(A.text??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"text-delta",text:_.delta}};continue}if(_.type==="response.reasoning_summary_text.delta"){yield*I();let{index:v,isNew:p}=y(`reasoning:${_.output_index}:${_.summary_index}`,{type:"reasoning",reasoning:""});p&&(yield{event:"content-block-start",index:v,content:{type:"reasoning",reasoning:""}});let A=n.get(v);A.reasoning=(A.reasoning??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"reasoning-delta",reasoning:_.delta}};continue}if(_.type==="response.output_item.added"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let v=`tool:${_.output_index}`,p=_.item.type==="custom_tool_call",A=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:O,isNew:z}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index,...p?{isCustomTool:!0}:{}});if(z&&(yield{event:"content-block-start",index:O,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:A,index:_.output_index}}),A){let N=n.get(O);yield{event:"content-block-delta",index:O,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...N.id!=null?{id:N.id}:{},...N.name!=null?{name:N.name}:{},args:N.args}}}}continue}if(_.type==="response.function_call_arguments.delta"||_.type==="response.custom_tool_call_input.delta"){yield*I();let{index:v,isNew:p}=y(`tool:${_.output_index}`,{type:"tool_call_chunk",args:"",index:_.output_index,..._.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});p&&(yield{event:"content-block-start",index:v,content:{type:"tool_call_chunk",args:"",index:_.output_index}});let A=n.get(v);A.args=(A.args??"")+_.delta,yield{event:"content-block-delta",index:v,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...A.id!=null?{id:A.id}:{},...A.name!=null?{name:A.name}:{},args:A.args}}};continue}if(_.type==="response.output_item.done"&&(_.item.type==="function_call"||_.item.type==="custom_tool_call")){yield*I();let v=`tool:${_.output_index}`,p=_.item.type==="function_call"?_.item.arguments??"":_.item.input??"",{index:A,isNew:O}=y(v,{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index});if(O)yield{event:"content-block-start",index:A,content:{type:"tool_call_chunk",id:_.item.call_id,name:_.item.name,args:p,index:_.output_index}};else{let z=n.get(A);z.args=p,z.id=_.item.call_id,z.name=_.item.name}yield*x(A);continue}if(_.type==="response.completed"||_.type==="response.incomplete"){yield*I(),c=_.response.id,f=$p(_.response.status,_.type),h={model_provider:s,id:_.response.id,model:_.response.model,status:_.response.status},r&&_.response.usage&&(u=ns(_.response.usage),yield{event:"usage",usage:u});continue}_.type!=="response.image_generation_call.partial_image"&&(yield*I(),yield{event:"provider",provider:s,name:_.type,payload:_})}a||(yield{event:"message-start"});for(let[_]of n)g.has(_)||(yield*x(_));yield{event:"message-finish",reason:f,...u?{usage:u}:{},...h?{responseMetadata:h}:{}}}function $p(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var jn=class extends Ut{constructor(t,e){super(ss(t,e))}invocationParams(t){let e;t?.strict!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);let r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t?.previous_response_id,truncation:t?.truncation,include:t?.include,tools:t?.tools?.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:Qa(t?.tool_choice)?t?.tool_choice:(()=>{let n=vn(t?.tool_choice);if(typeof n=="object"&&"type"in n){if(n.type==="function")return{type:"function",name:n.function.name};if(n.type==="allowed_tools")return{type:"allowed_tools",mode:n.allowed_tools.mode,tools:n.allowed_tools.tools};if(n.type==="custom")return{type:"custom",name:n.custom.name}}})(),text:(()=>{if(t?.text)return t.text;let n=this._getResponseFormat(t?.response_format);return n?.type==="json_schema"?n.json_schema.schema!=null?{format:{type:"json_schema",schema:n.json_schema.schema,description:n.json_schema.description,name:n.json_schema.name,strict:n.json_schema.strict},verbosity:t?.verbosity}:void 0:{format:n,verbosity:t?.verbosity}})(),parallel_tool_calls:t?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:t?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:t?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(t);return s!==void 0&&(r.reasoning=s),r}async _generate(t,e,r){e.signal?.throwIfAborted();let s=this.invocationParams(e);if(s.stream){let n=this._streamResponseChunks(t,e,r),o;for await(let i of n)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},o=o?.concat(i)??i;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:o?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...s,stream:!1},{signal:e?.signal,maxRetries:e?.maxRetries,...e?.options});return{generations:[{text:n.output_text,message:js(n)}],llmOutput:{id:n.id,estimatedTokenUsage:n.usage?{promptTokens:n.usage.input_tokens,completionTokens:n.usage.output_tokens,totalTokens:n.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),n=this.streamUsage??e.streamUsage;yield*Vo(async function*(i,a){for await(let c of i){if(a?.aborted)return;yield c}}(s,e.signal),{streamUsage:n??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,r){let s=await this.completionWithRetry({...this.invocationParams(e),input:os({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(let n of s){if(e.signal?.aborted)return;let o=Un(n);o!=null&&(yield o,await r?.handleLLMNewToken(o.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:o}))}}catch(n){throw ce(n)}}async completionWithRetry(t,e){let{maxRetries:r,...s}=e??{},n=this._getClientOptions(s);return this.caller.callWithOptions({maxRetries:r},async()=>{try{return t.text?.format?.type==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(o){throw ce(o)}})}_reduceChatOpenAITools(t,e){let r=[];for(let s of t)if(rs(s))s.type==="image_generation"&&e?.stream&&(s.partial_images=1),r.push(s);else if(Mt(s)){let n=s.metadata.customTool;r.push({type:"custom",name:n.name,description:n.description,format:n.format})}else if(Hs(s)){let n={};for(let[o,i]of Object.entries(s))o!=="type"&&o!=="function"&&(n[o]=i);r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:e?.strict??null,...n})}else Tn(s)&&r.push(nu(s));return r}};var Dn=class tl extends Ut{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}fields;constructor(e,r){let s=ss(e,r);super(s),this.fields=s,this.useResponsesApi=s?.useResponsesApi??!1,this.responses=s?.responses??new jn(s),this.completions=s?.completions??new Mn(s)}_useResponsesApi(e){let r=e?.tools?.some(rs),s=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,n=e?.tools?.some(Tn)||e?.tools?.some(Mt);return this.useResponsesApi||r||s||n||Ha(this.model)}getLsParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(e){let r=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(e,r,s){return this._useResponsesApi(r)?this.responses._generate(e,r,s):this.completions._generate(e,r,s)}async*_streamChatModelEvents(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(e,this._combineCallOptions(r),s);return}yield*this.completions._streamChatModelEvents(e,this._combineCallOptions(r),s)}async*_streamResponseChunks(e,r,s){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(r),s);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(r),s)}withConfig(e){let r=new tl(this.fields);return r.defaultOptions={...this.defaultOptions,...e},r}};var Ln=class extends Pi{model="text-embedding-ada-002";modelName;batchSize=512;stripNewLines=!0;dimensions;timeout;organization;encodingFormat;client;clientConfig;apiKey;constructor(t){let e={maxConcurrency:2,...t};super(e);let r=e?.apiKey??e?.openAIApiKey??re("OPENAI_API_KEY");this.organization=e?.configuration?.organization??re("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelName=this.model,this.batchSize=e?.batchSize??this.batchSize,this.stripNewLines=e?.stripNewLines??this.stripNewLines,this.timeout=e?.timeout,this.dimensions=e?.dimensions,this.encodingFormat=e?.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...t?.configuration}}async embedDocuments(t){let e=Gn(this.stripNewLines?t.map(o=>o.replace(/\n/g," ")):t,this.batchSize),r=e.map(o=>{let i={model:this.model,input:o};return this.dimensions&&(i.dimensions=this.dimensions),this.encodingFormat&&(i.encoding_format=this.encodingFormat),this.embeddingWithRetry(i)}),s=await Promise.all(r),n=[];for(let o=0;o<s.length;o+=1){let i=e[o],{data:a}=s[o];for(let c=0;c<i.length;c+=1)n.push(a[c].embedding)}return n}async embedQuery(t){let e={model:this.model,input:this.stripNewLines?t.replace(/\n/g," "):t};this.dimensions&&(e.dimensions=this.dimensions),this.encodingFormat&&(e.encoding_format=this.encodingFormat);let{data:r}=await this.embeddingWithRetry(e);return r[0].embedding}async embeddingWithRetry(t){if(!this.client){let r=Ue({baseURL:this.clientConfig.baseURL}),s={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};s.baseURL||delete s.baseURL,s.defaultHeaders=je(s.defaultHeaders),this.client=new T(s)}let e={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(t,e)}catch(r){throw ce(r)}})}};var Up=b.object({type:b.literal("screenshot")}),jp=b.object({type:b.literal("click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Dp=b.object({type:b.literal("double_click"),x:b.number(),y:b.number(),button:b.enum(["left","right","wheel","back","forward"]).default("left")}),Lp=b.object({type:b.literal("drag"),path:b.array(b.object({x:b.number(),y:b.number()}))}),Kp=b.object({type:b.literal("keypress"),keys:b.array(b.string())}),Fp=b.object({type:b.literal("move"),x:b.number(),y:b.number()}),Bp=b.object({type:b.literal("scroll"),x:b.number(),y:b.number(),scroll_x:b.number(),scroll_y:b.number()}),qp=b.object({type:b.literal("type"),text:b.string()}),Wp=b.object({type:b.literal("wait"),duration:b.number().optional()}),Hp=b.union([Up,jp,Dp,Lp,Kp,Fp,Bp,qp,Wp]),aT=b.object({action:Hp});var Zp=b.object({type:b.literal("exec"),command:b.array(b.string()),env:b.record(b.string(),b.string()).optional(),working_directory:b.string().optional(),timeout_ms:b.number().optional(),user:b.string().optional()}),pT=b.union([Zp]);var hT=b.object({commands:b.array(b.string()).describe("Array of shell commands to execute"),timeout_ms:b.number().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:b.number().optional().describe("Optional maximum number of characters to return from each command")});var Vp=b.object({type:b.literal("create_file"),path:b.string(),diff:b.string()}),Jp=b.object({type:b.literal("update_file"),path:b.string(),diff:b.string()}),Gp=b.object({type:b.literal("delete_file"),path:b.string()}),AT=b.union([Vp,Jp,Gp]);var nl={advanced:"gpt-5.6-sol",default:"gpt-5.6-terra",fast:"gpt-5.6-luna"},Fn={default:"text-embedding-ada-002"},Go=new Map,Kn=null,em=()=>{let t=rl.getDefault().helperServices;if(!t?.aiModels?.url)throw new Error("AI Models Service URL is not defined in the portal's helper services.");return t.aiModels.url},ol=async t=>{let e=em();Go.size===0&&(Kn||(Kn=(async()=>{try{(await sl(`${e}/models`)).data.models.forEach(s=>Go.set(s.name,s))}catch(s){throw Kn=null,s}})()),await Kn);let r=Go.get(t);if(!r)throw new Error(`Model '${t}' is not available in the discovery service.`);return r.endpoint},tm=async(t="default")=>await ol(nl[t]),rm=async(t="default")=>await ol(Fn[t]),sm=t=>typeof t=="string"&&t.length>0?t:void 0,nm=()=>ri(),om=t=>typeof t!="string"||t.trim().length===0?"MapsSDK":`MapsSDK - ${t.trim()}`,im=t=>{let e=t?.configurable;return{conversationId:sm(e?.thread_id),abortSignal:t?.signal,requestId:nm(),requestSource:om(Qp.applicationName)}},am=t=>{if(t==null||typeof t=="string"||t instanceof FormData||t instanceof HTMLFormElement)return t;if(t instanceof URLSearchParams)return t.toString();throw new TypeError(`Unsupported request body type: ${Object.prototype.toString.call(t)}`)},il=async({config:t})=>{let e=rl.getDefault(),r=await Yp.getCredential(`${e.url}/sharing`);return async(s,n)=>{let{conversationId:o,abortSignal:i,requestId:a,requestSource:c}=im(t),u=new Headers(n?.headers);for(let g of[...u.keys()]){let y=g.toLowerCase();(y==="authorization"||y==="api-key"||y.startsWith("x-stainless-"))&&u.delete(g)}let f=r?.token;f&&f.length>0&&u.set("X-Esri-Authorization",`Bearer ${f}`),e.isPortal||(c&&c.length>0&&u.set("X-Esri-Request-Source",c),o&&o.length>0&&u.set("X-Esri-Conversation-Id",o),a.length>0&&u.set("X-Esri-Request-Id",a));let h=i&&n?.signal?AbortSignal.any([i,n.signal]):n?.signal??i;return(await sl(s instanceof Request?s.url:s.toString(),{body:am(n?.body),headers:Object.fromEntries(u),responseType:"native",signal:h})).data}},is=async(t={})=>{let{modelTier:e="default",config:r}=t,s=nl[e],n=await tm(e);return new Dn({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await il({config:r})}})},LC=async(t={})=>{let{tier:e="default",config:r}=t,s=Fn[e],n=await rm(e);return new Ln({modelName:s,apiKey:"dummy-key",configuration:{baseURL:n,fetch:await il({config:r})},batchSize:2048,maxConcurrency:10})};var GC=ke.Root({agentExecutionContext:ke({default:Ti,reducer:ki}),currentIntent:ke({default:()=>"none",reducer:ls}),routing:ke({default:()=>({mode:"auto"}),reducer:ls}),lastExecutedAgent:ke({default:()=>"",reducer:ls}),requiresFollowUp:ke({default:()=>!0,reducer:ls}),stepCount:ke({default:()=>0,reducer:(t,e)=>e??t+1}),finalOutputMessage:ke({default:()=>"",reducer:vi})}),um=t=>{if(!t||typeof t!="object"||!("services"in t))return!1;let e=t.services;return!!e&&typeof e=="object"&&"agentRegistry"in e},lm=t=>{let e=t?.configurable;return um(e)?e:void 0},cm=(t,e,r)=>{let s=t[e];return s?typeof s=="function"?s():Promise.resolve(s):new Promise((n,o)=>{(typeof queueMicrotask=="function"?queueMicrotask:setTimeout)(o.bind(null,new Error("Unknown variable dynamic import: "+e+(e.split("/").length!==r?". Note that variables only represent file names one level deep.":""))))})},Yo=async t=>(await cm(Object.assign({"./field_descriptions_prompt.md":()=>import("./FPH52WOH.js"),"./intent_prompt.md":()=>import("./HMMYCSOK.js"),"./layer_descriptions_prompt.md":()=>import("./L3BTURBA.js")}),`./${t}.md`,2)).default,pm=async t=>{let{agent:e,messages:r,config:s}=t;return{structuredResponse:(await e.invoke({messages:r},s)).structuredResponse}},mm=b.object({id:b.string().min(1),name:b.string().min(1),description:b.string().min(1)});b.array(mm);var al=t=>JSON.stringify(t,null,2),dm=t=>{let e=t.map(s=>s.id),r=b.enum(e);return b.object({intent:r.nullable(),assignedTask:b.string().nullable(),requiresFollowUp:b.boolean()})},XC=async(t,e)=>{let r=lm(e);if(e?.signal?.aborted)return await st({text:"Run cancelled; skipping intent routing"},e),{...t,currentIntent:"none",finalOutputMessage:"Operation cancelled.",requiresFollowUp:!1};try{await st({text:"Asking LLM to route to an agent"},e);let s=r.services.agentRegistry?.list()??[],n=s.map(({agent:x})=>({id:x.id,name:x.name,description:x.description}));if(!n.length)return await st({text:"No agents registered; skipping intent detection"},e),{...t,currentIntent:"none",finalOutputMessage:"No agents registered; skipping intent detection."};let o=await Yo("intent_prompt"),i=al(n),a=dm(n),c={registeredAgents:i,priorSteps:al(t.agentExecutionContext.priorSteps),userRequest:t.agentExecutionContext.userRequest},u=await Xn.fromTemplate(o).format(c),f=Ci({model:await is({modelTier:"fast",config:e}),tools:[],systemPrompt:u,responseFormat:a,middleware:[Ri({model:await is({modelTier:"fast",config:e}),trigger:{tokens:4e3},keep:{messages:6}}),Ei({runLimit:2})]}),{structuredResponse:h}=await pm({agent:f,messages:t.agentExecutionContext.messages,config:e}),g=a.parse(h??{intent:null,assignedTask:null,requiresFollowUp:!1}),y=g.intent??"none",I={...t,currentIntent:y,requiresFollowUp:g.requiresFollowUp,agentExecutionContext:{...t.agentExecutionContext,assignedTask:g.assignedTask??""}};if(y==="none"){let x=`I could not find an agent that can handle that request. I have access to the following agents: ${s.map(({agent:_})=>_.name).join(", ")}.
36
36
 
37
37
  Please ask a question that can be answered by one of these agents.`;return await st({text:"LLM did not identify a clear intent."},e),{...t,currentIntent:y,requiresFollowUp:!1,finalOutputMessage:x,agentExecutionContext:{...t.agentExecutionContext,assignedTask:"",messages:[...t.agentExecutionContext.messages,new ae(x)],priorSteps:[...t.agentExecutionContext.priorSteps??[],{agentId:"no-intent-router",assignedTask:t.agentExecutionContext.userRequest,summary:"No matching agent found; asked user to rephrase.",status:"failed"}]}}}return await st({text:`Agent picked: ${y}
38
38
  Task Assigned: ${g.assignedTask??""}