@mcp-use/inspector 1.0.0-canary.8 → 1.0.0

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 (246) hide show
  1. package/dist/cdn/inspector.css +1 -1
  2. package/dist/cdn/inspector.js +81264 -80633
  3. package/dist/client/hooks/useMCPPrompts.d.ts +3 -3
  4. package/dist/client/index.js +13657 -775
  5. package/dist/web/assets/browser-BwHKNEau.js +380 -0
  6. package/dist/web/assets/chunk-BBSBHVGK-D4wCPq_w.js +1 -0
  7. package/dist/web/assets/{chunk-KJ5RBDDO-DJkMH4KI.js → chunk-ECXMLUNG-CSRGaMIB.js} +1 -1
  8. package/dist/web/assets/chunk-JU7W27UC-CMTI_w7A.js +1 -0
  9. package/dist/web/assets/{chunk-QWQYAQCK-CyFuZlX8.js → chunk-QWQYAQCK-BR4V0xsV.js} +1 -1
  10. package/dist/web/assets/{chunk-RPN2XO5I-Boiv0wCv.js → chunk-RPN2XO5I-Cr13Miz-.js} +1 -1
  11. package/dist/web/assets/{chunk-UJPHRNQP-C81GjauI.js → chunk-UJPHRNQP-B14ZPq5a.js} +1 -1
  12. package/dist/web/assets/chunk_array-Bw1lTtex.js +1 -0
  13. package/dist/web/assets/{client-MLH2Q2DK-UzuK4Kji.js → client-2BTCLEUX-BhvJZmo-.js} +3 -3
  14. package/dist/web/assets/client-z1GrRUEs.js +68 -0
  15. package/dist/web/assets/{core-DktjxGrT.js → core-CsUyNVs5.js} +1 -1
  16. package/dist/web/assets/{core-B6Kp8rMh.js → core-GZZnkE26.js} +1 -1
  17. package/dist/web/assets/{display-A5IEINAP-BFwsYEHq.js → display-A5IEINAP-B8BJrcag.js} +2 -2
  18. package/dist/web/assets/{dist-CY62NsuD.js → dist-BZmXa__p.js} +2 -2
  19. package/dist/web/assets/{dist-B_dkmahO.js → dist-DlypDwtn.js} +1 -1
  20. package/dist/web/assets/dist-JsQmV3pO.js +21 -0
  21. package/dist/web/assets/dist-t5Yo0YiG.js +41 -0
  22. package/dist/web/assets/function_calling-kK7um7Ye.js +61 -0
  23. package/dist/web/assets/index-CM9P_1sf.css +2 -0
  24. package/dist/web/assets/index-zlrXpRSB.js +720 -0
  25. package/dist/web/assets/{json-schema-processors-DSIsU0go.js → json-schema-processors-DNSjFPrk.js} +1 -1
  26. package/dist/web/assets/langfuse-U2OEF7K7-BF5JV8uu.js +1 -0
  27. package/dist/web/assets/{llms-ByHaqvCr.js → llms-ByyTYk2T.js} +2 -2
  28. package/dist/web/assets/messages-D4_mH1tk.js +36 -0
  29. package/dist/web/assets/{module-DCsrdi7m.js → module-DbiflUeG.js} +2 -2
  30. package/dist/web/assets/react-C6BFTceN.js +1 -0
  31. package/dist/web/assets/rpc-logger-TPNV75J4-CMVlzCN7.js +1 -0
  32. package/dist/web/assets/{schemas-79owEkeD.js → schemas-BrqAD_Qo.js} +1 -1
  33. package/dist/web/assets/{source-1h9sRCfR.js → source-DeHaVNLZ.js} +1 -1
  34. package/dist/web/assets/stan-r2rUHRuO.js +1 -0
  35. package/dist/web/assets/{stdio-DH6BP75M-C4--HtGN.js → stdio-RWLH66ZO-C753VwJ7.js} +1 -1
  36. package/dist/web/assets/tools-kLe9X8V8.js +2 -0
  37. package/dist/web/index.html +13 -10
  38. package/package.json +8 -17
  39. package/dist/web/assets/browser-DeFVa-Up.js +0 -380
  40. package/dist/web/assets/chunk_array-CT_rI3GZ.js +0 -1
  41. package/dist/web/assets/client-DaI4JaTs.js +0 -68
  42. package/dist/web/assets/dist-Cjn62jmL.js +0 -21
  43. package/dist/web/assets/dist-DWk4vNzA.js +0 -41
  44. package/dist/web/assets/function_calling-BHFkMa4W.js +0 -61
  45. package/dist/web/assets/index-Bd0WP6Xj.js +0 -465
  46. package/dist/web/assets/index-DAB6h2wg.css +0 -2
  47. package/dist/web/assets/langfuse-U2OEF7K7-UPVEn4-O.js +0 -1
  48. package/dist/web/assets/messages-DQuC8BOl.js +0 -1
  49. package/dist/web/assets/react-C-wC1s-h.js +0 -1
  50. package/dist/web/assets/rpc-logger-TPNV75J4-DBofHjaa.js +0 -1
  51. package/dist/web/assets/stan-btJKTWsQ.js +0 -1
  52. package/dist/web/assets/tools-CFpbqXW1.js +0 -2
  53. /package/dist/web/assets/{1c-xAwF9KHw.js → 1c-AGlpZ3Bo.js} +0 -0
  54. /package/dist/web/assets/{abnf-57JF8nOy.js → abnf-CY04oKOo.js} +0 -0
  55. /package/dist/web/assets/{accesslog-C2D2ESC1.js → accesslog-BW-XYbZ-.js} +0 -0
  56. /package/dist/web/assets/{actionscript-BA90Z6ek.js → actionscript-CyrdwIe8.js} +0 -0
  57. /package/dist/web/assets/{ada-BOZemNeY.js → ada-C-TrrrBy.js} +0 -0
  58. /package/dist/web/assets/{angelscript-BPuRd7Au.js → angelscript-CRTYantF.js} +0 -0
  59. /package/dist/web/assets/{apache-CRejwSR0.js → apache-BtWb7jui.js} +0 -0
  60. /package/dist/web/assets/{applescript-DRWfnP7q.js → applescript-B5uiivcX.js} +0 -0
  61. /package/dist/web/assets/{arcade-c4fxT6cy.js → arcade-CKXflcFV.js} +0 -0
  62. /package/dist/web/assets/{arduino-D-GQgoAg.js → arduino-9WdEHP7F.js} +0 -0
  63. /package/dist/web/assets/{armasm-DW6aLB45.js → armasm-B1n3-9gm.js} +0 -0
  64. /package/dist/web/assets/{asciidoc-l4rRUjBn.js → asciidoc-DnpyabXI.js} +0 -0
  65. /package/dist/web/assets/{aspectj-CBoSaF_P.js → aspectj-DHfRYIO6.js} +0 -0
  66. /package/dist/web/assets/{autohotkey-oklQZH_e.js → autohotkey-D4kyAzbx.js} +0 -0
  67. /package/dist/web/assets/{autoit-CCOhikpq.js → autoit-Dkm5j0Id.js} +0 -0
  68. /package/dist/web/assets/{avrasm-DQyyIbM0.js → avrasm-DDWyveTc.js} +0 -0
  69. /package/dist/web/assets/{awk-Bpx3OGwB.js → awk-0C9tJhw5.js} +0 -0
  70. /package/dist/web/assets/{axapta-ConOtNUD.js → axapta-7WyvVgTr.js} +0 -0
  71. /package/dist/web/assets/{bash-CG9dvFVQ.js → bash-BU3h1nvY.js} +0 -0
  72. /package/dist/web/assets/{basic-D55fg9VU.js → basic-cvnVWdBh.js} +0 -0
  73. /package/dist/web/assets/{bnf-BRHfvdnF.js → bnf-DqQP6RvA.js} +0 -0
  74. /package/dist/web/assets/{brainfuck-CvIc7KgZ.js → brainfuck-9Gnm7MFh.js} +0 -0
  75. /package/dist/web/assets/{c-BYqCyjPu.js → c-CR0xII_C.js} +0 -0
  76. /package/dist/web/assets/{c-like-BiZIVjlk.js → c-like-DQRMjEeJ.js} +0 -0
  77. /package/dist/web/assets/{cal-BI45EWE9.js → cal-BupHjSW7.js} +0 -0
  78. /package/dist/web/assets/{capnproto-CT4_QH7U.js → capnproto-BJz3QcqE.js} +0 -0
  79. /package/dist/web/assets/{ceylon-DEhPqbQs.js → ceylon-Cm5BiqjN.js} +0 -0
  80. /package/dist/web/assets/{chunk-3GQAWCBQ-C-9Cm0Np.js → chunk-3GQAWCBQ-ntjTDD_C.js} +0 -0
  81. /package/dist/web/assets/{clean-Dj90Ldo4.js → clean-yd5cdwwQ.js} +0 -0
  82. /package/dist/web/assets/{clojure-nGPdvoWZ.js → clojure-BEy8uY0S.js} +0 -0
  83. /package/dist/web/assets/{clojure-repl-CoLrBnNB.js → clojure-repl-4mYnspW8.js} +0 -0
  84. /package/dist/web/assets/{cmake-Cau5qcoL.js → cmake-D6UxhUeW.js} +0 -0
  85. /package/dist/web/assets/{coffeescript-CRI19SN5.js → coffeescript-BKMS6sen.js} +0 -0
  86. /package/dist/web/assets/{coq-cKQTGfiT.js → coq-ByIcAboL.js} +0 -0
  87. /package/dist/web/assets/{cos-BvDn-C7W.js → cos-WtGXvK46.js} +0 -0
  88. /package/dist/web/assets/{cpp-Cm8w5GBK.js → cpp-7GTPyvMa.js} +0 -0
  89. /package/dist/web/assets/{crmsh-BphFuWfQ.js → crmsh-C5mOafXq.js} +0 -0
  90. /package/dist/web/assets/{crystal-CjeRzStm.js → crystal-CDkEXhx-.js} +0 -0
  91. /package/dist/web/assets/{csharp-BjNNmcwi.js → csharp-BB5evbyJ.js} +0 -0
  92. /package/dist/web/assets/{csp-BDakTyDq.js → csp-C5gCtA0-.js} +0 -0
  93. /package/dist/web/assets/{css-BS5Bw9la.js → css-BxJzVbPg.js} +0 -0
  94. /package/dist/web/assets/{d-iafwvjhA.js → d-pa4_Cp7t.js} +0 -0
  95. /package/dist/web/assets/{dart-CJj6VfDK.js → dart-BX2VLXw3.js} +0 -0
  96. /package/dist/web/assets/{delphi-CiYfdpeB.js → delphi-DdHGjuIZ.js} +0 -0
  97. /package/dist/web/assets/{diff-C0_uVc7j.js → diff-CBEZzUzk.js} +0 -0
  98. /package/dist/web/assets/{django-D2hgH-Q1.js → django-D4YuT7a9.js} +0 -0
  99. /package/dist/web/assets/{dns-Cl4dGnK7.js → dns-r4HMRPCv.js} +0 -0
  100. /package/dist/web/assets/{dockerfile-meWkyaPv.js → dockerfile-ZfcC6nOD.js} +0 -0
  101. /package/dist/web/assets/{dos-AwMP_0oM.js → dos-CIXc_2yf.js} +0 -0
  102. /package/dist/web/assets/{dsconfig-CnDR2ZdU.js → dsconfig-DlugHtUP.js} +0 -0
  103. /package/dist/web/assets/{dts-BzC-HwM_.js → dts-DaEIYGjQ.js} +0 -0
  104. /package/dist/web/assets/{dust-C7Vcl3-X.js → dust-D5BPeLmO.js} +0 -0
  105. /package/dist/web/assets/{ebnf-CL9qQEga.js → ebnf-FDSeI3Uq.js} +0 -0
  106. /package/dist/web/assets/{elixir-CfaDenjY.js → elixir-BW6MO0JC.js} +0 -0
  107. /package/dist/web/assets/{elm-Cy8gaJOl.js → elm-DlEB7oVS.js} +0 -0
  108. /package/dist/web/assets/{erb-C-4IIk8K.js → erb-Cfqar-lN.js} +0 -0
  109. /package/dist/web/assets/{erlang-B1M6fLuV.js → erlang-CAmVwVgE.js} +0 -0
  110. /package/dist/web/assets/{erlang-repl-BejU3MB_.js → erlang-repl-ynjzGTyJ.js} +0 -0
  111. /package/dist/web/assets/{excel-BkfhIrhj.js → excel-B4xDzPh0.js} +0 -0
  112. /package/dist/web/assets/{fix-BVmdZVAA.js → fix-DrIaqPya.js} +0 -0
  113. /package/dist/web/assets/{flix-D0avEvQY.js → flix-C1QBAYX7.js} +0 -0
  114. /package/dist/web/assets/{fortran-DakqiesO.js → fortran-13hn1qLz.js} +0 -0
  115. /package/dist/web/assets/{fsharp-DA54xfXW.js → fsharp-DsthWJmP.js} +0 -0
  116. /package/dist/web/assets/{gams-CXTQKphs.js → gams-CCIHfrc2.js} +0 -0
  117. /package/dist/web/assets/{gauss-CG12HF6_.js → gauss-DPE0fKXo.js} +0 -0
  118. /package/dist/web/assets/{gcode-BCEABt45.js → gcode-Cnu_Eke-.js} +0 -0
  119. /package/dist/web/assets/{gherkin-ZM-mRt_J.js → gherkin-6DphholZ.js} +0 -0
  120. /package/dist/web/assets/{glsl-CsBoWmwk.js → glsl-bxnyXALN.js} +0 -0
  121. /package/dist/web/assets/{gml-BpvmFz5F.js → gml-CNHkNLih.js} +0 -0
  122. /package/dist/web/assets/{go-oa77k3Q1.js → go-CNn2XrbH.js} +0 -0
  123. /package/dist/web/assets/{golo-DnSZZkzZ.js → golo-DiSoln2k.js} +0 -0
  124. /package/dist/web/assets/{gradle-xhSl5jRG.js → gradle-DwRwgn-A.js} +0 -0
  125. /package/dist/web/assets/{groovy-BUGEyqOY.js → groovy-B5vHRPUi.js} +0 -0
  126. /package/dist/web/assets/{haml-Q5moYl6B.js → haml-DyyQV85z.js} +0 -0
  127. /package/dist/web/assets/{handlebars-B8gHazwq.js → handlebars-BAEJweq7.js} +0 -0
  128. /package/dist/web/assets/{haskell-C_nTNVTF.js → haskell-ChxeibtB.js} +0 -0
  129. /package/dist/web/assets/{haxe-DEa-mhEM.js → haxe-Bnvb8PoO.js} +0 -0
  130. /package/dist/web/assets/{hsp-DAtUNrWr.js → hsp-BdBjqG0g.js} +0 -0
  131. /package/dist/web/assets/{htmlbars-IZ5H55KS.js → htmlbars-Dco0ls0x.js} +0 -0
  132. /package/dist/web/assets/{http-BlfIsTrN.js → http-BQrDnbm9.js} +0 -0
  133. /package/dist/web/assets/{hy-BKHwYI3U.js → hy-j_gy-_-v.js} +0 -0
  134. /package/dist/web/assets/{inform7-DBoQipSc.js → inform7-4lpsdkpY.js} +0 -0
  135. /package/dist/web/assets/{ini-rm_5Fj36.js → ini-CyoU_M9N.js} +0 -0
  136. /package/dist/web/assets/{irpf90-R1rxRBNO.js → irpf90-CA5ICZkt.js} +0 -0
  137. /package/dist/web/assets/{isbl-WbUbjWRI.js → isbl-D5MCB9gL.js} +0 -0
  138. /package/dist/web/assets/{java-flBTnDBg.js → java-C_cNvtw0.js} +0 -0
  139. /package/dist/web/assets/{javascript-Bi9wT7IL.js → javascript-Cx9Fh-yC.js} +0 -0
  140. /package/dist/web/assets/{jboss-cli-BVqHepEU.js → jboss-cli-n0a6upZq.js} +0 -0
  141. /package/dist/web/assets/{json-BvAVz8jQ.js → json-pS218i2Y.js} +0 -0
  142. /package/dist/web/assets/{julia-B3zW89kP.js → julia-ByIGgcyj.js} +0 -0
  143. /package/dist/web/assets/{julia-repl-Cpt_AFpB.js → julia-repl-DoKEpX79.js} +0 -0
  144. /package/dist/web/assets/{kotlin-CMZ_9XJI.js → kotlin-D7EVUsdH.js} +0 -0
  145. /package/dist/web/assets/{lasso-DVqtNSau.js → lasso-CfHzza_u.js} +0 -0
  146. /package/dist/web/assets/{latex-CFJv-UA6.js → latex-DEpVEzU4.js} +0 -0
  147. /package/dist/web/assets/{ldif-BS-KKOy0.js → ldif-CztKIlXq.js} +0 -0
  148. /package/dist/web/assets/{leaf--Z87tMVa.js → leaf-BeXHCQvG.js} +0 -0
  149. /package/dist/web/assets/{less-CXBPSZIU.js → less-BYuoMNFC.js} +0 -0
  150. /package/dist/web/assets/{lisp-cVmS95gk.js → lisp-DENj9Gb0.js} +0 -0
  151. /package/dist/web/assets/{livecodeserver-BOOiQrUz.js → livecodeserver-DzZuZBA6.js} +0 -0
  152. /package/dist/web/assets/{livescript-CVxJe7N1.js → livescript-Dcoaf4MP.js} +0 -0
  153. /package/dist/web/assets/{llvm-DQeHJJ2W.js → llvm-B_NkXFs1.js} +0 -0
  154. /package/dist/web/assets/{lsl-Bfxi34aD.js → lsl-sr9xRjsv.js} +0 -0
  155. /package/dist/web/assets/{lua-DXxL7Qnq.js → lua-DOwApfze.js} +0 -0
  156. /package/dist/web/assets/{makefile-B5Fr6EdB.js → makefile-Dnbo7dYF.js} +0 -0
  157. /package/dist/web/assets/{markdown-DTODmQHl.js → markdown-DGgwjJWS.js} +0 -0
  158. /package/dist/web/assets/{mathematica-XsKNpYVI.js → mathematica-DvU9l120.js} +0 -0
  159. /package/dist/web/assets/{matlab-BQHIwHUE.js → matlab-flr6798G.js} +0 -0
  160. /package/dist/web/assets/{maxima-4gc2wOHL.js → maxima-DCd2nSGc.js} +0 -0
  161. /package/dist/web/assets/{mel-tWDc8R_0.js → mel-NmXTNXHL.js} +0 -0
  162. /package/dist/web/assets/{mercury-CMAR8Kmo.js → mercury-PVmYLiQ2.js} +0 -0
  163. /package/dist/web/assets/{mipsasm-CuThUvs6.js → mipsasm-LHYPiOXU.js} +0 -0
  164. /package/dist/web/assets/{mizar-DJiOXbyw.js → mizar-BbJKfTOL.js} +0 -0
  165. /package/dist/web/assets/{mojolicious-BHZ1FyrY.js → mojolicious-Dw8SBiyk.js} +0 -0
  166. /package/dist/web/assets/{monkey-Ckr0R6Af.js → monkey-CYCsHKco.js} +0 -0
  167. /package/dist/web/assets/{moonscript-rPHoYTbB.js → moonscript-BndWJdyg.js} +0 -0
  168. /package/dist/web/assets/{n1ql-CVbFFpfR.js → n1ql-p64i6r1f.js} +0 -0
  169. /package/dist/web/assets/{nginx-piKHOi7C.js → nginx-Clg11n23.js} +0 -0
  170. /package/dist/web/assets/{nim-D2ljN6dK.js → nim-BF6erjkH.js} +0 -0
  171. /package/dist/web/assets/{nix-BE-MXto5.js → nix-aqHU_7Cj.js} +0 -0
  172. /package/dist/web/assets/{node-repl-DywEPp9w.js → node-repl-DuuOln4U.js} +0 -0
  173. /package/dist/web/assets/{nsis-DQnnPyE6.js → nsis-BZNwabo3.js} +0 -0
  174. /package/dist/web/assets/{objectivec-DVFSpwpL.js → objectivec-BD-A2eRS.js} +0 -0
  175. /package/dist/web/assets/{ocaml-B9_ypEp1.js → ocaml-Dtfm3HD8.js} +0 -0
  176. /package/dist/web/assets/{openscad-Cquxty4i.js → openscad-3uP221Jx.js} +0 -0
  177. /package/dist/web/assets/{oxygene-BtOMSMR6.js → oxygene-DBIMAfJO.js} +0 -0
  178. /package/dist/web/assets/{parser3-CWVyPD7l.js → parser3-C9bjRYvd.js} +0 -0
  179. /package/dist/web/assets/{path-BzTN_bR6.js → path-CG3438uq.js} +0 -0
  180. /package/dist/web/assets/{perl-DQMBOVA5.js → perl-Be1CLDbh.js} +0 -0
  181. /package/dist/web/assets/{pf-DhGORkJd.js → pf-BEYn9RX1.js} +0 -0
  182. /package/dist/web/assets/{pgsql-awwi5nDK.js → pgsql-Bp-7Jjz8.js} +0 -0
  183. /package/dist/web/assets/{php-_c_VoeVa.js → php-D8HtobZG.js} +0 -0
  184. /package/dist/web/assets/{php-template-Dsp4D0jE.js → php-template-5wDTa_KR.js} +0 -0
  185. /package/dist/web/assets/{plaintext-7v3vLFp3.js → plaintext-DF3cBN5Y.js} +0 -0
  186. /package/dist/web/assets/{pony-BVahP-cB.js → pony-CA_LuLTd.js} +0 -0
  187. /package/dist/web/assets/{powershell-DDAkbMgT.js → powershell-CfylS3qM.js} +0 -0
  188. /package/dist/web/assets/{preload-helper-XLr9-hSf.js → preload-helper-ckxxtgMM.js} +0 -0
  189. /package/dist/web/assets/{processing-CCja83Ot.js → processing-BOdw1uey.js} +0 -0
  190. /package/dist/web/assets/{profile-BjuA8z3S.js → profile-BMNLdTbz.js} +0 -0
  191. /package/dist/web/assets/{prolog-jJiPeztA.js → prolog-wnuVaQNI.js} +0 -0
  192. /package/dist/web/assets/{properties-DK40DOVd.js → properties-BY2UjzIx.js} +0 -0
  193. /package/dist/web/assets/{protobuf-DJs85Lp7.js → protobuf-W4tuiDUG.js} +0 -0
  194. /package/dist/web/assets/{puppet-BPdGz-Jp.js → puppet-CcAPsi7F.js} +0 -0
  195. /package/dist/web/assets/{purebasic-C8c2xseX.js → purebasic-Cx_iSilj.js} +0 -0
  196. /package/dist/web/assets/{python-B-gHuzXK.js → python-DtGc5unX.js} +0 -0
  197. /package/dist/web/assets/{python-repl-CLJQcHH8.js → python-repl-B1V7zIpU.js} +0 -0
  198. /package/dist/web/assets/{q-VmMkCWpr.js → q-DwgFecwj.js} +0 -0
  199. /package/dist/web/assets/{qml-BkIM5RCI.js → qml-CxtqwNEV.js} +0 -0
  200. /package/dist/web/assets/{r-CHi-Wrw8.js → r-Vyl1b83h.js} +0 -0
  201. /package/dist/web/assets/{reasonml-B05iQ6f2.js → reasonml-D1BWml10.js} +0 -0
  202. /package/dist/web/assets/{rib-DzxrqgFS.js → rib-WKK4Jb_l.js} +0 -0
  203. /package/dist/web/assets/{roboconf-DVxtd4X5.js → roboconf-DD9St8Le.js} +0 -0
  204. /package/dist/web/assets/{routeros-C7PRtmmR.js → routeros-DIyDrw3W.js} +0 -0
  205. /package/dist/web/assets/{rsl-CcIHTLD_.js → rsl-CfigMFVZ.js} +0 -0
  206. /package/dist/web/assets/{ruby-BGhMoiTk.js → ruby-YHScF8rv.js} +0 -0
  207. /package/dist/web/assets/{ruleslanguage-2nOGmUbL.js → ruleslanguage-BYwdQsZF.js} +0 -0
  208. /package/dist/web/assets/{rust-Bn5K3sZf.js → rust-B5YXnMyV.js} +0 -0
  209. /package/dist/web/assets/{sas-BOCzodK2.js → sas-CCTr8w16.js} +0 -0
  210. /package/dist/web/assets/{scala-BRv9Y1Gl.js → scala-Cbxd3VFS.js} +0 -0
  211. /package/dist/web/assets/{scheme-DgxU7T27.js → scheme-BsN3DINT.js} +0 -0
  212. /package/dist/web/assets/{scilab-CDpHNnol.js → scilab-DPKVNXPG.js} +0 -0
  213. /package/dist/web/assets/{scss-_DXiA8XH.js → scss-DbQAKOek.js} +0 -0
  214. /package/dist/web/assets/{shell-JZbpHYqw.js → shell-DWzkAqOf.js} +0 -0
  215. /package/dist/web/assets/{smali-D-pxIQI6.js → smali-BftjeLb5.js} +0 -0
  216. /package/dist/web/assets/{smalltalk-BgHXrgWH.js → smalltalk-CRiQmXNN.js} +0 -0
  217. /package/dist/web/assets/{sml-XMsOdlaX.js → sml-StzcQc9I.js} +0 -0
  218. /package/dist/web/assets/{sqf-BAJmpDEs.js → sqf-DD5HJChz.js} +0 -0
  219. /package/dist/web/assets/{sql-qDDDtU5U.js → sql-DPgh6LFW.js} +0 -0
  220. /package/dist/web/assets/{sql_more-OsRq2zw0.js → sql_more-CtzXbTQc.js} +0 -0
  221. /package/dist/web/assets/{stata-Bk4QaRj1.js → stata-BVbnRiot.js} +0 -0
  222. /package/dist/web/assets/{step21-JBksYMyW.js → step21-Dq-6Zq9y.js} +0 -0
  223. /package/dist/web/assets/{stylus-B2-KoW99.js → stylus-BBnpEkBq.js} +0 -0
  224. /package/dist/web/assets/{subunit-Dms0B4fv.js → subunit-ELCErEkQ.js} +0 -0
  225. /package/dist/web/assets/{swift-BDkC6DWd.js → swift-DaAs7qTh.js} +0 -0
  226. /package/dist/web/assets/{taggerscript-BQuVNykw.js → taggerscript-1FPav-0a.js} +0 -0
  227. /package/dist/web/assets/{tap-Bwup7RHy.js → tap-EToQ4lhN.js} +0 -0
  228. /package/dist/web/assets/{tcl-CbpGYImD.js → tcl-D3o49C6L.js} +0 -0
  229. /package/dist/web/assets/{thrift-B_z8wKcZ.js → thrift-CWhyiqPB.js} +0 -0
  230. /package/dist/web/assets/{tp-BJLBEN3J.js → tp-B6O9yM_7.js} +0 -0
  231. /package/dist/web/assets/{twig-nUEnJWT1.js → twig-CtXlonbL.js} +0 -0
  232. /package/dist/web/assets/{typescript-CrQbuH5h.js → typescript-CCrKHjvE.js} +0 -0
  233. /package/dist/web/assets/{util-BS7JSiXp.js → util-_DavpSWv.js} +0 -0
  234. /package/dist/web/assets/{vala-2XexN6SZ.js → vala-DqTbJvZE.js} +0 -0
  235. /package/dist/web/assets/{vbnet-BAt8krwo.js → vbnet-BIMC8kyn.js} +0 -0
  236. /package/dist/web/assets/{vbscript--ebsjfOw.js → vbscript-CwHfrTEX.js} +0 -0
  237. /package/dist/web/assets/{vbscript-html-yaZI43iV.js → vbscript-html-6BIOjkqb.js} +0 -0
  238. /package/dist/web/assets/{verilog-emU2h0-4.js → verilog-Br3eYmwZ.js} +0 -0
  239. /package/dist/web/assets/{vhdl-CPuOZFR2.js → vhdl-CDlnDphM.js} +0 -0
  240. /package/dist/web/assets/{vim-ZfleAGCY.js → vim-BOZojkV6.js} +0 -0
  241. /package/dist/web/assets/{x86asm-BHTiWqya.js → x86asm-Br9iqCtX.js} +0 -0
  242. /package/dist/web/assets/{xl-MlLWG0U8.js → xl-eSTclZWH.js} +0 -0
  243. /package/dist/web/assets/{xml-CJKMw8W2.js → xml-C775tW_n.js} +0 -0
  244. /package/dist/web/assets/{xquery-B4Yi49S8.js → xquery-DimlVJ6h.js} +0 -0
  245. /package/dist/web/assets/{yaml-5C-oV2Cp.js → yaml-Dnhus5cp.js} +0 -0
  246. /package/dist/web/assets/{zephir-Dig9AotJ.js → zephir-j3mL6he_.js} +0 -0
@@ -0,0 +1,21 @@
1
+ import{A as e,Bn as t,Fn as n,Jt as r,Ln as i,Nn as a,Qt as o,Rn as s,S as c,U as l,Ut as u,Wt as d,Xt as f,Zt as p,_n as m,et as h,fn as ee,gn as te,hn as g,it as _,l as ne,ln as re,m as ie,mn as ae,pn as oe,tt as se}from"./messages-D4_mH1tk.js";import{S as ce,Yn as le}from"./json-schema-processors-DNSjFPrk.js";import{_ as ue,d as v,l as de,m as y,o as fe,p as b,r as pe,v as x}from"./schemas-BrqAD_Qo.js";import{E as me,M as he,p as ge,r as _e,s as ve,t as ye,w as be}from"./function_calling-kK7um7Ye.js";import"./tools-kLe9X8V8.js";import"./chunk_array-Bw1lTtex.js";import{a as xe,i as Se,o as Ce,s as we}from"./llms-ByyTYk2T.js";function Te(e,t){return e.lc_error_code=t,e.message=`${e.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${t}/\n`,e}function S(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function C(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var Ee=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return Ee=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))};function De(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var Oe=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)},w=class extends Error{},T=class e extends w{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new ke({message:r,cause:Oe(n)});let a=n?.error;return t===400?new je(t,a,r,i):t===401?new Me(t,a,r,i):t===403?new Ne(t,a,r,i):t===404?new Pe(t,a,r,i):t===409?new Fe(t,a,r,i):t===422?new Ie(t,a,r,i):t===429?new Le(t,a,r,i):t>=500?new Re(t,a,r,i):new e(t,a,r,i)}},E=class extends T{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},ke=class extends T{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},Ae=class extends ke{constructor({message:e}={}){super({message:e??`Request timed out.`})}},je=class extends T{},Me=class extends T{},Ne=class extends T{},Pe=class extends T{},Fe=class extends T{},Ie=class extends T{},Le=class extends T{},Re=class extends T{},ze=class extends w{constructor(){super(`Could not parse response content as the length limit was reached`)}},Be=class extends w{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},Ve=class extends Error{constructor(e){super(e)}},He=/^[a-z][a-z0-9+.-]*:/i,Ue=e=>He.test(e),D=e=>(D=Array.isArray,D(e)),We=D;function Ge(e){return typeof e==`object`?e??{}:{}}function Ke(e){if(!e)return!0;for(let t in e)return!1;return!0}function qe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Je(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ye=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new w(`${e} must be an integer`);if(t<0)throw new w(`${e} must be a positive integer`);return t},Xe=e=>{try{return JSON.parse(e)}catch{return}},Ze=e=>new Promise(t=>setTimeout(t,e)),Qe=`6.17.0`,$e=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`;function et(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}var tt=()=>{let e=et();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":it(Deno.build.os),"X-Stainless-Arch":rt(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":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":it(globalThis.process.platform??`unknown`),"X-Stainless-Arch":rt(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=nt();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Qe,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}};function nt(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var rt=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,it=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),at,ot=()=>at??=tt();function st(){if(typeof fetch<`u`)return fetch;throw 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 ct(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function lt(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return ct({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ut(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function dt(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var ft=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)}),pt=`RFC3986`,mt=e=>String(e),ht={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:mt},gt=(e,t)=>(gt=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),gt(e,t)),O=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),_t=1024,vt=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=_t){let t=a.length>=_t?a.slice(e,e+_t):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=O[r];continue}if(r<2048){n[n.length]=O[192|r>>6]+O[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=O[224|r>>12]+O[128|r>>6&63]+O[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=O[240|r>>18]+O[128|r>>12&63]+O[128|r>>6&63]+O[128|r&63]}o+=n.join(``)}return o};function yt(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function bt(e,t){if(D(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var xt={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},St=function(e,t){Array.prototype.push.apply(e,D(t)?t:[t])},Ct,k={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:vt,encodeValuesOnly:!1,format:pt,formatter:mt,indices:!1,serializeDate(e){return(Ct??=Function.prototype.call.bind(Date.prototype.toISOString))(e)},skipNulls:!1,strictNullHandling:!1};function wt(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}var Tt={};function Et(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,ee,te){let g=e,_=te,ne=0,re=!1;for(;(_=_.get(Tt))!==void 0&&!re;){let t=_.get(e);if(ne+=1,t!==void 0){if(t===ne)throw RangeError(`Cyclic object value`);re=!0}_.get(Tt)===void 0&&(ne=0)}if(typeof l==`function`?g=l(t,g):g instanceof Date?g=f?.(g):n===`comma`&&D(g)&&(g=bt(g,function(e){return e instanceof Date?f?.(e):e})),g===null){if(a)return c&&!h?c(t,k.encoder,ee,`key`,p):t;g=``}if(wt(g)||yt(g)){if(c){let e=h?t:c(t,k.encoder,ee,`key`,p);return[m?.(e)+`=`+m?.(c(g,k.encoder,ee,`value`,p))]}return[m?.(t)+`=`+m?.(String(g))]}let ie=[];if(g===void 0)return ie;let ae;if(n===`comma`&&D(g))h&&c&&(g=bt(g,c)),ae=[{value:g.length>0?g.join(`,`)||null:void 0}];else if(D(l))ae=l;else{let e=Object.keys(g);ae=u?e.sort(u):e}let oe=s?String(t).replace(/\./g,`%2E`):String(t),se=r&&D(g)&&g.length===1?oe+`[]`:oe;if(i&&D(g)&&g.length===0)return se+`[]`;for(let t=0;t<ae.length;++t){let _=ae[t],re=typeof _==`object`&&_.value!==void 0?_.value:g[_];if(o&&re===null)continue;let oe=d&&s?_.replace(/\./g,`%2E`):_,ce=D(g)?typeof n==`function`?n(se,oe):se:se+(d?`.`+oe:`[`+oe+`]`);te.set(e,ne);let le=new WeakMap;le.set(Tt,te),St(ie,Et(re,ce,n,r,i,a,o,s,n===`comma`&&h&&D(g)?null:c,l,u,d,f,p,m,h,ee,le))}return ie}function Dt(e=k){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||k.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=pt;if(e.format!==void 0){if(!gt(ht,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=ht[n],i=k.filter;(typeof e.filter==`function`||D(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in xt?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:k.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:k.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:k.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:k.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:k.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?k.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:k.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:k.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:k.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:k.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:k.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:k.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:k.strictNullHandling}}function Ot(e,t={}){let n=e,r=Dt(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):D(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=xt[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||=Object.keys(n),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||St(o,Et(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}function kt(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}var At;function jt(e){let t;return(At??=(t=new globalThis.TextEncoder,t.encode.bind(t)))(e)}var Mt;function Nt(e){let t;return(Mt??=(t=new globalThis.TextDecoder,t.decode.bind(t)))(e)}var A,j,Pt=class{constructor(){A.set(this,void 0),j.set(this,void 0),S(this,A,new Uint8Array,`f`),S(this,j,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?jt(e):e;S(this,A,kt([C(this,A,`f`),t]),`f`);let n=[],r;for(;(r=Ft(C(this,A,`f`),C(this,j,`f`)))!=null;){if(r.carriage&&C(this,j,`f`)==null){S(this,j,r.index,`f`);continue}if(C(this,j,`f`)!=null&&(r.index!==C(this,j,`f`)+1||r.carriage)){n.push(Nt(C(this,A,`f`).subarray(0,C(this,j,`f`)-1))),S(this,A,C(this,A,`f`).subarray(C(this,j,`f`)),`f`),S(this,j,null,`f`);continue}let e=C(this,j,`f`)===null?r.preceding:r.preceding-1,t=Nt(C(this,A,`f`).subarray(0,e));n.push(t),S(this,A,C(this,A,`f`).subarray(r.index),`f`),S(this,j,null,`f`)}return n}flush(){return C(this,A,`f`).length?this.decode(`
2
+ `):[]}};A=new WeakMap,j=new WeakMap,Pt.NEWLINE_CHARS=new Set([`
3
+ `,`\r`]),Pt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Ft(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function It(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Lt={off:0,error:200,warn:300,info:400,debug:500},Rt=(e,t,n)=>{if(e){if(qe(Lt,e))return e;M(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Lt))}`)}};function zt(){}function Bt(e,t,n){return!t||Lt[e]>Lt[n]?zt:t[e].bind(t)}var Vt={error:zt,warn:zt,info:zt,debug:zt},Ht=new WeakMap;function M(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Vt;let r=Ht.get(t);if(r&&r[0]===n)return r[1];let i={error:Bt(`error`,t,n),warn:Bt(`warn`,t,n),info:Bt(`info`,t,n),debug:Bt(`debug`,t,n)};return Ht.set(t,[n,i]),i}var Ut=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t])),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e),Wt,Gt=class e{constructor(e,t,n){this.iterator=e,Wt.set(this,void 0),this.controller=t,S(this,Wt,n,`f`)}static fromSSEResponse(t,n,r){let i=!1,a=r?M(r):console;async function*o(){if(i)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let r of Kt(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw a.error(`Could not parse message into JSON:`,r.data),a.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new T(void 0,e.error,void 0,t.headers);yield e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw console.error(`Could not parse message into JSON:`,r.data),console.error(`From chunk:`,r.raw),e}if(r.event==`error`)throw new T(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(De(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Pt,n=ut(t);for await(let t of n)for(let n of e.decode(t))yield n;for(let t of e.flush())yield t}async function*o(){if(i)throw new w("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(De(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Wt=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,C(this,Wt,`f`)),new e(()=>i(n),this.controller,C(this,Wt,`f`))]}toReadableStream(){let e=this,t;return ct({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=jt(JSON.stringify(n)+`
4
+ `);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}};async function*Kt(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new w(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`):new w(`Attempted to iterate over a response with no body`);let n=new Jt,r=new Pt,i=ut(e.body);for await(let e of qt(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*qt(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?jt(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=It(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}var Jt=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith(`\r`)&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join(`
5
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=Yt(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}};function Yt(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}async function Xt(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return M(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e):Gt.fromSSEResponse(n,t.controller,e);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?Zt(await n.json(),n):await n.text()})();return M(e).debug(`[${r}] response parsed`,Ut({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function Zt(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,`_request_id`,{value:t.headers.get(`x-request-id`),enumerable:!1})}var Qt,$t=class e extends Promise{constructor(e,t,n=Xt){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,Qt.set(this,void 0),S(this,Qt,e,`f`)}_thenUnwrap(t){return new e(C(this,Qt,`f`),this.responsePromise,async(e,n)=>Zt(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||=this.responsePromise.then(e=>this.parseResponse(C(this,Qt,`f`),e)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Qt=new WeakMap;var en,tn=class{constructor(e,t,n,r){en.set(this,void 0),S(this,en,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new w("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await C(this,en,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(en=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},nn=class extends $t{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await Xt(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},rn=class extends tn{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},N=class extends tn{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Ge(this.options.query),after:t}}:null}},an=class extends tn{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Ge(this.options.query),after:e}}:null}},on=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":``))}};function sn(e,t,n){return on(),new File(e,t??`unknown_file`,n)}function cn(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}var ln=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,un=async(e,t)=>_n(e.body)?{...e,body:await mn(e.body,t)}:e,dn=async(e,t)=>({...e,body:await mn(e.body,t)}),fn=new WeakMap;function pn(e){let t=typeof e==`function`?e:e.fetch,n=fn.get(t);if(n)return n;let r=(async()=>{try{let e=`Response`in t?t.Response:(await t(`data:,`)).constructor,n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return fn.set(t,r),r}var mn=async(e,t)=>{if(!await pn(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>vn(n,e,t))),n},hn=e=>e instanceof Blob&&`name`in e,gn=e=>typeof e==`object`&&!!e&&(e instanceof Response||ln(e)||hn(e)),_n=e=>{if(gn(e))return!0;if(Array.isArray(e))return e.some(_n);if(e&&typeof e==`object`){for(let t in e)if(_n(e[t]))return!0}return!1},vn=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,sn([await n.blob()],cn(n)));else if(ln(n))e.append(t,sn([await new Response(lt(n)).blob()],cn(n)));else if(hn(n))e.append(t,n,cn(n));else if(Array.isArray(n))await Promise.all(n.map(n=>vn(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>vn(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},yn=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,bn=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&yn(e),xn=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`;async function Sn(e,t,n){if(on(),e=await e,bn(e))return e instanceof File?e:sn([await e.arrayBuffer()],e.name);if(xn(e)){let r=await e.blob();return t||=new URL(e.url).pathname.split(/[\\/]/).pop(),sn(await Cn(r),t,n)}let r=await Cn(e);if(t||=cn(e),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return sn(r,t,n)}async function Cn(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(yn(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(ln(e))for await(let n of e)t.push(...await Cn(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${wn(e)}`)}return t}function wn(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var P=class{constructor(e){this._client=e}};function Tn(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var En=Object.freeze(Object.create(null)),F=((e=Tn)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??En)??En)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can\'t be safely passed as a path parameter`});if(i.sort((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new w(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
6
+ `)}\n${a}\n${t}`)}return a})(Tn),Dn=class extends P{list(e,t={},n){return this._client.getAPIList(F`/chat/completions/${e}/messages`,N,{query:t,...n})}};function On(e){return e!==void 0&&`function`in e&&e.function!==void 0}function kn(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function An(e){return e?.$brand===`auto-parseable-response-format`}function jn(e){return e?.$brand===`auto-parseable-tool`}function Mn(e,t){return!t||!Ln(t)?{...e,choices:e.choices.map(e=>(Rn(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:Nn(e,t)}function Nn(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new ze;if(e.finish_reason===`content_filter`)throw new Be;return Rn(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>Fn(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?Pn(t,e.message.content):null}}});return{...e,choices:n}}function Pn(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function Fn(e,t){let n=e.tools?.find(e=>On(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:jn(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function In(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>On(e)&&e.function?.name===t.function.name);return On(n)&&(jn(n)||n?.function.strict||!1)}function Ln(e){return An(e.response_format)?!0:e.tools?.some(e=>jn(e)||e.type===`function`&&e.function.strict===!0)??!1}function Rn(e){for(let t of e||[])if(t.type!==`function`)throw new w(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function zn(e){for(let t of e??[]){if(t.type!==`function`)throw new w(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new w(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Bn=e=>e?.role===`assistant`,Vn=e=>e?.role===`tool`,Hn,Un,Wn,Gn,Kn,qn,Jn,I,Yn,Xn,Zn,Qn,$n,er=class{constructor(){Hn.add(this),this.controller=new AbortController,Un.set(this,void 0),Wn.set(this,()=>{}),Gn.set(this,()=>{}),Kn.set(this,void 0),qn.set(this,()=>{}),Jn.set(this,()=>{}),I.set(this,{}),Yn.set(this,!1),Xn.set(this,!1),Zn.set(this,!1),Qn.set(this,!1),S(this,Un,new Promise((e,t)=>{S(this,Wn,e,`f`),S(this,Gn,t,`f`)}),`f`),S(this,Kn,new Promise((e,t)=>{S(this,qn,e,`f`),S(this,Jn,t,`f`)}),`f`),C(this,Un,`f`).catch(()=>{}),C(this,Kn,`f`).catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit(`end`)},C(this,Hn,`m`,$n).bind(this))},0)}_connected(){this.ended||(C(this,Wn,`f`).call(this),this._emit(`connect`))}get ended(){return C(this,Yn,`f`)}get errored(){return C(this,Xn,`f`)}get aborted(){return C(this,Zn,`f`)}abort(){this.controller.abort()}on(e,t){return(C(this,I,`f`)[e]||(C(this,I,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=C(this,I,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(C(this,I,`f`)[e]||(C(this,I,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{S(this,Qn,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}async done(){S(this,Qn,!0,`f`),await C(this,Kn,`f`)}_emit(e,...t){if(C(this,Yn,`f`))return;e===`end`&&(S(this,Yn,!0,`f`),C(this,qn,`f`).call(this));let n=C(this,I,`f`)[e];if(n&&(C(this,I,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!C(this,Qn,`f`)&&!n?.length&&Promise.reject(e),C(this,Gn,`f`).call(this,e),C(this,Jn,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!C(this,Qn,`f`)&&!n?.length&&Promise.reject(e),C(this,Gn,`f`).call(this,e),C(this,Jn,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}};Un=new WeakMap,Wn=new WeakMap,Gn=new WeakMap,Kn=new WeakMap,qn=new WeakMap,Jn=new WeakMap,I=new WeakMap,Yn=new WeakMap,Xn=new WeakMap,Zn=new WeakMap,Qn=new WeakMap,Hn=new WeakSet,$n=function(e){if(S(this,Xn,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new E),e instanceof E)return S(this,Zn,!0,`f`),this._emit(`abort`,e);if(e instanceof w)return this._emit(`error`,e);if(e instanceof Error){let t=new w(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new w(String(e)))};function tr(e){return typeof e.parse==`function`}var L,nr,rr,ir,ar,or,sr,cr,lr=10,ur=class extends er{constructor(){super(...arguments),L.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),Vn(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(Bn(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new w(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),C(this,L,`m`,nr).call(this)}async finalMessage(){return await this.done(),C(this,L,`m`,rr).call(this)}async finalFunctionToolCall(){return await this.done(),C(this,L,`m`,ir).call(this)}async finalFunctionToolCallResult(){return await this.done(),C(this,L,`m`,ar).call(this)}async totalUsage(){return await this.done(),C(this,L,`m`,or).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=C(this,L,`m`,rr).call(this);t&&this._emit(`finalMessage`,t);let n=C(this,L,`m`,nr).call(this);n&&this._emit(`finalContent`,n);let r=C(this,L,`m`,ir).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=C(this,L,`m`,ar).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,C(this,L,`m`,or).call(this))}async _createChatCompletion(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),C(this,L,`m`,sr).call(this,t);let i=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Nn(i,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n){let r=`tool`,{tool_choice:i=`auto`,stream:a,...o}=t,s=typeof i!=`string`&&i.type===`function`&&i?.function?.name,{maxChatCompletions:c=lr}=n||{},l=t.tools.map(e=>{if(jn(e)){if(!e.$callback)throw new w("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),u={};for(let e of l)e.type===`function`&&(u[e.function.name||e.function.function.name]=e.function);let d=`tools`in t?l.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);for(let t=0;t<c;++t){let t=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:d,messages:[...this.messages]},n)).choices[0]?.message;if(!t)throw new w(`missing message in ChatCompletion response`);if(!t.tool_calls?.length)return;for(let e of t.tool_calls){if(e.type!==`function`)continue;let t=e.id,{name:n,arguments:i}=e.function,a=u[n];if(!a){let e=`Invalid tool_call: ${JSON.stringify(n)}. Available options are: ${Object.keys(u).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}else if(s&&s!==n){let e=`Invalid tool_call: ${JSON.stringify(n)}. ${JSON.stringify(s)} requested. Please try again`;this._addMessage({role:r,tool_call_id:t,content:e});continue}let o;try{o=tr(a)?await a.parse(i):i}catch(e){let n=e instanceof Error?e.message:String(e);this._addMessage({role:r,tool_call_id:t,content:n});continue}let c=await a.function(o,this),l=C(this,L,`m`,cr).call(this,c);if(this._addMessage({role:r,tool_call_id:t,content:l}),s)return}}}};L=new WeakSet,nr=function(){return C(this,L,`m`,rr).call(this).content??null},rr=function(){let e=this.messages.length;for(;e-- >0;){let t=this.messages[e];if(Bn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new w(`stream ended without producing a ChatCompletionMessage with role=assistant`)},ir=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Bn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(e=>e.type===`function`).at(-1)?.function}},ar=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(Vn(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},or=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},sr=function(e){if(e.n!=null&&e.n>1)throw new w(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},cr=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)};var dr=class e extends ur{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),Bn(e)&&e.content&&this._emit(`content`,e.content)}},fr=1,pr=2,mr=4,hr=8,gr=16,_r=32,vr=64,yr=128,br=256,xr=yr|br,Sr=496,Cr=pr|497,wr=mr|hr,R={STR:fr,NUM:pr,ARR:mr,OBJ:hr,NULL:gr,BOOL:_r,NAN:vr,INFINITY:yr,MINUS_INFINITY:br,INF:xr,SPECIAL:Sr,ATOM:Cr,COLLECTION:wr,ALL:Cr|wr},Tr=class extends Error{},Er=class extends Error{};function Dr(e,t=R.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return Or(e.trim(),t)}var Or=(e,t)=>{let n=e.length,r=0,i=e=>{throw new Tr(`${e} at position ${r}`)},a=e=>{throw new Er(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||R.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||R.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||R.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||R.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||R.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||R.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`?!s:!1,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(R.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&R.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(R.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(R.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(R.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&R.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(R.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(R.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&R.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
7
+ \r `.includes(e[r]);)r++};return o()},kr=e=>Dr(e,R.ALL^R.NUM),z,B,Ar,V,jr,Mr,Nr,Pr,Fr,Ir,Lr,Rr,zr=class e extends ur{constructor(e){super(),z.add(this),B.set(this,void 0),Ar.set(this,void 0),V.set(this,void 0),S(this,B,e,`f`),S(this,Ar,[],`f`)}get currentChatCompletionSnapshot(){return C(this,V,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion;let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),C(this,z,`m`,jr).call(this);let i=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of i)C(this,z,`m`,Nr).call(this,e);if(i.controller.signal?.aborted)throw new E;return this._addChatCompletion(C(this,z,`m`,Ir).call(this))}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),C(this,z,`m`,jr).call(this),this._connected();let r=Gt.fromReadableStream(e,this.controller),i;for await(let e of r)i&&i!==e.id&&this._addChatCompletion(C(this,z,`m`,Ir).call(this)),C(this,z,`m`,Nr).call(this,e),i=e.id;if(r.controller.signal?.aborted)throw new E;return this._addChatCompletion(C(this,z,`m`,Ir).call(this))}[(B=new WeakMap,Ar=new WeakMap,V=new WeakMap,z=new WeakSet,jr=function(){this.ended||S(this,V,void 0,`f`)},Mr=function(e){let t=C(this,Ar,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},C(this,Ar,`f`)[e.index]=t,t)},Nr=function(e){if(this.ended)return;let t=C(this,z,`m`,Rr).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index];n.delta.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,n.delta.content,e.message.content),this._emit(`content.delta`,{delta:n.delta.content,snapshot:e.message.content,parsed:e.message.parsed})),n.delta.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:n.delta.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let r=C(this,z,`m`,Mr).call(this,e);e.finish_reason&&(C(this,z,`m`,Fr).call(this,e),r.current_tool_call_index!=null&&C(this,z,`m`,Pr).call(this,e,r.current_tool_call_index));for(let t of n.delta.tool_calls??[])r.current_tool_call_index!==t.index&&(C(this,z,`m`,Fr).call(this,e),r.current_tool_call_index!=null&&C(this,z,`m`,Pr).call(this,e,r.current_tool_call_index)),r.current_tool_call_index=t.index;for(let t of n.delta.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},Pr=function(e,t){if(C(this,z,`m`,Mr).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=C(this,B,`f`)?.tools?.find(e=>On(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:jn(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},Fr=function(e){let t=C(this,z,`m`,Mr).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=C(this,z,`m`,Lr).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},Ir=function(){if(this.ended)throw new w(`stream has ended, this shouldn't happen`);let e=C(this,V,`f`);if(!e)throw new w(`request ended without sending any chunks`);return S(this,V,void 0,`f`),S(this,Ar,[],`f`),Br(e,C(this,B,`f`))},Lr=function(){let e=C(this,B,`f`)?.response_format;return An(e)?e:null},Rr=function(e){var t,n,r,i;let a=C(this,V,`f`),{choices:o,...s}=e;a?Object.assign(a,s):a=S(this,V,{...s,choices:[]},`f`);for(let{delta:o,finish_reason:s,index:c,logprobs:l=null,...u}of e.choices){let e=a.choices[c];if(e||=a.choices[c]={finish_reason:s,index:c,message:{},logprobs:l,...u},l)if(!e.logprobs)e.logprobs=Object.assign({},l);else{let{content:r,refusal:i,...a}=l;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}if(s&&(e.finish_reason=s,C(this,B,`f`)&&Ln(C(this,B,`f`)))){if(s===`length`)throw new ze;if(s===`content_filter`)throw new Be}if(Object.assign(e,u),!o)continue;let{content:d,refusal:f,function_call:p,role:m,tool_calls:h,...ee}=o;if(Object.assign(e.message,ee),f&&(e.message.refusal=(e.message.refusal||``)+f),m&&(e.message.role=m),p&&(e.message.function_call?(p.name&&(e.message.function_call.name=p.name),p.arguments&&((r=e.message.function_call).arguments??(r.arguments=``),e.message.function_call.arguments+=p.arguments)):e.message.function_call=p),d&&(e.message.content=(e.message.content||``)+d,!e.message.refusal&&C(this,z,`m`,Lr).call(this)&&(e.message.parsed=kr(e.message.content))),h){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:a,...o}of h){let s=(i=e.message.tool_calls)[t]??(i[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),a&&(s.function??={name:a.name??``,arguments:``}),a?.name&&(s.function.name=a.name),a?.arguments&&(s.function.arguments+=a.arguments,In(C(this,B,`f`),s)&&(s.function.parsed_arguments=kr(s.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Gt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function Br(e,t){let{id:n,choices:r,created:i,model:a,system_fingerprint:o,...s}=e;return Mn({...s,id:n,choices:r.map(({message:t,finish_reason:n,index:r,logprobs:i,...a})=>{if(!n)throw new w(`missing finish_reason for choice ${r}`);let{content:o=null,function_call:s,tool_calls:c,...l}=t,u=t.role;if(!u)throw new w(`missing role for choice ${r}`);if(s){let{arguments:e,name:c}=s;if(e==null)throw new w(`missing function_call.arguments for choice ${r}`);if(!c)throw new w(`missing function_call.name for choice ${r}`);return{...a,message:{content:o,function_call:{arguments:e,name:c},role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}return c?{...a,index:r,finish_reason:n,logprobs:i,message:{...l,role:u,content:o,refusal:t.refusal??null,tool_calls:c.map((t,n)=>{let{function:i,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=i||{};if(o==null)throw new w(`missing choices[${r}].tool_calls[${n}].id\n${Vr(e)}`);if(a==null)throw new w(`missing choices[${r}].tool_calls[${n}].type\n${Vr(e)}`);if(l==null)throw new w(`missing choices[${r}].tool_calls[${n}].function.name\n${Vr(e)}`);if(c==null)throw new w(`missing choices[${r}].tool_calls[${n}].function.arguments\n${Vr(e)}`);return{...s,id:o,type:a,function:{...u,name:l,arguments:c}}})}}:{...a,message:{...l,content:o,role:u,refusal:t.refusal??null},finish_reason:n,index:r,logprobs:i}}),created:i,model:a,object:`chat.completion`,...o?{system_fingerprint:o}:{}},t)}function Vr(e){return JSON.stringify(e)}var Hr=class e extends zr{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,a)),i}},Ur=class extends P{constructor(){super(...arguments),this.messages=new Dn(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(F`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(F`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/chat/completions`,N,{query:e,...t})}delete(e,t){return this._client.delete(F`/chat/completions/${e}`,t)}parse(e,t){return zn(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>Nn(t,e))}runTools(e,t){return e.stream?Hr.runTools(this._client,e,t):dr.runTools(this._client,e,t)}stream(e,t){return zr.createChatCompletion(this._client,e,t)}};Ur.Messages=Dn;var Wr=class extends P{constructor(){super(...arguments),this.completions=new Ur(this._client)}};Wr.Completions=Ur;var Gr=Symbol(`brand.privateNullableHeaders`);function*Kr(e){if(!e)return;if(Gr in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():We(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=We(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var H=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of Kr(r)){let r=i.toLowerCase();e.has(r)||(t.delete(i),e.add(r)),a===null?(t.delete(i),n.add(r)):(t.append(i,a),n.delete(r))}}return{[Gr]:!0,values:t,nulls:n}},qr=class extends P{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:H([{Accept:`application/octet-stream`},t?.headers]),__binaryResponse:!0})}},Jr=class extends P{create(e,t){return this._client.post(`/audio/transcriptions`,dn({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}},Yr=class extends P{create(e,t){return this._client.post(`/audio/translations`,dn({body:e,...t,__metadata:{model:e.model}},this._client))}},Xr=class extends P{constructor(){super(...arguments),this.transcriptions=new Jr(this._client),this.translations=new Yr(this._client),this.speech=new qr(this._client)}};Xr.Transcriptions=Jr,Xr.Translations=Yr,Xr.Speech=qr;var Zr=class extends P{create(e,t){return this._client.post(`/batches`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList(`/batches`,N,{query:e,...t})}cancel(e,t){return this._client.post(F`/batches/${e}/cancel`,t)}},Qr=class extends P{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/assistants/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/assistants`,N,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(F`/assistants/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},$r=class extends P{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},ei=class extends P{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}},ti=class extends P{constructor(){super(...arguments),this.sessions=new $r(this._client),this.transcriptionSessions=new ei(this._client)}};ti.Sessions=$r,ti.TranscriptionSessions=ei;var ni=class extends P{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}cancel(e,t){return this._client.post(F`/chatkit/sessions/${e}/cancel`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}},ri=class extends P{retrieve(e,t){return this._client.get(F`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,an,{query:e,...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}delete(e,t){return this._client.delete(F`/chatkit/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers])})}listItems(e,t={},n){return this._client.getAPIList(F`/chatkit/threads/${e}/items`,an,{query:t,...n,headers:H([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers])})}},ii=class extends P{constructor(){super(...arguments),this.sessions=new ni(this._client),this.threads=new ri(this._client)}};ii.Sessions=ni,ii.Threads=ri;var ai=class extends P{create(e,t,n){return this._client.post(F`/threads/${e}/messages`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/messages/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/messages`,N,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(F`/threads/${r}/messages/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},oi=class extends P{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(F`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(F`/threads/${r}/runs/${e}/steps`,N,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},si=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}else{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}},ci=e=>{if(globalThis.process!==void 0)return{}?.[e]?.trim()??void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()},U,li,ui,W,di,G,fi,pi,mi,hi,K,gi,_i,vi,yi,bi,xi,Si,Ci,wi,Ti,Ei,Di,Oi=class extends er{constructor(){super(...arguments),U.add(this),ui.set(this,[]),W.set(this,{}),di.set(this,{}),G.set(this,void 0),fi.set(this,void 0),pi.set(this,void 0),mi.set(this,void 0),hi.set(this,void 0),K.set(this,void 0),gi.set(this,void 0),_i.set(this,void 0),vi.set(this,void 0)}[(ui=new WeakMap,W=new WeakMap,di=new WeakMap,G=new WeakMap,fi=new WeakMap,pi=new WeakMap,mi=new WeakMap,hi=new WeakMap,K=new WeakMap,gi=new WeakMap,_i=new WeakMap,vi=new WeakMap,U=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new li;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){let n=t?.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener(`abort`,()=>this.controller.abort())),this._connected();let r=Gt.fromReadableStream(e,this.controller);for await(let e of r)C(this,U,`m`,yi).call(this,e);if(r.controller.signal?.aborted)throw new E;return this._addRun(C(this,U,`m`,bi).call(this))}toReadableStream(){return new Gt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new li;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)C(this,U,`m`,yi).call(this,e);if(o.controller.signal?.aborted)throw new E;return this._addRun(C(this,U,`m`,bi).call(this))}static createThreadAssistantStream(e,t,n){let r=new li;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new li;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return C(this,gi,`f`)}currentRun(){return C(this,_i,`f`)}currentMessageSnapshot(){return C(this,G,`f`)}currentRunStepSnapshot(){return C(this,vi,`f`)}async finalRunSteps(){return await this.done(),Object.values(C(this,W,`f`))}async finalMessages(){return await this.done(),Object.values(C(this,di,`f`))}async finalRun(){if(await this.done(),!C(this,fi,`f`))throw Error(`Final run was not received.`);return C(this,fi,`f`)}async _createThreadAssistantStream(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort()));let i={...t,stream:!0},a=await e.createAndRun(i,{...n,signal:this.controller.signal});this._connected();for await(let e of a)C(this,U,`m`,yi).call(this,e);if(a.controller.signal?.aborted)throw new E;return this._addRun(C(this,U,`m`,bi).call(this))}async _createAssistantStream(e,t,n,r){let i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener(`abort`,()=>this.controller.abort()));let a={...n,stream:!0},o=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(let e of o)C(this,U,`m`,yi).call(this,e);if(o.controller.signal?.aborted)throw new E;return this._addRun(C(this,U,`m`,bi).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(Je(t)&&Je(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!Je(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw console.error(e),Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t.push(e):t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}};li=Oi,yi=function(e){if(!this.ended)switch(S(this,gi,e,`f`),C(this,U,`m`,Ci).call(this,e),e.event){case`thread.created`:break;case`thread.run.created`:case`thread.run.queued`:case`thread.run.in_progress`:case`thread.run.requires_action`:case`thread.run.completed`:case`thread.run.incomplete`:case`thread.run.failed`:case`thread.run.cancelling`:case`thread.run.cancelled`:case`thread.run.expired`:C(this,U,`m`,Di).call(this,e);break;case`thread.run.step.created`:case`thread.run.step.in_progress`:case`thread.run.step.delta`:case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:C(this,U,`m`,Si).call(this,e);break;case`thread.message.created`:case`thread.message.in_progress`:case`thread.message.delta`:case`thread.message.completed`:case`thread.message.incomplete`:C(this,U,`m`,xi).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`);default:}},bi=function(){if(this.ended)throw new w(`stream has ended, this shouldn't happen`);if(!C(this,fi,`f`))throw Error(`Final run has not been received`);return C(this,fi,`f`)},xi=function(e){let[t,n]=C(this,U,`m`,Ti).call(this,e,C(this,G,`f`));S(this,G,t,`f`),C(this,di,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=C(this,pi,`f`)){if(C(this,mi,`f`))switch(C(this,mi,`f`).type){case`text`:this._emit(`textDone`,C(this,mi,`f`).text,C(this,G,`f`));break;case`image_file`:this._emit(`imageFileDone`,C(this,mi,`f`).image_file,C(this,G,`f`));break}S(this,pi,n.index,`f`)}S(this,mi,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(C(this,pi,`f`)!==void 0){let t=e.data.content[C(this,pi,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,C(this,G,`f`));break;case`text`:this._emit(`textDone`,t.text,C(this,G,`f`));break}}C(this,G,`f`)&&this._emit(`messageDone`,e.data),S(this,G,void 0,`f`)}},Si=function(e){let t=C(this,U,`m`,wi).call(this,e);switch(S(this,vi,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==C(this,hi,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(C(this,K,`f`)&&this._emit(`toolCallDone`,C(this,K,`f`)),S(this,hi,e.index,`f`),S(this,K,t.step_details.tool_calls[e.index],`f`),C(this,K,`f`)&&this._emit(`toolCallCreated`,C(this,K,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:S(this,vi,void 0,`f`),e.data.step_details.type==`tool_calls`&&C(this,K,`f`)&&(this._emit(`toolCallDone`,C(this,K,`f`)),S(this,K,void 0,`f`)),this._emit(`runStepDone`,e.data,t);break;case`thread.run.step.in_progress`:break}},Ci=function(e){C(this,ui,`f`).push(e),this._emit(`event`,e)},wi=function(e){switch(e.event){case`thread.run.step.created`:return C(this,W,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=C(this,W,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=li.accumulateDelta(t,n.delta);C(this,W,`f`)[e.data.id]=r}return C(this,W,`f`)[e.data.id];case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:case`thread.run.step.in_progress`:C(this,W,`f`)[e.data.id]=e.data;break}if(C(this,W,`f`)[e.data.id])return C(this,W,`f`)[e.data.id];throw Error(`No snapshot available`)},Ti=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=C(this,U,`m`,Ei).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},Ei=function(e,t){return li.accumulateDelta(t,e)},Di=function(e){switch(S(this,_i,e.data,`f`),e.event){case`thread.run.created`:break;case`thread.run.queued`:break;case`thread.run.in_progress`:break;case`thread.run.requires_action`:case`thread.run.cancelled`:case`thread.run.failed`:case`thread.run.completed`:case`thread.run.expired`:case`thread.run.incomplete`:S(this,fi,e.data,`f`),C(this,K,`f`)&&(this._emit(`toolCallDone`,C(this,K,`f`)),S(this,K,void 0,`f`));break;case`thread.run.cancelling`:break}};var ki=class extends P{constructor(){super(...arguments),this.steps=new oi(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(F`/threads/${r}/runs/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/threads/${e}/runs`,N,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(F`/threads/${r}/runs/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return Oi.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ze(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return Oi.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(F`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return Oi.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}};ki.Steps=oi;var Ai=class extends P{constructor(){super(...arguments),this.runs=new ki(this._client),this.messages=new ai(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/threads/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t){return this._client.delete(F`/threads/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return Oi.createThreadAssistantStream(e,this._client.beta.threads,t)}};Ai.Runs=ki,Ai.Messages=ai;var ji=class extends P{constructor(){super(...arguments),this.realtime=new ti(this._client),this.chatkit=new ii(this._client),this.assistants=new Qr(this._client),this.threads=new Ai(this._client)}};ji.Realtime=ti,ji.ChatKit=ii,ji.Assistants=Qr,ji.Threads=Ai;var Mi=class extends P{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1})}},Ni=class extends P{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}/content`,{...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}},Pi=class extends P{constructor(){super(...arguments),this.content=new Ni(this._client)}create(e,t,n){return this._client.post(F`/containers/${e}/files`,dn({body:t,...n},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(F`/containers/${r}/files/${e}`,n)}list(e,t={},n){return this._client.getAPIList(F`/containers/${e}/files`,N,{query:t,...n})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(F`/containers/${r}/files/${e}`,{...n,headers:H([{Accept:`*/*`},n?.headers])})}};Pi.Content=Ni;var Fi=class extends P{constructor(){super(...arguments),this.files=new Pi(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList(`/containers`,N,{query:e,...t})}delete(e,t){return this._client.delete(F`/containers/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}};Fi.Files=Pi;var Ii=class extends P{create(e,t,n){let{include:r,...i}=t;return this._client.post(F`/conversations/${e}/items`,{query:{include:r},body:i,...n})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(F`/conversations/${r}/items/${e}`,{query:i,...n})}list(e,t={},n){return this._client.getAPIList(F`/conversations/${e}/items`,an,{query:t,...n})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(F`/conversations/${r}/items/${e}`,n)}},Li=class extends P{constructor(){super(...arguments),this.items=new Ii(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/conversations/${e}`,t)}update(e,t,n){return this._client.post(F`/conversations/${e}`,{body:t,...n})}delete(e,t){return this._client.delete(F`/conversations/${e}`,t)}};Li.Items=Ii;var Ri=class extends P{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&M(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t});return n?i:(M(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=si(t)}),e)))}},zi=class extends P{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(F`/evals/${r}/runs/${i}/output_items/${e}`,n)}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(F`/evals/${r}/runs/${e}/output_items`,N,{query:i,...n})}},Bi=class extends P{constructor(){super(...arguments),this.outputItems=new zi(this._client)}create(e,t,n){return this._client.post(F`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(F`/evals/${r}/runs/${e}`,n)}list(e,t={},n){return this._client.getAPIList(F`/evals/${e}/runs`,N,{query:t,...n})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(F`/evals/${r}/runs/${e}`,n)}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(F`/evals/${r}/runs/${e}`,n)}};Bi.OutputItems=zi;var Vi=class extends P{constructor(){super(...arguments),this.runs=new Bi(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/evals/${e}`,t)}update(e,t,n){return this._client.post(F`/evals/${e}`,{body:t,...n})}list(e={},t){return this._client.getAPIList(`/evals`,N,{query:e,...t})}delete(e,t){return this._client.delete(F`/evals/${e}`,t)}};Vi.Runs=Bi;var Hi=class extends P{create(e,t){return this._client.post(`/files`,dn({body:e,...t},this._client))}retrieve(e,t){return this._client.get(F`/files/${e}`,t)}list(e={},t){return this._client.getAPIList(`/files`,N,{query:e,...t})}delete(e,t){return this._client.delete(F`/files/${e}`,t)}content(e,t){return this._client.get(F`/files/${e}/content`,{...t,headers:H([{Accept:`application/binary`},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=1800*1e3}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Ze(t),a=await this.retrieve(e),Date.now()-i>n)throw new Ae({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}},Ui=class extends P{},Wi=class extends P{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t})}},Gi=class extends P{constructor(){super(...arguments),this.graders=new Wi(this._client)}};Gi.Graders=Wi;var Ki=class extends P{create(e,t,n){return this._client.getAPIList(F`/fine_tuning/checkpoints/${e}/permissions`,rn,{body:t,method:`post`,...n})}retrieve(e,t={},n){return this._client.get(F`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(F`/fine_tuning/checkpoints/${r}/permissions/${e}`,n)}},qi=class extends P{constructor(){super(...arguments),this.permissions=new Ki(this._client)}};qi.Permissions=Ki;var Ji=class extends P{list(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/checkpoints`,N,{query:t,...n})}},Yi=class extends P{constructor(){super(...arguments),this.checkpoints=new Ji(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t})}retrieve(e,t){return this._client.get(F`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,N,{query:e,...t})}cancel(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return this._client.getAPIList(F`/fine_tuning/jobs/${e}/events`,N,{query:t,...n})}pause(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(F`/fine_tuning/jobs/${e}/resume`,t)}};Yi.Checkpoints=Ji;var Xi=class extends P{constructor(){super(...arguments),this.methods=new Ui(this._client),this.jobs=new Yi(this._client),this.checkpoints=new qi(this._client),this.alpha=new Gi(this._client)}};Xi.Methods=Ui,Xi.Jobs=Yi,Xi.Checkpoints=qi,Xi.Alpha=Gi;var Zi=class extends P{},Qi=class extends P{constructor(){super(...arguments),this.graderModels=new Zi(this._client)}};Qi.GraderModels=Zi;var $i=class extends P{createVariation(e,t){return this._client.post(`/images/variations`,dn({body:e,...t},this._client))}edit(e,t){return this._client.post(`/images/edits`,dn({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1})}},ea=class extends P{retrieve(e,t){return this._client.get(F`/models/${e}`,t)}list(e){return this._client.getAPIList(`/models`,rn,e)}delete(e,t){return this._client.delete(F`/models/${e}`,t)}},ta=class extends P{create(e,t){return this._client.post(`/moderations`,{body:e,...t})}},na=class extends P{accept(e,t,n){return this._client.post(F`/realtime/calls/${e}/accept`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}hangup(e,t){return this._client.post(F`/realtime/calls/${e}/hangup`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}refer(e,t,n){return this._client.post(F`/realtime/calls/${e}/refer`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}reject(e,t={},n){return this._client.post(F`/realtime/calls/${e}/reject`,{body:t,...n,headers:H([{Accept:`*/*`},n?.headers])})}},ra=class extends P{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t})}},ia=class extends P{constructor(){super(...arguments),this.clientSecrets=new ra(this._client),this.calls=new na(this._client)}};ia.ClientSecrets=ra,ia.Calls=na;function aa(e,t){return!t||!ca(t)?{...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)}:oa(e,t)}function oa(e,t){let n=e.output.map(e=>{if(e.type===`function_call`)return{...e,parsed_arguments:da(t,e)};if(e.type===`message`){let n=e.content.map(e=>e.type===`output_text`?{...e,parsed:sa(t,e.text)}:e);return{...e,content:n}}return e}),r=Object.assign({},e,{output:n});return Object.getOwnPropertyDescriptor(e,`output_text`)||fa(r),Object.defineProperty(r,`output_parsed`,{enumerable:!0,get(){for(let e of r.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),r}function sa(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function ca(e){return!!An(e.text?.format)}function la(e){return e?.$brand===`auto-parseable-tool`}function ua(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function da(e,t){let n=ua(e.tools??[],t.name);return{...t,...t,parsed_arguments:la(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function fa(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var pa,ma,q,ha,ga,_a,va,ya,ba=class e extends er{constructor(e){super(),pa.add(this),ma.set(this,void 0),q.set(this,void 0),ha.set(this,void 0),S(this,ma,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createOrRetrieveResponse(e,t,n){let r=n?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener(`abort`,()=>this.controller.abort())),C(this,pa,`m`,ga).call(this);let i,a=null;`response_id`in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of i)C(this,pa,`m`,_a).call(this,e,a);if(i.controller.signal?.aborted)throw new E;return C(this,pa,`m`,va).call(this)}[(ma=new WeakMap,q=new WeakMap,ha=new WeakMap,pa=new WeakSet,ga=function(){this.ended||S(this,q,void 0,`f`)},_a=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=C(this,pa,`m`,ya).call(this,e);switch(n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new w(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new w(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new w(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new w(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e);break}},va=function(){if(this.ended)throw new w(`stream has ended, this shouldn't happen`);let e=C(this,q,`f`);if(!e)throw new w(`request ended without sending any events`);S(this,q,void 0,`f`);let t=xa(e,C(this,ma,`f`));return S(this,ha,t,`f`),t},ya=function(e){let t=C(this,q,`f`);if(!t){if(e.type!==`response.created`)throw new w(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return t=S(this,q,e.response,`f`),t}switch(e.type){case`response.output_item.added`:t.output.push(e.item);break;case`response.content_part.added`:{let n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);let r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?n.content.push(i):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||=[],n.content.push(i));break}case`response.output_text.delta`:{let n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);if(n.type===`message`){let t=n.content[e.content_index];if(!t)throw new w(`missing content at index ${e.content_index}`);if(t.type!==`output_text`)throw new w(`expected content to be 'output_text', got ${t.type}`);t.text+=e.delta}break}case`response.function_call_arguments.delta`:{let n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.reasoning_text.delta`:{let n=t.output[e.output_index];if(!n)throw new w(`missing output at index ${e.output_index}`);if(n.type===`reasoning`){let t=n.content?.[e.content_index];if(!t)throw new w(`missing content at index ${e.content_index}`);if(t.type!==`reasoning_text`)throw new w(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.completed`:S(this,q,e.response,`f`);break}return t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=C(this,ha,`f`);if(!e)throw new w(`stream ended without producing a ChatCompletion`);return e}};function xa(e,t){return aa(e,t)}var Sa=class extends P{list(e,t={},n){return this._client.getAPIList(F`/responses/${e}/input_items`,N,{query:t,...n})}},Ca=class extends P{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t})}},wa=class extends P{constructor(){super(...arguments),this.inputItems=new Sa(this._client),this.inputTokens=new Ca(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&fa(e),e))}retrieve(e,t={},n){return this._client.get(F`/responses/${e}`,{query:t,...n,stream:t?.stream??!1})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&fa(e),e))}delete(e,t){return this._client.delete(F`/responses/${e}`,{...t,headers:H([{Accept:`*/*`},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>oa(t,e))}stream(e,t){return ba.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(F`/responses/${e}/cancel`,t)}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t})}};wa.InputItems=Sa,wa.InputTokens=Ca;var Ta=class extends P{create(e,t,n){return this._client.post(F`/uploads/${e}/parts`,dn({body:t,...n},this._client))}},Ea=class extends P{constructor(){super(...arguments),this.parts=new Ta(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t})}cancel(e,t){return this._client.post(F`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(F`/uploads/${e}/complete`,{body:t,...n})}};Ea.Parts=Ta;var Da=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n)console.error(e.reason);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r},Oa=class extends P{create(e,t,n){return this._client.post(F`/vector_stores/${e}/file_batches`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/file_batches/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(F`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(F`/vector_stores/${r}/file_batches/${e}/files`,N,{query:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ze(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}return await Da(Array(a).fill(s).map(l)),await this.createAndPoll(e,{file_ids:c})}},ka=class extends P{create(e,t,n){return this._client.post(F`/vector_stores/${e}/files`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(F`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(F`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e,t={},n){return this._client.getAPIList(F`/vector_stores/${e}/files`,N,{query:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(F`/vector_stores/${r}/files/${e}`,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=H([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Ze(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(F`/vector_stores/${r}/files/${e}/content`,rn,{...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}},Aa=class extends P{constructor(){super(...arguments),this.files=new ka(this._client),this.fileBatches=new Oa(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}retrieve(e,t){return this._client.get(F`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}update(e,t,n){return this._client.post(F`/vector_stores/${e}`,{body:t,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}list(e={},t){return this._client.getAPIList(`/vector_stores`,N,{query:e,...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}delete(e,t){return this._client.delete(F`/vector_stores/${e}`,{...t,headers:H([{"OpenAI-Beta":`assistants=v2`},t?.headers])})}search(e,t,n){return this._client.getAPIList(F`/vector_stores/${e}/search`,rn,{body:t,method:`post`,...n,headers:H([{"OpenAI-Beta":`assistants=v2`},n?.headers])})}};Aa.Files=ka,Aa.FileBatches=Oa;var ja=class extends P{create(e,t){return this._client.post(`/videos`,un({body:e,...t},this._client))}retrieve(e,t){return this._client.get(F`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList(`/videos`,an,{query:e,...t})}delete(e,t){return this._client.delete(F`/videos/${e}`,t)}downloadContent(e,t={},n){return this._client.get(F`/videos/${e}/content`,{query:t,...n,headers:H([{Accept:`application/binary`},n?.headers]),__binaryResponse:!0})}remix(e,t,n){return this._client.post(F`/videos/${e}/remix`,un({body:t,...n},this._client))}},Ma,Na,Pa,Fa=class extends P{constructor(){super(...arguments),Ma.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");C(this,Ma,`m`,Na).call(this,n);let i=H([t]).values,a=C(this,Ma,`m`,Pa).call(this,i,`webhook-signature`),o=C(this,Ma,`m`,Pa).call(this,i,`webhook-timestamp`),s=C(this,Ma,`m`,Pa).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new Ve(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new Ve(`Webhook timestamp is too old`);if(c>l+r)throw new Ve(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new Ve(`The given webhook signature does not match the expected signature`)}};Ma=new WeakSet,Na=function(e){if(typeof e!=`string`||e.length===0)throw Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`)},Pa=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n};var Ia,La,Ra,za,J=class{constructor({baseURL:e=ci(`OPENAI_BASE_URL`),apiKey:t=ci(`OPENAI_API_KEY`),organization:n=ci(`OPENAI_ORG_ID`)??null,project:r=ci(`OPENAI_PROJECT_ID`)??null,webhookSecret:i=ci(`OPENAI_WEBHOOK_SECRET`)??null,...a}={}){if(Ia.add(this),Ra.set(this,void 0),this.completions=new Mi(this),this.chat=new Wr(this),this.embeddings=new Ri(this),this.files=new Hi(this),this.images=new $i(this),this.audio=new Xr(this),this.moderations=new ta(this),this.models=new ea(this),this.fineTuning=new Xi(this),this.graders=new Qi(this),this.vectorStores=new Aa(this),this.webhooks=new Fa(this),this.beta=new ji(this),this.batches=new Zr(this),this.uploads=new Ea(this),this.responses=new wa(this),this.realtime=new ia(this),this.conversations=new Li(this),this.evals=new Vi(this),this.containers=new Fi(this),this.videos=new ja(this),t===void 0)throw new w("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");let o={apiKey:t,organization:n,project:r,webhookSecret:i,...a,baseURL:e||`https://api.openai.com/v1`};if(!o.dangerouslyAllowBrowser&&$e())throw new w(`It looks like you're running in a browser-like environment.
8
+
9
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
10
+ If you understand the risks and have appropriate mitigations in place,
11
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
12
+
13
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
14
+
15
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
16
+ `);this.baseURL=o.baseURL,this.timeout=o.timeout??La.DEFAULT_TIMEOUT,this.logger=o.logger??console;let s=`warn`;this.logLevel=s,this.logLevel=Rt(o.logLevel,`ClientOptions.logLevel`,this)??Rt(ci(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??s,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??st(),S(this,Ra,ft,`f`),this._options=o,this.apiKey=typeof t==`string`?t:`Missing Key`,this.organization=n,this.project=r,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return H([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Ot(e,{arrayFormat:`brackets`})}getUserAgent(){return`${this.constructor.name}/JS ${Qe}`}defaultIdempotencyKey(){return`stainless-node-retry-${Ee()}`}makeStatusError(e,t,n,r){return T.generate(e,t,n,r)}async _callApiKey(){let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof w?e:new w(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new w(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!C(this,Ia,`m`,za).call(this)&&n||this.baseURL,i=Ue(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery();return Ke(a)||(t={...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new $t(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??=i,await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});let c=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),l=n===void 0?``:`, retryOf: ${n}`,u=Date.now();if(M(this).debug(`[${c}] sending request`,Ut({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new E;let d=new AbortController,f=await this.fetchWithTimeout(o,a,s,d).catch(Oe),p=Date.now();if(f instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new E;let i=De(f)||/timed? ?out/i.test(String(f)+(`cause`in f?String(f.cause):``));if(t)return M(this).info(`[${c}] connection ${i?`timed out`:`failed`} - ${e}`),M(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (${e})`,Ut({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,n??c);throw M(this).info(`[${c}] connection ${i?`timed out`:`failed`} - error; no more retries left`),M(this).debug(`[${c}] connection ${i?`timed out`:`failed`} (error; no more retries left)`,Ut({retryOfRequestLogID:n,url:o,durationMs:p-u,message:f.message})),i?new Ae:new ke({cause:f})}let m=`[${c}${l}${[...f.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${f.ok?`succeeded`:`failed`} with status ${f.status} in ${p-u}ms`;if(!f.ok){let e=await this.shouldRetry(f);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await dt(f.body),M(this).info(`${m} - ${e}`),M(this).debug(`[${c}] response error (${e})`,Ut({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,n??c,f.headers)}let i=e?`error; no more retries left`:`error; not retryable`;M(this).info(`${m} - ${i}`);let a=await f.text().catch(e=>Oe(e).message),o=Xe(a),s=o?void 0:a;throw M(this).debug(`[${c}] response error (${i})`,Ut({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,message:s,durationMs:Date.now()-u})),this.makeStatusError(f.status,o,s,f.headers)}return M(this).info(m),M(this).debug(`[${c}] response start`,Ut({retryOfRequestLogID:n,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:d,requestLogID:c,retryOfRequestLogID:n,startTime:u}}getAPIList(e,t,n){return this.requestAPIList(t,{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new nn(this,n,e)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{};i&&i.addEventListener(`abort`,()=>r.abort());let s=setTimeout(()=>r.abort(),n),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:r.signal,...c?{duplex:`half`}:{},method:`GET`,...o};a&&(l.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(s)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(!(i&&0<=i&&i<60*1e3)){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Ze(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&Ye(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n});return{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||=this.defaultIdempotencyKey(),i[this.idempotencyHeader]=e.idempotencyKey);let a=H([i,{Accept:`application/json`,"User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...ot(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=H([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e==`string`&&n.values.has(`content-type`)||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e==`object`&&(Symbol.asyncIterator in e||Symbol.iterator in e&&`next`in e&&typeof e.next==`function`)?{bodyHeaders:void 0,body:lt(e)}:C(this,Ra,`f`).call(this,{body:e,headers:n})}};La=J,Ra=new WeakMap,Ia=new WeakSet,za=function(){return this.baseURL!==`https://api.openai.com/v1`},J.OpenAI=La,J.DEFAULT_TIMEOUT=6e5,J.OpenAIError=w,J.APIError=T,J.APIConnectionError=ke,J.APIConnectionTimeoutError=Ae,J.APIUserAbortError=E,J.NotFoundError=Pe,J.ConflictError=Fe,J.RateLimitError=Le,J.BadRequestError=je,J.AuthenticationError=Me,J.InternalServerError=Re,J.PermissionDeniedError=Ne,J.UnprocessableEntityError=Ie,J.InvalidWebhookSignatureError=Ve,J.toFile=Sn,J.Completions=Mi,J.Chat=Wr,J.Embeddings=Ri,J.Files=Hi,J.Images=$i,J.Audio=Xr,J.Moderations=ta,J.Models=ea,J.FineTuning=Xi,J.Graders=Qi,J.VectorStores=Aa,J.Webhooks=Fa,J.Beta=ji,J.Batches=Zr,J.Uploads=Ea,J.Responses=wa,J.Realtime=ia,J.Conversations=Li,J.Evals=Vi,J.Containers=Fi,J.Videos=ja;function Ba(e){if(!e||typeof e!=`object`)return e;let t;return e.constructor.name===Ae.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`TimeoutError`):e.constructor.name===E.name&&`message`in e&&typeof e.message==`string`?(t=Error(e.message),t.name=`AbortError`):t=`status`in e&&e.status===400&&`message`in e&&typeof e.message==`string`&&e.message.includes(`tool_calls`)?Te(e,`INVALID_TOOL_RESULTS`):`status`in e&&e.status===401?Te(e,`MODEL_AUTHENTICATION`):`status`in e&&e.status===429?Te(e,`MODEL_RATE_LIMIT`):`status`in e&&e.status===404?Te(e,`MODEL_NOT_FOUND`):e,t}var Va=e=>e();function Ha(e){return e?!!(/^o\d/.test(e??``)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`)):!1}function Ua(e){return e.role!==`system`&&e.role!==`developer`&&e.role!==`assistant`&&e.role!==`user`&&e.role!==`function`&&e.role!==`tool`&&console.warn(`Unknown message role: ${e.role}`),e.role}function Wa(e){return e.metadata?.filename??e.metadata?.name??e.metadata?.title}function Ga(e){let t=e.metadata?.filename??e.metadata?.name??e.metadata?.title;if(!t)throw Error(`a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks`);return t}function Ka(e){let t=e._getType();switch(t){case`system`:return`system`;case`ai`:return`assistant`;case`human`:return`user`;case`function`:return`function`;case`tool`:return`tool`;case`generic`:if(!ae.isInstance(e))throw Error(`Invalid generic chat message`);return Ua(e);default:throw Error(`Unknown message type: ${t}`)}}function qa(e){return e.includes(`gpt-5.2-pro`)}function Ja(e){let{azureOpenAIApiDeploymentName:t,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:a,azureADTokenProvider:o,azureOpenAIEndpoint:s}=e;if((r||o)&&i&&t)return`${i}/${t}`;if((r||o)&&s&&t)return`${s}/openai/deployments/${t}`;if(r||o){if(!n)throw Error(`azureOpenAIApiInstanceName is required when using azureOpenAIApiKey`);if(!t)throw Error(`azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey`);return`https://${n}.openai.azure.com/openai/deployments/${t}`}return a}function Ya(e){return typeof Headers<`u`&&typeof e==`object`&&!!e&&Object.prototype.toString.call(e)===`[object Headers]`}function Xa(e){let t=Va(()=>{if(Ya(e))return e;if(Array.isArray(e))return new Headers(e);if(typeof e==`object`&&e&&`values`in e&&Ya(e.values))return e.values;if(typeof e==`object`&&e){let t=Object.entries(e).filter(([,e])=>typeof e==`string`).map(([e,t])=>[e,t]);return new Headers(t)}return new Headers});return Object.fromEntries(t.entries())}function Za(){let e=u();return(e===`node`||e===`deno`)&&(e=`(${e}/${process.version}; browser; ${process.arch})`),e}function Qa(e,t=!1,n=`1.0.0`){let r=Xa(e),i=Za(),a=`langchainjs${t?`-azure`:``}-openai`;return{...r,"User-Agent":r[`User-Agent`]?`${a}/${n} (${i})${r[`User-Agent`]}`:`${a}/${n} (${i})`}}function $a(e,t){let n;return n=_e(e)?ye(e):e,t?.strict!==void 0&&(n.function.strict=t.strict),n}function eo(e){return e.anyOf!==void 0&&Array.isArray(e.anyOf)}function to(e){let t=[`namespace functions {`,``];for(let n of e)n.description&&t.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(t.push(`type ${n.name} = (_: {`),t.push(no(n.parameters,0)),t.push(`}) => any;`)):t.push(`type ${n.name} = () => any;`),t.push(``);return t.push(`} // namespace functions`),t.join(`
17
+ `)}function no(e,t){let n=[];for(let[r,i]of Object.entries(e.properties??{}))i.description&&t<2&&n.push(`// ${i.description}`),e.required?.includes(r)?n.push(`${r}: ${ro(i,t)},`):n.push(`${r}?: ${ro(i,t)},`);return n.map(e=>` `.repeat(t)+e).join(`
18
+ `)}function ro(e,t){if(eo(e))return e.anyOf.map(e=>ro(e,t)).join(` | `);switch(e.type){case`string`:return e.enum?e.enum.map(e=>`"${e}"`).join(` | `):`string`;case`number`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`integer`:return e.enum?e.enum.map(e=>`${e}`).join(` | `):`number`;case`boolean`:return`boolean`;case`null`:return`null`;case`object`:return[`{`,no(e,t+2),`}`].join(`
19
+ `);case`array`:return e.items?`${ro(e.items,t)}[]`:`any[]`;default:return``}}function io(e){if(e)return e===`any`||e===`required`?`required`:e===`auto`?`auto`:e===`none`?`none`:typeof e==`string`?{type:`function`,function:{name:e}}:e}function ao(e){return`type`in e&&e.type!==`function`}function oo(e){return typeof e==`object`&&!!e&&`extras`in e&&typeof e.extras==`object`&&e.extras!==null&&`providerToolDefinition`in e.extras&&typeof e.extras.providerToolDefinition==`object`&&e.extras.providerToolDefinition!==null}function so(e){return typeof e==`object`&&!!e&&`type`in e&&e.type!==`function`}function co(e){return typeof e==`object`&&!!e&&`metadata`in e&&typeof e.metadata==`object`&&e.metadata!==null&&`customTool`in e.metadata&&typeof e.metadata.customTool==`object`&&e.metadata.customTool!==null}function lo(e){return`type`in e&&e.type===`custom`&&`custom`in e&&typeof e.custom==`object`&&e.custom!==null}function uo(e){if(e.type===`custom_tool_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:e.name,isCustomTool:!0,args:{input:e.input}}}function fo(e){if(e.type===`computer_call`)return{...e,type:`tool_call`,call_id:e.id,id:e.call_id,name:`computer_use`,isComputerTool:!0,args:{action:e.action}}}function po(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isComputerTool`in e&&e.isComputerTool===!0}function mo(e){return typeof e==`object`&&!!e&&`type`in e&&e.type===`tool_call`&&`isCustomTool`in e&&e.isCustomTool===!0}function ho(e){return{type:`custom`,name:e.custom.name,description:e.custom.description,format:(()=>{if(e.custom.format){if(e.custom.format.type===`grammar`)return{type:`grammar`,definition:e.custom.format.grammar.definition,syntax:e.custom.format.grammar.syntax};if(e.custom.format.type===`text`)return{type:`text`}}})()}}function go(e){return{type:`custom`,custom:{name:e.name,description:e.description,format:(()=>{if(e.format){if(e.format.type===`grammar`)return{type:`grammar`,grammar:{definition:e.format.definition,syntax:e.format.syntax}};if(e.format.type===`text`)return{type:`text`}}})()}}}var _o=Symbol(`Let zodToJsonSchema decide on which parser to use`),vo={name:void 0,$refStrategy:`root`,effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,nullableStrategy:`from-target`,removeAdditionalStrategy:`passthrough`,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`},yo=e=>typeof e==`string`?{...vo,basePath:[`#`],definitions:{},name:e}:{...vo,basePath:[`#`],definitions:{},...e},bo=e=>`_def`in e?e._def:e;function xo(e){if(!e)return!0;for(let t in e)return!1;return!0}var So=e=>{let t=yo(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[bo(n),{def:bo(n),path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function Co(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function Y(e,t,n,r,i){e[t]=n,Co(e,t,r,i)}function wo(){return{}}function To(e,n){let r={type:`array`};return e.type?._def?.typeName!==t.ZodAny&&(r.items=Q(e.type._def,{...n,currentPath:[...n.currentPath,`items`]})),e.minLength&&Y(r,`minItems`,e.minLength.value,e.minLength.message,n),e.maxLength&&Y(r,`maxItems`,e.maxLength.value,e.maxLength.message,n),e.exactLength&&(Y(r,`minItems`,e.exactLength.value,e.exactLength.message,n),Y(r,`maxItems`,e.exactLength.value,e.exactLength.message,n)),r}function Eo(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?Y(n,`minimum`,r.value,r.message,t):Y(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Y(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Y(n,`maximum`,r.value,r.message,t):Y(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Y(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Y(n,`multipleOf`,r.value,r.message,t);break}return n}function Do(){return{type:`boolean`}}function Oo(e,t){return Q(e.type._def,t)}var ko=(e,t)=>Q(e.innerType._def,t);function Ao(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>Ao(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return jo(e,t)}}var jo=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:Y(n,`minimum`,r.value,r.message,t);break;case`max`:Y(n,`maximum`,r.value,r.message,t);break}return n};function Mo(e,t){return{...Q(e.innerType._def,t),default:e.defaultValue()}}function No(e,t,n){return t.effectStrategy===`input`?Q(e.schema._def,t,n):{}}function Po(e){return{type:`string`,enum:[...e.values]}}var Fo=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function Io(e,t){let n=[Q(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Q(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(Fo(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Lo(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}var Ro,zo={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(Ro===void 0&&(Ro=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Ro),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function Bo(e,t){let n={type:`string`};function r(e){return t.patternStrategy===`escape`?Vo(e):e}if(e.checks)for(let i of e.checks)switch(i.kind){case`min`:Y(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t);break;case`max`:Y(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:X(n,`email`,i.message,t);break;case`format:idn-email`:X(n,`idn-email`,i.message,t);break;case`pattern:zod`:Z(n,zo.email,i.message,t);break}break;case`url`:X(n,`uri`,i.message,t);break;case`uuid`:X(n,`uuid`,i.message,t);break;case`regex`:Z(n,i.regex,i.message,t);break;case`cuid`:Z(n,zo.cuid,i.message,t);break;case`cuid2`:Z(n,zo.cuid2,i.message,t);break;case`startsWith`:Z(n,RegExp(`^${r(i.value)}`),i.message,t);break;case`endsWith`:Z(n,RegExp(`${r(i.value)}$`),i.message,t);break;case`datetime`:X(n,`date-time`,i.message,t);break;case`date`:X(n,`date`,i.message,t);break;case`time`:X(n,`time`,i.message,t);break;case`duration`:X(n,`duration`,i.message,t);break;case`length`:Y(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,i.value):i.value,i.message,t),Y(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,i.value):i.value,i.message,t);break;case`includes`:Z(n,RegExp(r(i.value)),i.message,t);break;case`ip`:i.version!==`v6`&&X(n,`ipv4`,i.message,t),i.version!==`v4`&&X(n,`ipv6`,i.message,t);break;case`emoji`:Z(n,zo.emoji,i.message,t);break;case`ulid`:Z(n,zo.ulid,i.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:X(n,`binary`,i.message,t);break;case`contentEncoding:base64`:Y(n,`contentEncoding`,`base64`,i.message,t);break;case`pattern:zod`:Z(n,zo.base64,i.message,t);break}break;case`nanoid`:Z(n,zo.nanoid,i.message,t);case`toLowerCase`:case`toUpperCase`:case`trim`:break;default:(e=>{})(i)}return n}var Vo=e=>Array.from(e).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(``),X=(e,t,n,r)=>{e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Y(e,`format`,t,n,r)},Z=(e,t,n,r)=>{e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:Ho(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Y(e,`pattern`,Ho(t,r),n,r)},Ho=(e,t)=>{let n=typeof e==`function`?e():e;if(!t.applyRegexFlags||!n.flags)return n.source;let r={i:n.flags.includes(`i`),m:n.flags.includes(`m`),s:n.flags.includes(`s`)},i=r.i?n.source.toLowerCase():n.source,a=``,o=!1,s=!1,c=!1;for(let e=0;e<i.length;e++){if(o){a+=i[e],o=!1;continue}if(r.i){if(s){if(i[e].match(/[a-z]/)){c?(a+=i[e],a+=`${i[e-2]}-${i[e]}`.toUpperCase(),c=!1):i[e+1]===`-`&&i[e+2]?.match(/[a-z]/)?(a+=i[e],c=!0):a+=`${i[e]}${i[e].toUpperCase()}`;continue}}else if(i[e].match(/[a-z]/)){a+=`[${i[e]}${i[e].toUpperCase()}]`;continue}}if(r.m){if(i[e]===`^`){a+=`(^|(?<=[\r
20
+ ]))`;continue}else if(i[e]===`$`){a+=`($|(?=[\r
21
+ ]))`;continue}}if(r.s&&i[e]===`.`){a+=s?`${i[e]}\r\n`:`[${i[e]}\r\n]`;continue}a+=i[e],i[e]===`\\`?o=!0:s&&i[e]===`]`?s=!1:!s&&i[e]===`[`&&(s=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return a};function Uo(e,n){if(n.target===`openApi3`&&e.keyType?._def.typeName===t.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((t,r)=>({...t,[r]:Q(e.valueType._def,{...n,currentPath:[...n.currentPath,`properties`,r]})??{}}),{}),additionalProperties:!1};let r={type:`object`,additionalProperties:Q(e.valueType._def,{...n,currentPath:[...n.currentPath,`additionalProperties`]})??{}};if(n.target===`openApi3`)return r;if(e.keyType?._def.typeName===t.ZodString&&e.keyType._def.checks?.length){let t=Object.entries(Bo(e.keyType._def,n)).reduce((e,[t,n])=>t===`type`?e:{...e,[t]:n},{});return{...r,propertyNames:t}}else if(e.keyType?._def.typeName===t.ZodEnum)return{...r,propertyNames:{enum:e.keyType._def.values}};return r}function Wo(e,t){return t.mapStrategy===`record`?Uo(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Q(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||{},Q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||{}],minItems:2,maxItems:2}}}function Go(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function Ko(){return{not:{}}}function qo(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}var Jo={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function Yo(e,t){if(t.target===`openApi3`)return Xo(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in Jo&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=Jo[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Xo(e,t)}var Xo=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Zo(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`||t.nullableStrategy===`property`?{type:Jo[e.innerType._def.typeName],nullable:!0}:{type:[Jo[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Qo(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,Co(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?Y(n,`minimum`,r.value,r.message,t):Y(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),Y(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?Y(n,`maximum`,r.value,r.message,t):Y(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),Y(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:Y(n,`multipleOf`,r.value,r.message,t);break}return n}function $o(e,t){return t.removeAdditionalStrategy===`strict`?e.catchall._def.typeName===`ZodNever`?e.unknownKeys!==`strict`:Q(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0:e.catchall._def.typeName===`ZodNever`?e.unknownKeys===`passthrough`:Q(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??!0}function es(e,t){let n={type:`object`,...Object.entries(e.shape()).reduce((e,[n,r])=>{if(r===void 0||r._def===void 0)return e;let i=[...t.currentPath,`properties`,n],a=Q(r._def,{...t,currentPath:i,propertyPath:i});if(a===void 0)return e;if(t.openaiStrictMode&&r.isOptional()&&!r.isNullable()&&r._def?.defaultValue===void 0)throw 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:{...e.properties,[n]:a},required:r.isOptional()&&!t.openaiStrictMode?e.required:[...e.required,n]}},{properties:{},required:[]}),additionalProperties:$o(e,t)};return n.required.length||delete n.required,n}var ts=(e,t)=>{if(t.propertyPath&&t.currentPath.slice(0,t.propertyPath.length).toString()===t.propertyPath.toString())return Q(e.innerType._def,{...t,currentPath:t.currentPath});let n=Q(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:{}},n]}:{}},ns=(e,t)=>{if(t.pipeStrategy===`input`)return Q(e.in._def,t);if(t.pipeStrategy===`output`)return Q(e.out._def,t);let n=Q(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Q(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function rs(e,t){return Q(e.type._def,t)}function is(e,t){let n={type:`array`,uniqueItems:!0,items:Q(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&Y(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&Y(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function as(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Q(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Q(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function os(){return{not:{}}}function ss(){return{}}var cs=(e,t)=>Q(e.innerType._def,t);function Q(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==_o)return i}if(r&&!n){let e=ls(r,t);if(e!==void 0)return`$ref`in e&&t.seenRefs.add(e.$ref),e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=ds(e,e.typeName,t,n);return a&&fs(e,t,a),i.jsonSchema=a,a}var ls=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`extract-to-root`:let n=e.path.slice(t.basePath.length+1).join(`_`);return n!==t.name&&t.nameStrategy===`duplicate-ref`&&(t.definitions[n]=e.def),{$ref:[...t.basePath,t.definitionPath,n].join(`/`)};case`relative`:return{$ref:us(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),{}):t.$refStrategy===`seen`?{}:void 0}},us=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)},ds=(e,n,r,i)=>{switch(n){case t.ZodString:return Bo(e,r);case t.ZodNumber:return Qo(e,r);case t.ZodObject:return es(e,r);case t.ZodBigInt:return Eo(e,r);case t.ZodBoolean:return Do();case t.ZodDate:return Ao(e,r);case t.ZodUndefined:return os();case t.ZodNull:return qo(r);case t.ZodArray:return To(e,r);case t.ZodUnion:case t.ZodDiscriminatedUnion:return Yo(e,r);case t.ZodIntersection:return Io(e,r);case t.ZodTuple:return as(e,r);case t.ZodRecord:return Uo(e,r);case t.ZodLiteral:return Lo(e,r);case t.ZodEnum:return Po(e);case t.ZodNativeEnum:return Go(e);case t.ZodNullable:return Zo(e,r);case t.ZodOptional:return ts(e,r);case t.ZodMap:return Wo(e,r);case t.ZodSet:return is(e,r);case t.ZodLazy:return Q(e.getter()._def,r);case t.ZodPromise:return rs(e,r);case t.ZodNaN:case t.ZodNever:return Ko();case t.ZodEffects:return No(e,r,i);case t.ZodAny:return wo();case t.ZodUnknown:return ss();case t.ZodDefault:return Mo(e,r);case t.ZodBranded:return Oo(e,r);case t.ZodReadonly:return cs(e,r);case t.ZodCatch:return ko(e,r);case t.ZodPipeline:return ns(e,r);case t.ZodFunction:case t.ZodVoid:case t.ZodSymbol:return;default:return(e=>void 0)(n)}},fs=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),ps=(e,t)=>{let n=So(t),r=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,i=Q(e._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},a=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;a!==void 0&&(i.title=a);let o=(()=>{if(xo(n.definitions))return;let e={},t=new Set;for(let r=0;r<500;r++){let r=Object.entries(n.definitions).filter(([e])=>!t.has(e));if(r.length===0)break;for(let[i,a]of r)e[i]=Q(bo(a),{...n,currentPath:[...n.basePath,n.definitionPath,i]},!0)??{},t.add(i)}return e})(),s=r===void 0?o?{...i,[n.definitionPath]:o}:i:n.nameStrategy===`duplicate-ref`?{...i,...o||n.seenRefs.size?{[n.definitionPath]:{...o,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,r].join(`/`),[n.definitionPath]:{...o,[r]:i}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:n.target===`jsonSchema2019-09`&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),s};function ms(e){if(e.type!==`object`)throw Error(`Root schema must have type: 'object' but got type: ${e.type?`'${e.type}'`:`undefined`}`);let t=structuredClone(e);return $(t,[],t)}function hs(e){if(typeof e==`boolean`)return!1;if(e.type===`null`)return!0;for(let t of e.oneOf??[])if(hs(t))return!0;for(let t of e.anyOf??[])if(hs(t))return!0;return!1}function $(e,t,n){if(typeof e==`boolean`)throw TypeError(`Expected object schema but got boolean; path=${t.join(`/`)}`);if(!_s(e))throw TypeError(`Expected ${JSON.stringify(e)} to be an object; path=${t.join(`/`)}`);let r=e.$defs;if(_s(r))for(let[e,i]of Object.entries(r))$(i,[...t,`$defs`,e],n);let i=e.definitions;if(_s(i))for(let[e,r]of Object.entries(i))$(r,[...t,`definitions`,e],n);e.type===`object`&&!(`additionalProperties`in e)&&(e.additionalProperties=!1);let a=e.required??[],o=e.properties;if(_s(o)){for(let[e,n]of Object.entries(o))if(!hs(n)&&!a.includes(e))throw Error(`Zod field at \`${[...t,`properties`,e].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`);e.required=Object.keys(o),e.properties=Object.fromEntries(Object.entries(o).map(([e,r])=>[e,$(r,[...t,`properties`,e],n)]))}let s=e.items;_s(s)&&(e.items=$(s,[...t,`items`],n));let c=e.anyOf;Array.isArray(c)&&(e.anyOf=c.map((e,r)=>$(e,[...t,`anyOf`,String(r)],n)));let l=e.allOf;if(Array.isArray(l))if(l.length===1){let r=$(l[0],[...t,`allOf`,`0`],n);Object.assign(e,r),delete e.allOf}else e.allOf=l.map((e,r)=>$(e,[...t,`allOf`,String(r)],n));e.default===null&&delete e.default;let u=e.$ref;if(u&&vs(e,1)){if(typeof u!=`string`)throw TypeError(`Received non-string $ref - ${u}; path=${t.join(`/`)}`);let r=gs(n,u);if(typeof r==`boolean`)throw Error(`Expected \`$ref: ${u}\` to resolve to an object schema but got boolean`);if(!_s(r))throw Error(`Expected \`$ref: ${u}\` to resolve to an object but got ${JSON.stringify(r)}`);return Object.assign(e,{...r,...e}),delete e.$ref,$(e,t,n)}return e}function gs(e,t){if(!t.startsWith(`#/`))throw Error(`Unexpected $ref format ${JSON.stringify(t)}; Does not start with #/`);let n=t.slice(2).split(`/`),r=e;for(let e of n){if(!_s(r))throw Error(`encountered non-object entry while resolving ${t} - ${JSON.stringify(r)}`);let n=r[e];if(n===void 0)throw Error(`Key ${e} not found while resolving ${t}`);r=n}return r}function _s(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function vs(e,t){let n=0;for(let r in e)if(n++,n>t)return!0;return!1}function ys(e,t){return ps(e,{openaiStrictMode:!0,name:t.name,nameStrategy:`duplicate-ref`,$refStrategy:`extract-to-root`,nullableStrategy:`property`})}function bs(e){return ms(ce(e,{target:`draft-7`}))}function xs(e){return`_zod`in e}function Ss(e,t,n){return kn({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:xs(e)?bs(e):ys(e,{name:t})}},t=>e.parse(JSON.parse(t)))}var Cs=[`jsonSchema`,`functionCalling`,`jsonMode`];function ws(e,t){if(t!==void 0&&!Cs.includes(t))throw Error(`Invalid method: ${t}. Supported methods are: ${Cs.join(`, `)}`);let n=!e.startsWith(`gpt-3`)&&!e.startsWith(`gpt-4-`)&&e!==`gpt-4`;if(n&&!t)return`jsonSchema`;if(!n&&t===`jsonSchema`)throw Error(`JSON Schema is not supported for model "${e}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return t??`functionCalling`}function Ts(e,t){let n={...e};return Object.defineProperties(n,{$brand:{value:`auto-parseable-response-format`,enumerable:!1},$parseRaw:{value:t,enumerable:!1}}),n}function Es(e,t,n){if(h(e))return Ss(e,t,n);if(se(e))return Ts({type:`json_schema`,json_schema:{...n,name:t,strict:!0,schema:c(e,{cycles:`ref`,reused:`ref`,override(e){e.jsonSchema.title=t}})}},t=>le(e,JSON.parse(t)));throw Error(`Unsupported schema response format`)}function Ds(e,t){if(t&&typeof t==`object`&&`images`in t&&Array.isArray(t.images)){let n=t.images.filter(e=>typeof e?.image_url?.url==`string`).map(e=>({type:`image`,url:e.image_url.url}));return[{type:`text`,text:e},...n]}return e}var Os={"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-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":{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},"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-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-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-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},"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},"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},"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-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},"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},"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},"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-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},"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-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},"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},"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},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-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},"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},"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},"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-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},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},"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-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},"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},"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},"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}},ks=class extends ve{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`.split(`.`)}getLsParams(e){let t=this.invocationParams(e);return{ls_provider:`openai`,ls_model_name:this.model,ls_model_type:`chat`,ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{});let t=typeof e?.configuration?.apiKey==`string`||typeof e?.configuration?.apiKey==`function`?e?.configuration?.apiKey:void 0;this.apiKey=e?.apiKey??t??d(`OPENAI_API_KEY`),this.organization=e?.configuration?.organization??d(`OPENAI_ORGANIZATION`),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.promptCacheRetention=e?.promptCacheRetention??this.promptCacheRetention,this.verbosity=e?.verbosity??this.verbosity,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.disableStreaming&&(this.streaming=!1),e?.streaming===!1&&(this.disableStreaming=!0),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!Ha(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),e?.reasoningEffort!==void 0&&t?.effort===void 0&&(t={...t,effort:e.reasoningEffort}),t}_getResponseFormat(e){return e&&e.type===`json_schema`&&e.json_schema.schema&&l(e.json_schema.schema)?Es(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){let e=Ja({baseURL:this.clientConfig.baseURL}),t={...this.clientConfig,baseURL:e,timeout:this.timeout,maxRetries:0};t.baseURL||delete t.baseURL,t.defaultHeaders=Qa(t.defaultHeaders),this.client=new J(t)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return co(e)?go(e.metadata.customTool):ge(e)?t?.strict===void 0?e:{...e,function:{...e.function,strict:t.strict}}:$a(e,t)}bindTools(e,t){let n;return t?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=t.strict,this.withConfig({tools:e.map(e=>ao(e)||co(e)?e:oo(e)?e.extras.providerToolDefinition:this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((e,t)=>(t&&t.tokenUsage&&(e.tokenUsage.completionTokens+=t.tokenUsage.completionTokens??0,e.tokenUsage.promptTokens+=t.tokenUsage.promptTokens??0,e.tokenUsage.totalTokens+=t.tokenUsage.totalTokens??0),e),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,n=0,r=0;this.model===`gpt-3.5-turbo-0301`?(n=4,r=-1):(n=3,r=1);let i=await Promise.all(e.map(async e=>{let[i,a]=await Promise.all([this.getNumTokens(e.content),this.getNumTokens(Ka(e))]),o=e.name===void 0?0:r+await this.getNumTokens(e.name),s=i+n+a+o,c=e;if(c._getType()===`function`&&(s-=2),c.additional_kwargs?.function_call&&(s+=3),c?.additional_kwargs.function_call?.name&&(s+=await this.getNumTokens(c.additional_kwargs.function_call?.name)),c.additional_kwargs.function_call?.arguments)try{s+=await this.getNumTokens(JSON.stringify(JSON.parse(c.additional_kwargs.function_call?.arguments)))}catch(e){console.error(`Error parsing function arguments`,e,JSON.stringify(c.additional_kwargs.function_call)),s+=await this.getNumTokens(c.additional_kwargs.function_call?.arguments)}return t+=s,s}));return t+=3,{totalCount:t,countPerMessage:i}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async e=>e.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([e.message])).countPerMessage[0]:await this.getNumTokens(e.message.content)))).reduce((e,t)=>e+t,0)}async _getEstimatedTokenCountFromPrompt(e,t,n){let r=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&n!==`auto`){let e=to(t);r+=await this.getNumTokens(e),r+=9}return t&&e.find(e=>e._getType()===`system`)&&(r-=4),n===`none`?r+=1:typeof n==`object`&&(r+=await this.getNumTokens(n.name)+4),r}async moderateContent(e,t){let n=this._getClientOptions(t?.options),r={input:e,model:t?.model??`omni-moderation-latest`};return this.caller.call(async()=>{try{return await this.client.moderations.create(r,n)}catch(e){throw Ba(e)}})}get profile(){return Os[this.model]??{}}_getStructuredOutputMethod(e){let t={...e};if(!this.model.startsWith(`gpt-3`)&&!this.model.startsWith(`gpt-4-`)&&this.model!==`gpt-4`){if(t?.method===void 0)return`jsonSchema`}else t.method===`jsonSchema`&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(t,n){let r,i,{schema:a,name:o,includeRaw:s}={...n,schema:t};if(n?.strict!==void 0&&n.method===`jsonMode`)throw Error("Argument `strict` is only supported for `method` = 'function_calling'");let u=ws(this.model,n?.method);if(u===`jsonMode`){i=l(a)?me.fromZodSchema(a):new be;let e=c(a);r=this.withConfig({outputVersion:`v0`,response_format:{type:`json_object`},ls_structured_output_format:{kwargs:{method:`json_mode`},schema:{title:o??`extract`,...e}}})}else if(u===`jsonSchema`){let t={name:o??`extract`,description:e(a),schema:a,strict:n?.strict},s=c(t.schema);if(r=this.withConfig({outputVersion:`v0`,response_format:{type:`json_schema`,json_schema:t},ls_structured_output_format:{kwargs:{method:`json_schema`},schema:{title:t.name,description:t.description,...s}}}),l(a)){let e=me.fromZodSchema(a);i=ne.from(t=>`parsed`in t.additional_kwargs?t.additional_kwargs.parsed:e)}else i=new be}else{let e=o??`extract`;if(l(a)){let t=c(a);r=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:{name:e,description:t.description,parameters:t}}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...t}},...n?.strict===void 0?{}:{strict:n.strict}}),i=new Se({returnSingle:!0,keyName:e,zodSchema:a})}else{let t;typeof a.name==`string`&&typeof a.parameters==`object`&&a.parameters!=null?(t=a,e=a.name):(e=a.title??e,t={name:e,description:a.description??``,parameters:a});let o=c(a);r=this.withConfig({outputVersion:`v0`,tools:[{type:`function`,function:t}],tool_choice:{type:`function`,function:{name:e}},ls_structured_output_format:{kwargs:{method:`function_calling`},schema:{title:e,...o}},...n?.strict===void 0?{}:{strict:n.strict}}),i=new Se({returnSingle:!0,keyName:e})}}if(!s)return r.pipe(i);let d=he.assign({parsed:(e,t)=>i.invoke(e.raw,t)}),f=he.assign({parsed:()=>null}),p=d.withFallbacks({fallbacks:[f]});return ie.from([{raw:r},p])}},As={providerName:`ChatOpenAI`,fromStandardTextBlock(e){return{type:`text`,text:e.text}},fromStandardImageBlock(e){if(e.source_type===`url`)return{type:`image_url`,image_url:{url:e.url,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};if(e.source_type===`base64`)return{type:`image_url`,image_url:{url:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.detail?{detail:e.metadata.detail}:{}}};throw Error(`Image content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(e){if(e.source_type===`url`){let t=i({dataUrl:e.url});if(!t)throw Error(`URL audio blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);let n=t.mime_type||e.mime_type||``,r;try{r=s(n)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!==`audio`||r.subtype!==`wav`&&r.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:r.subtype,data:t.data}}}if(e.source_type===`base64`){let t;try{t=s(e.mime_type??``)}catch{throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`)}if(t.type!==`audio`||t.subtype!==`wav`&&t.subtype!==`mp3`)throw Error(`Audio blocks with source_type ${e.source_type} must have mime type of audio/wav or audio/mp3`);return{type:`input_audio`,input_audio:{format:t.subtype,data:e.data}}}throw Error(`Audio content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(e){if(e.source_type===`url`){let t=i({dataUrl:e.url}),n=Ga(e);if(!t)throw Error(`URL file blocks with source_type ${e.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:`file`,file:{file_data:e.url,...e.metadata?.filename||e.metadata?.name?{filename:n}:{}}}}if(e.source_type===`base64`){let t=Ga(e);return{type:`file`,file:{file_data:`data:${e.mime_type??``};base64,${e.data}`,...e.metadata?.filename||e.metadata?.name||e.metadata?.title?{filename:t}:{}}}}if(e.source_type===`id`)return{type:`file`,file:{file_id:e.id}};throw Error(`File content blocks with source_type ${e.source_type} are not supported for ChatOpenAI`)}},js=({message:e,rawResponse:t,includeRawResponse:n})=>{let r=e.tool_calls;switch(e.role){case`assistant`:{let i=[],a=[];for(let e of r??[])try{i.push(we(e,{returnId:!0}))}catch(t){a.push(Ce(e,t.message))}let o={function_call:e.function_call,tool_calls:r};n!==void 0&&(o.__raw_response=t);let s={model_provider:`openai`,model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};return e.audio&&(o.audio=e.audio),new f({content:Ds(e.content||``,t.choices?.[0]?.message),tool_calls:i,invalid_tool_calls:a,additional_kwargs:o,response_metadata:s,id:t.id})}default:return new ae(e.content||``,e.role??`unknown`)}},Ms=({delta:e,rawResponse:t,includeRawResponse:n,defaultRole:r})=>{let i=e.role??r,a=e.content??``,o;o=e.function_call?{function_call:e.function_call}:e.tool_calls?{tool_calls:e.tool_calls}:{},n&&(o.__raw_response=t),e.audio&&(o.audio={...e.audio,index:t.choices[0].index});let s={model_provider:`openai`,usage:{...t.usage}};if(i===`user`)return new ee({content:a,response_metadata:s});if(i===`assistant`){let n=[];if(Array.isArray(e.tool_calls))for(let t of e.tool_calls)n.push({name:t.function?.name,args:t.function?.arguments,id:t.id,index:t.index,type:`tool_call_chunk`});return new p({content:a,tool_call_chunks:n,additional_kwargs:o,id:t.id,response_metadata:s})}else if(i===`system`)return new re({content:a,response_metadata:s});else if(i===`developer`)return new re({content:a,response_metadata:s,additional_kwargs:{__openai_role__:`developer`}});else if(i===`function`)return new oe({content:a,additional_kwargs:o,name:e.name,response_metadata:s});else if(i===`tool`)return new m({content:a,additional_kwargs:o,tool_call_id:e.tool_call_id,response_metadata:s});else return new g({content:a,role:i,response_metadata:s})},Ns=e=>{if(e.type===`image`){if(e.url)return{type:`image_url`,image_url:{url:e.url}};if(e.data)return{type:`image_url`,image_url:{url:`data:${e.mimeType};base64,${e.data}`}}}if(e.type===`audio`&&e.data){let t=r(()=>{let[,t]=e.mimeType.split(`/`);return t===`wav`||t===`mp3`?t:`wav`});return{type:`input_audio`,input_audio:{data:e.data.toString(),format:t}}}if(e.type===`file`){if(e.data){let t=Ga(e);return{type:`file`,file:{file_data:`data:${e.mimeType};base64,${e.data}`,filename:t}}}if(e.fileId)return{type:`file`,file:{file_id:e.fileId}}}},Ps=({message:e,model:t})=>{let n=Ka(e);if(n===`system`&&Ha(t)&&(n=`developer`),n===`developer`)return{role:`developer`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`system`)return{role:`system`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`assistant`)return{role:`assistant`,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`tool`&&te.isInstance(e))return{role:`tool`,tool_call_id:e.tool_call_id,content:e.contentBlocks.filter(e=>e.type===`text`)};if(n===`function`)return{role:`function`,name:e.name??``,content:e.contentBlocks.filter(e=>e.type===`text`).join(``)};function*r(e){for(let t of e){t.type===`text`&&(yield{type:`text`,text:t.text});let e=Ns(t);e&&(yield e)}}return{role:`user`,content:Array.from(r(e.contentBlocks))}},Fs=({messages:e,model:t})=>e.flatMap(e=>{if(`output_version`in e.response_metadata&&e.response_metadata?.output_version===`v1`)return Ps({message:e});let r=Ka(e);r===`system`&&Ha(t)&&(r=`developer`);let i=typeof e.content==`string`?e.content:e.content.map(e=>n(e)?a(e,As):e),o={role:r,content:i};return e.name!=null&&(o.name=e.name),e.additional_kwargs.function_call!=null&&(o.function_call=e.additional_kwargs.function_call),f.isInstance(e)&&e.tool_calls?.length?o.tool_calls=e.tool_calls.map(xe):(e.additional_kwargs.tool_calls!=null&&(o.tool_calls=e.additional_kwargs.tool_calls),te.isInstance(e)&&e.tool_call_id!=null&&(o.tool_call_id=e.tool_call_id)),e.additional_kwargs.audio&&typeof e.additional_kwargs.audio==`object`&&`id`in e.additional_kwargs.audio?[o,{role:`assistant`,audio:{id:e.additional_kwargs.audio.id}}]:o}),Is=class extends ks{invocationParams(e,t){let n;e?.strict===void 0?this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling):n=e.strict;let r={};e?.stream_options===void 0?this.streamUsage&&(this.streaming||t?.streaming)&&(r={stream_options:{include_usage:!0}}):r={stream_options:e.stream_options};let i={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(e=>this._convertChatOpenAIToolToCompletionsTool(e,{strict:n})):void 0,tool_choice:io(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...r,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(i.prediction=e.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),e?.service_tier!==void 0&&(i.service_tier=e.service_tier);let a=this._getReasoningParams(e);return a!==void 0&&a.effort!==void 0&&(i.reasoning_effort=a.effort),Ha(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(e,t,n){t.signal?.throwIfAborted();let r={},i=this.invocationParams(t),a=Fs({messages:e,model:this.model});if(i.stream){let i=this._streamResponseChunks(e,t,n),a={};for await(let e of i){e.message.response_metadata={...e.generationInfo,...e.message.response_metadata};let t=e.generationInfo?.completion??0;a[t]===void 0?a[t]=e:a[t]=a[t].concat(e)}let o=Object.entries(a).sort(([e],[t])=>parseInt(e,10)-parseInt(t,10)).map(([e,t])=>t),{functions:s,function_call:c}=this.invocationParams(t),l=await this._getEstimatedTokenCountFromPrompt(e,s,c),u=await this._getNumTokensFromGenerations(o);return r.input_tokens=l,r.output_tokens=u,r.total_tokens=l+u,{generations:o,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{let e=await this.completionWithRetry({...i,stream:!1,messages:a},{signal:t?.signal,...t?.options}),{completion_tokens:n,prompt_tokens:s,total_tokens:c,prompt_tokens_details:l,completion_tokens_details:u}=e?.usage??{};n&&(r.output_tokens=(r.output_tokens??0)+n),s&&(r.input_tokens=(r.input_tokens??0)+s),c&&(r.total_tokens=(r.total_tokens??0)+c),(l?.audio_tokens!==null||l?.cached_tokens!==null)&&(r.input_token_details={...l?.audio_tokens!==null&&{audio:l?.audio_tokens},...l?.cached_tokens!==null&&{cache_read:l?.cached_tokens}}),(u?.audio_tokens!==null||u?.reasoning_tokens!==null)&&(r.output_token_details={...u?.audio_tokens!==null&&{audio:u?.audio_tokens},...u?.reasoning_tokens!==null&&{reasoning:u?.reasoning_tokens}});let d=[];for(let t of e?.choices??[]){let n={text:t.message?.content??``,message:this._convertCompletionsMessageToBaseMessage(t.message??{role:`assistant`},e)};n.generationInfo={...t.finish_reason?{finish_reason:t.finish_reason}:{},...t.logprobs?{logprobs:t.logprobs}:{}},o(n.message)&&(n.message.usage_metadata=r),n.message=new f(Object.fromEntries(Object.entries(n.message).filter(([e])=>!e.startsWith(`lc_`)))),d.push(n)}return{generations:d,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamResponseChunks(e,t,n){let r=Fs({messages:e,model:this.model}),i={...this.invocationParams(t,{streaming:!0}),messages:r,stream:!0},a,o=await this.completionWithRetry(i,t),s;for await(let e of o){if(t.signal?.aborted)return;let r=e?.choices?.[0];if(e.usage&&(s=e.usage),!r)continue;let{delta:i}=r;if(!i)continue;let o=this._convertCompletionsDeltaToBaseMessageChunk(i,e,a);a=i.role??a;let c={prompt:t.promptIndex??0,completion:r.index??0};if(typeof o.content!=`string`){console.log(`[WARNING]: Received non-string content from OpenAI. This is currently not supported.`);continue}let l={...c};r.finish_reason!=null&&(l.finish_reason=r.finish_reason,l.system_fingerprint=e.system_fingerprint,l.model_name=e.model,l.service_tier=e.service_tier),this.logprobs&&(l.logprobs=r.logprobs);let u=new _({message:o,text:o.content,generationInfo:l});yield u,await n?.handleLLMNewToken(u.text??``,c,void 0,void 0,void 0,{chunk:u})}if(s){let e={...s.prompt_tokens_details?.audio_tokens!==null&&{audio:s.prompt_tokens_details?.audio_tokens},...s.prompt_tokens_details?.cached_tokens!==null&&{cache_read:s.prompt_tokens_details?.cached_tokens}},t={...s.completion_tokens_details?.audio_tokens!==null&&{audio:s.completion_tokens_details?.audio_tokens},...s.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:s.completion_tokens_details?.reasoning_tokens}};yield new _({message:new p({content:``,response_metadata:{usage:{...s}},usage_metadata:{input_tokens:s.prompt_tokens,output_tokens:s.completion_tokens,total_tokens:s.total_tokens,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(t).length>0&&{output_token_details:t}}}),text:``})}if(t.signal?.aborted)throw Error(`AbortError`)}async completionWithRetry(e,t){let n=this._getClientOptions(t),r=e.response_format&&e.response_format.type===`json_schema`;return this.caller.call(async()=>{try{return r&&!e.stream?await this.client.chat.completions.parse(e,n):await this.client.chat.completions.create(e,n)}catch(e){throw Ba(e)}})}_convertCompletionsDeltaToBaseMessageChunk(e,t,n){return Ms({delta:e,rawResponse:t,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(e,t){return js({message:e,rawResponse:t,includeRawResponse:this.__includeRawResponse})}},Ls=`__openai_function_call_ids__`;function Rs(e){return e.type===`url_citation`?{type:`citation`,source:`url_citation`,url:e.url,title:e.title,startIndex:e.start_index,endIndex:e.end_index}:e.type===`file_citation`?{type:`citation`,source:`file_citation`,title:e.filename,startIndex:e.index,file_id:e.file_id}:e.type===`container_file_citation`?{type:`citation`,source:`container_file_citation`,title:e.filename,startIndex:e.start_index,endIndex:e.end_index,file_id:e.file_id,container_id:e.container_id}:e.type===`file_path`?{type:`citation`,source:`file_path`,startIndex:e.index,file_id:e.file_id}:{type:`non_standard`,value:e}}var zs=e=>{let t={...e?.input_tokens_details?.cached_tokens!=null&&{cache_read:e?.input_tokens_details?.cached_tokens}},n={...e?.output_tokens_details?.reasoning_tokens!=null&&{reasoning:e?.output_tokens_details?.reasoning_tokens}};return{input_tokens:e?.input_tokens??0,output_tokens:e?.output_tokens??0,total_tokens:e?.total_tokens??0,input_token_details:t,output_token_details:n}},Bs=e=>{if(e.error){let t=Error(e.error.message);throw t.name=e.error.code,t}let t,n=[],r=[],i=[],a={model_provider:`openai`,model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(let a of e.output)if(a.type===`message`)t=a.id,n.push(...a.content.flatMap(e=>e.type===`output_text`?(`parsed`in e&&e.parsed!=null&&(o.parsed=e.parsed),{type:`text`,text:e.text,annotations:e.annotations.map(Rs)}):e.type===`refusal`?(o.refusal=e.refusal,[]):e));else if(a.type===`function_call`){let e={function:{name:a.name,arguments:a.arguments},id:a.call_id};try{r.push(we(e,{returnId:!0}))}catch(t){let n;typeof t==`object`&&t&&`message`in t&&typeof t.message==`string`&&(n=t.message),i.push(Ce(e,n))}o[Ls]??={},a.id&&(o[Ls][a.call_id]=a.id)}else if(a.type===`reasoning`){o.reasoning=a;let e=a.summary?.map(e=>e.text).filter(Boolean).join(``);e&&n.push({type:`reasoning`,reasoning:e})}else if(a.type===`custom_tool_call`){let e=uo(a);e?r.push(e):i.push(Ce(a,`Malformed custom tool call`))}else if(a.type===`computer_call`){let e=fo(a);e?r.push(e):i.push(Ce(a,`Malformed computer call`))}else a.type===`image_generation_call`?(a.result&&n.push({type:`image`,mimeType:`image/png`,data:a.result,id:a.id,metadata:{status:a.status}}),o.tool_outputs??=[],o.tool_outputs.push(a)):(o.tool_outputs??=[],o.tool_outputs.push(a));return new f({id:t,content:n,tool_calls:r,invalid_tool_calls:i,usage_metadata:zs(e.usage),additional_kwargs:o,response_metadata:a})},Vs=e=>{let t=(e.summary.length>1?e.summary.reduce((e,t)=>{let n=e[e.length-1];return n.index===t.index?n.text+=t.text:e.push(t),e},[{...e.summary[0]}]):e.summary).map(e=>Object.fromEntries(Object.entries(e).filter(([e])=>e!==`index`)));return{...e,summary:t}},Hs=e=>{let t=[],n={},r,i=[],a={model_provider:`openai`},o={},s;if(e.type===`response.output_text.delta`)t.push({type:`text`,text:e.delta,index:e.content_index});else if(e.type===`response.output_text.annotation.added`)t.push({type:`text`,text:``,annotations:[Rs(e.annotation)],index:e.content_index});else if(e.type===`response.output_item.added`&&e.item.type===`message`)s=e.item.id;else if(e.type===`response.output_item.added`&&e.item.type===`function_call`)i.push({type:`tool_call_chunk`,name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[Ls]={[e.item.call_id]:e.item.id};else if(e.type===`response.output_item.done`&&e.item.type===`computer_call`)i.push({type:`tool_call_chunk`,name:`computer_use`,args:JSON.stringify({action:e.item.action}),id:e.item.call_id,index:e.output_index}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&e.item.type===`image_generation_call`)e.item.result&&t.push({type:`image`,mimeType:`image/png`,data:e.item.result,id:e.item.id,metadata:{status:e.item.status}}),o.tool_outputs=[e.item];else if(e.type===`response.output_item.done`&&[`web_search_call`,`file_search_call`,`code_interpreter_call`,`mcp_call`,`mcp_list_tools`,`mcp_approval_request`,`custom_tool_call`].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type===`response.created`)a.id=e.response.id,a.model_name=e.response.model,a.model=e.response.model;else if(e.type===`response.completed`){let t=Bs(e.response);r=zs(e.response.usage),e.response.text?.format?.type===`json_schema`&&(o.parsed??=JSON.parse(t.text));for(let[t,n]of Object.entries(e.response))t!==`id`&&(a[t]=n)}else if(e.type===`response.function_call_arguments.delta`||e.type===`response.custom_tool_call_input.delta`)i.push({type:`tool_call_chunk`,args:e.delta,index:e.output_index});else if(e.type===`response.web_search_call.completed`||e.type===`response.file_search_call.completed`)n={tool_outputs:{id:e.item_id,type:e.type.replace(`response.`,``).replace(`.completed`,``),status:`completed`}};else if(e.type===`response.refusal.done`)o.refusal=e.refusal;else if(e.type===`response.output_item.added`&&`item`in e&&e.item.type===`reasoning`){let n=e.item.summary?e.item.summary.map((e,t)=>({...e,index:t})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...n?{summary:n}:{}};let r=e.item.summary?.map(e=>e.text).filter(Boolean).join(``);r&&t.push({type:`reasoning`,reasoning:r})}else if(e.type===`response.reasoning_summary_part.added`)o.reasoning={type:`reasoning`,summary:[{...e.part,index:e.summary_index}]},e.part.text&&t.push({type:`reasoning`,reasoning:e.part.text});else if(e.type===`response.reasoning_summary_text.delta`)o.reasoning={type:`reasoning`,summary:[{text:e.delta,type:`summary_text`,index:e.summary_index}]},e.delta&&t.push({type:`reasoning`,reasoning:e.delta});else if(e.type===`response.image_generation_call.partial_image`)return null;else return null;return new _({text:t.map(e=>e.text).join(``),message:new p({id:s,content:t,tool_call_chunks:i,usage_metadata:r,additional_kwargs:o,response_metadata:a}),generationInfo:n})},Us=e=>{let t=f.isInstance(e)&&e.response_metadata?.model_provider===`openai`;function*n(){let n=Va(()=>{try{let t=Ka(e);return t===`system`||t===`developer`||t===`assistant`||t===`user`?t:`assistant`}catch{return`assistant`}}),r,i=new Set,a=new Set,o=new Map,s=new Map;function*c(){if(!r)return;let e=r.content;(typeof e==`string`&&e.length>0||Array.isArray(e)&&e.length>0)&&(yield r),r=void 0}let l=e=>{r||={type:`message`,role:n,content:[]},typeof r.content==`string`?r.content=r.content.length>0?[{type:`input_text`,text:r.content},...e]:[...e]:r.content.push(...e)},u=e=>{if(typeof e==`string`)return e;try{return JSON.stringify(e??{})}catch{return`{}`}},d=e=>{let t=Va(()=>{let t=e.metadata?.detail;return t===`low`||t===`high`||t===`auto`?t:`auto`});if(e.fileId)return{type:`input_image`,detail:t,file_id:e.fileId};if(e.url)return{type:`input_image`,detail:t,image_url:e.url};if(e.data){let n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_image`,detail:t,image_url:`data:${e.mimeType??`image/png`};base64,${n}`}}},f=e=>{if(e.fileId){let t=Wa(e);return{type:`input_file`,file_id:e.fileId,...t?{filename:t}:{}}}if(e.url){let t=Wa(e);return{...t?{filename:t}:{},type:`input_file`,file_url:e.url}}if(e.data){let t=Ga(e),n=typeof e.data==`string`?e.data:Buffer.from(e.data).toString(`base64`);return{type:`input_file`,file_data:`data:${e.mimeType??`application/octet-stream`};base64,${n}`,...t?{filename:t}:{}}}},p=e=>{let t=Va(()=>{if(Array.isArray(e.summary)){let t=e.summary?.map(e=>e?.text).filter(e=>typeof e==`string`)??[];if(t.length>0)return t}return e.reasoning?[e.reasoning]:[]}),n=t.length>0?t.map(e=>({type:`summary_text`,text:e})):[{type:`summary_text`,text:``}],r={type:`reasoning`,id:e.id??``,summary:n};return e.reasoning&&(r.content=[{type:`reasoning_text`,text:e.reasoning}]),r},m=e=>({type:`function_call`,name:e.name??``,call_id:e.id??``,arguments:u(e.args)}),h=e=>{let t=u(e.output),n=e.status===`success`?`completed`:e.status===`error`?`incomplete`:void 0;return{type:`function_call_output`,call_id:e.toolCallId??``,output:t,...n?{status:n}:{}}};for(let n of e.contentBlocks)if(n.type===`text`)l([{type:`input_text`,text:n.text}]);else if(n.type!==`invalid_tool_call`){if(n.type===`reasoning`)yield*c(),yield p(n);else if(n.type===`tool_call`){yield*c();let e=n.id??``;e&&(i.add(e),o.delete(e)),yield m(n)}else if(n.type===`tool_call_chunk`){if(n.id){let e=o.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),o.set(n.id,e)}}else if(n.type===`server_tool_call`){yield*c();let e=n.id??``;e&&(a.add(e),s.delete(e)),yield m(n)}else if(n.type===`server_tool_call_chunk`){if(n.id){let e=s.get(n.id)??{name:n.name,args:[]};n.name&&(e.name=n.name),n.args&&e.args.push(n.args),s.set(n.id,e)}}else if(n.type===`server_tool_call_result`)yield*c(),yield h(n);else if(n.type!==`audio`)if(n.type===`file`){let e=f(n);e&&l([e])}else if(n.type===`image`){let e=d(n);e&&l([e])}else if(n.type===`video`){let e=f(n);e&&l([e])}else n.type===`text-plain`?n.text&&l([{type:`input_text`,text:n.text}]):n.type===`non_standard`&&t&&(yield*c(),yield n.value)}yield*c();for(let[e,t]of o){if(!e||i.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}for(let[e,t]of s){if(!e||a.has(e))continue;let n=t.args.join(``);!t.name&&!n||(yield{type:`function_call`,call_id:e,name:t.name??``,arguments:n})}}return Array.from(n())},Ws=({messages:e,zdrEnabled:t,model:r})=>e.flatMap(e=>{let i=e.response_metadata;if(i?.output_version===`v1`)return Us(e);let o=e.additional_kwargs,s=Ka(e);if(s===`system`&&Ha(r)&&(s=`developer`),s===`function`)throw Error(`Function messages are not supported in Responses API`);if(s===`tool`){let t=e;if(o?.type===`computer_call_output`)return{type:`computer_call_output`,output:(()=>{if(typeof t.content==`string`)return{type:`input_image`,image_url:t.content};if(Array.isArray(t.content)){let e=t.content.find(e=>e.type===`input_image`);if(e)return e;let n=t.content.find(e=>e.type===`computer_screenshot`);if(n)return n;let r=t.content.find(e=>e.type===`image_url`);if(r)return{type:`input_image`,image_url:typeof r.image_url==`string`?r.image_url:r.image_url.url}}throw Error(`Invalid computer call output`)})(),call_id:t.tool_call_id};if(t.additional_kwargs?.customTool)return{type:`custom_tool_call_output`,call_id:t.tool_call_id,output:t.content};let n=Array.isArray(t.content)&&t.content.every(e=>typeof e==`object`&&!!e&&`type`in e&&(e.type===`input_file`||e.type===`input_image`||e.type===`input_text`));return{type:`function_call_output`,call_id:t.tool_call_id,id:t.id?.startsWith(`fc_`)?t.id:void 0,output:n||typeof t.content==`string`?t.content:JSON.stringify(t.content)}}if(s===`assistant`){if(!t&&i?.output!=null&&Array.isArray(i?.output)&&i?.output.length>0&&i?.output.every(e=>`type`in e))return i?.output;let n=[];if(o?.reasoning&&!t){let e=Vs(o.reasoning);n.push(e)}let{content:r}=e;o?.refusal&&(typeof r==`string`&&(r=[{type:`output_text`,text:r,annotations:[]}]),r=[...r,{type:`refusal`,refusal:o.refusal}]),(typeof r==`string`||r.length>0)&&n.push({type:`message`,role:`assistant`,...e.id&&!t&&e.id.startsWith(`msg_`)?{id:e.id}:{},content:Va(()=>typeof r==`string`?r:r.flatMap(e=>e.type===`text`?{type:`output_text`,text:e.text,annotations:e.annotations??[]}:e.type===`output_text`||e.type===`refusal`?e:[]))});let a=o?.[Ls];f.isInstance(e)&&e.tool_calls?.length?n.push(...e.tool_calls.map(e=>mo(e)?{type:`custom_tool_call`,id:e.call_id,call_id:e.id??``,input:e.args.input,name:e.name}:po(e)?{type:`computer_call`,id:e.call_id,call_id:e.id??``,action:e.args.action}:{type:`function_call`,name:e.name,arguments:JSON.stringify(e.args),call_id:e.id,...t?{}:{id:a?.[e.id]}})):o?.tool_calls&&n.push(...o.tool_calls.map(e=>({type:`function_call`,name:e.function.name,call_id:e.id,arguments:e.function.arguments,...t?{}:{id:a?.[e.id]}})));let s=i?.output?.length?i?.output:o.tool_outputs,c=[`computer_call`,`mcp_call`,`code_interpreter_call`,`image_generation_call`];if(s!=null){let e=s?.filter(e=>c.includes(e.type));e.length>0&&n.push(...e)}return n}if(s===`user`||s===`system`||s===`developer`){if(typeof e.content==`string`)return{type:`message`,role:s,content:e.content};let t=[],r=e.content.flatMap(e=>(e.type===`mcp_approval_response`&&t.push({type:`mcp_approval_response`,approval_request_id:e.approval_request_id,approve:e.approve}),n(e)?a(e,As):e.type===`text`?{type:`input_text`,text:e.text}:e.type===`image_url`?{type:`input_image`,image_url:Va(()=>{if(typeof e.image_url==`string`)return e.image_url;if(typeof e.image_url==`object`&&e.image_url!==null&&`url`in e.image_url)return e.image_url.url}),detail:Va(()=>{if(typeof e.image_url==`string`)return`auto`;if(typeof e.image_url==`object`&&e.image_url!==null&&`detail`in e.image_url)return e.image_url.detail})}:e.type===`input_text`||e.type===`input_image`||e.type===`input_file`?e:[]));return r.length>0&&t.push({type:`message`,role:s,content:r}),t}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]}),Gs=class extends ks{invocationParams(e){let t;e?.strict!==void 0&&(t=e.strict),t===void 0&&this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);let n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:so(e?.tool_choice)?e?.tool_choice:(()=>{let t=io(e?.tool_choice);if(typeof t==`object`&&`type`in t){if(t.type===`function`)return{type:`function`,name:t.function.name};if(t.type===`allowed_tools`)return{type:`allowed_tools`,mode:t.allowed_tools.mode,tools:t.allowed_tools.tools};if(t.type===`custom`)return{type:`custom`,name:t.custom.name}}})(),text:(()=>{if(e?.text)return e.text;let t=this._getResponseFormat(e?.response_format);return t?.type===`json_schema`?t.json_schema.schema==null?void 0:{format:{type:`json_schema`,schema:t.json_schema.schema,description:t.json_schema.description,name:t.json_schema.name,strict:t.json_schema.strict},verbosity:e?.verbosity}:{format:t,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,prompt_cache_retention:e?.promptCacheRetention??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(e);return r!==void 0&&(n.reasoning=r),n}async _generate(e,t,n){t.signal?.throwIfAborted();let r=this.invocationParams(t);if(r.stream){let r=this._streamResponseChunks(e,t,n),i;for await(let e of r)e.message.response_metadata={...e.generationInfo,...e.message.response_metadata},i=i?.concat(e)??e;return{generations:i?[i]:[],llmOutput:{estimatedTokenUsage:i?.message?.usage_metadata}}}else{let n=await this.completionWithRetry({input:Ws({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:n.output_text,message:Bs(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*_streamResponseChunks(e,t,n){let r=await this.completionWithRetry({...this.invocationParams(t),input:Ws({messages:e,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},t);for await(let e of r){if(t.signal?.aborted)return;let r=Hs(e);r!=null&&(yield r,await n?.handleLLMNewToken(r.text||``,{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:r}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{let n=this._getClientOptions(t);try{return e.text?.format?.type===`json_schema`&&!e.stream?await this.client.responses.parse(e,n):await this.client.responses.create(e,n)}catch(e){throw Ba(e)}})}_reduceChatOpenAITools(e,t){let n=[];for(let r of e)if(ao(r))r.type===`image_generation`&&t?.stream&&(r.partial_images=1),n.push(r);else if(co(r)){let e=r.metadata.customTool;n.push({type:`custom`,name:e.name,description:e.description,format:e.format})}else ge(r)?n.push({type:`function`,name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:t?.strict??null}):lo(r)&&n.push(ho(r));return n}},Ks=class e extends ks{useResponsesApi=!1;responses;completions;get lc_serializable_keys(){return[...super.lc_serializable_keys,`useResponsesApi`]}get callKeys(){return[...super.callKeys,`useResponsesApi`]}constructor(e){super(e),this.fields=e,this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new Gs(e),this.completions=e?.completions??new Is(e)}_useResponsesApi(e){let t=e?.tools?.some(ao),n=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,r=e?.tools?.some(lo)||e?.tools?.some(co);return this.useResponsesApi||t||n||r||qa(this.model)}getLsParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){let t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,n){return this._useResponsesApi(t)?this.responses._generate(e,t,n):this.completions._generate(e,t,n)}async*_streamResponseChunks(e,t,n){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),n);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),n)}withConfig(t){let n=new e(this.fields);return n.defaultOptions={...this.defaultOptions,...t},n}};y({action:de(`type`,[y({type:v(`screenshot`)}),y({type:v(`click`),x:b(),y:b(),button:pe([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),y({type:v(`double_click`),x:b(),y:b(),button:pe([`left`,`right`,`wheel`,`back`,`forward`]).default(`left`)}),y({type:v(`drag`),path:fe(y({x:b(),y:b()}))}),y({type:v(`keypress`),keys:fe(x())}),y({type:v(`move`),x:b(),y:b()}),y({type:v(`scroll`),x:b(),y:b(),scroll_x:b(),scroll_y:b()}),y({type:v(`type`),text:x()}),y({type:v(`wait`),duration:b().optional()})])}),de(`type`,[y({type:v(`exec`),command:fe(x()),env:ue(x(),x()).optional(),working_directory:x().optional(),timeout_ms:b().optional(),user:x().optional()})]),y({commands:fe(x()).describe(`Array of shell commands to execute`),timeout_ms:b().optional().describe(`Optional timeout in milliseconds for the commands`),max_output_length:b().optional().describe(`Optional maximum number of characters to return from each command`)}),de(`type`,[y({type:v(`create_file`),path:x(),diff:x()}),y({type:v(`update_file`),path:x(),diff:x()}),y({type:v(`delete_file`),path:x()})]);export{Ks as ChatOpenAI};