@mcp-use/inspector 0.22.2 → 0.22.3
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.
- package/dist/cdn/inspector.js +2 -2
- package/dist/cli.js +13 -12
- package/dist/client/index.js +55 -55
- package/dist/server/{chunk-YF6BUSE7.js → chunk-42S46FP7.js} +1 -1
- package/dist/server/chunk-4CQ52PTY.js +10 -0
- package/dist/server/{chunk-YP2ENXIT.js → chunk-S2MXUMF5.js} +5 -7
- package/dist/server/cli.js +2 -1
- package/dist/server/index.js +3 -2
- package/dist/server/middleware.js +3 -2
- package/dist/server/server.js +2 -1
- package/dist/server/shared-static.d.ts.map +1 -1
- package/dist/server/shared-static.js +2 -1
- package/dist/server/version.d.ts +8 -0
- package/dist/server/version.d.ts.map +1 -0
- package/dist/server/version.js +9 -0
- package/dist/web/assets/{1c-DdyTu-k_.js → 1c-BY9hg5VO.js} +1 -1
- package/dist/web/assets/{abnf-C2DLuWsJ.js → abnf-CL1Oinim.js} +1 -1
- package/dist/web/assets/{accesslog-BcPmBnek.js → accesslog-Daj2COOe.js} +1 -1
- package/dist/web/assets/{actionscript-BX-T-H0r.js → actionscript-CK4mTICu.js} +1 -1
- package/dist/web/assets/{ada-bFUa8rWB.js → ada-Uu8mMOlf.js} +1 -1
- package/dist/web/assets/{angelscript--QyowWyi.js → angelscript-DG3JS4Pt.js} +1 -1
- package/dist/web/assets/{apache-CSPxjWTM.js → apache-BbDRmKD5.js} +1 -1
- package/dist/web/assets/{applescript-Beh8nYPj.js → applescript-C8vS9zYp.js} +1 -1
- package/dist/web/assets/{arcade-7vaiax_h.js → arcade-B-AGXDua.js} +1 -1
- package/dist/web/assets/{arduino-D67F76RP.js → arduino-Cw77rja_.js} +1 -1
- package/dist/web/assets/{armasm-DWQZh6t7.js → armasm-CHSjCEkG.js} +1 -1
- package/dist/web/assets/{asciidoc-DCLwNk1M.js → asciidoc-Cp4hnBVg.js} +1 -1
- package/dist/web/assets/{aspectj-C7zkyhZG.js → aspectj-DnEJ_6Tx.js} +1 -1
- package/dist/web/assets/{autohotkey-D67jHa54.js → autohotkey-pG5ZN3Xb.js} +1 -1
- package/dist/web/assets/{autoit-YshTFaZR.js → autoit-C93zudGB.js} +1 -1
- package/dist/web/assets/{avrasm-QFQOAcRR.js → avrasm-D8P7I6Xk.js} +1 -1
- package/dist/web/assets/{awk-h3G4tOxj.js → awk-B9AiPTi_.js} +1 -1
- package/dist/web/assets/{axapta-Ck2tuXpL.js → axapta-BiHIWhbm.js} +1 -1
- package/dist/web/assets/{bash-SNro2FI9.js → bash-Co_XMbBz.js} +1 -1
- package/dist/web/assets/{basic-CdFIzr_S.js → basic-gWgkzZ40.js} +1 -1
- package/dist/web/assets/{bnf-CoDF7W_1.js → bnf-CZ112Y_1.js} +1 -1
- package/dist/web/assets/{brainfuck-Bt-q8Sif.js → brainfuck-HHe3MmJP.js} +1 -1
- package/dist/web/assets/{c-CSy1LJEc.js → c-BiqWWzON.js} +1 -1
- package/dist/web/assets/{c-like-CgJH8TzM.js → c-like-Db5tg_sr.js} +1 -1
- package/dist/web/assets/{cal-BN4ZaGC3.js → cal-QNnVn6v3.js} +1 -1
- package/dist/web/assets/{capnproto-DtQwy4ia.js → capnproto-RqTIpDx9.js} +1 -1
- package/dist/web/assets/{ceylon-rt4387UK.js → ceylon-BuovP0OQ.js} +1 -1
- package/dist/web/assets/{clean-Cyb94-bm.js → clean-q9TT-CqW.js} +1 -1
- package/dist/web/assets/{client-hyRgVCty.js → client-A6Te1Nrl.js} +3 -3
- package/dist/web/assets/{clojure-CLewI5lA.js → clojure-Bv4T1o6e.js} +1 -1
- package/dist/web/assets/{clojure-repl-BtzgAt1p.js → clojure-repl-BKNwzg9u.js} +1 -1
- package/dist/web/assets/{cmake-DWrK9r_0.js → cmake-GwS-m6mj.js} +1 -1
- package/dist/web/assets/{coffeescript-dC8dxgju.js → coffeescript-St5PB0o0.js} +1 -1
- package/dist/web/assets/{coq-Dx-VjjMG.js → coq-C9uljeUe.js} +1 -1
- package/dist/web/assets/{core-l5FbiT9y.js → core-BcNI4N_j.js} +1 -1
- package/dist/web/assets/{cos-8hM_upPC.js → cos-DC_u_2Wk.js} +1 -1
- package/dist/web/assets/{cpp-C9q7oMVc.js → cpp-Npi735iX.js} +1 -1
- package/dist/web/assets/{crmsh-CM-iDW78.js → crmsh-CgwDy8hW.js} +1 -1
- package/dist/web/assets/{crystal-B89CGmJl.js → crystal-ChC4oJ0U.js} +1 -1
- package/dist/web/assets/{csharp-BML5bF5U.js → csharp-Clz9F3sP.js} +1 -1
- package/dist/web/assets/{csp-BFgIYW7p.js → csp-CQs0Rgdv.js} +1 -1
- package/dist/web/assets/{css-Bmr2MmHJ.js → css-Dx2cWeap.js} +1 -1
- package/dist/web/assets/{d-Bl1waUG7.js → d-Ck5uThWL.js} +1 -1
- package/dist/web/assets/{dart-7WM1pTL7.js → dart-Do5z2Ebl.js} +1 -1
- package/dist/web/assets/{delphi-BATb_6La.js → delphi-CIoWS_NP.js} +1 -1
- package/dist/web/assets/{diff-DQixhTxV.js → diff-D9MaYDd0.js} +1 -1
- package/dist/web/assets/{display-A5IEINAP-CIPa27wl.js → display-A5IEINAP-cWKELVdp.js} +2 -2
- package/dist/web/assets/{django-BaiMyL7a.js → django-BAB_pc60.js} +1 -1
- package/dist/web/assets/{dns-B9LMXwq0.js → dns-C_qR2SoS.js} +1 -1
- package/dist/web/assets/{dockerfile-CgRRyc7d.js → dockerfile-dLPaPiNQ.js} +1 -1
- package/dist/web/assets/{dos-CUi0wmYe.js → dos-zeCIrpto.js} +1 -1
- package/dist/web/assets/{dsconfig-CtHPMV_z.js → dsconfig-V_lTjveF.js} +1 -1
- package/dist/web/assets/{dts-Da6KiRGb.js → dts-DCkpDwtb.js} +1 -1
- package/dist/web/assets/{dust-CtSB5RuR.js → dust-BCiH9mmH.js} +1 -1
- package/dist/web/assets/{ebnf-Civ7z3Sl.js → ebnf-BssZ73ZD.js} +1 -1
- package/dist/web/assets/{elixir-BRz9w0Jz.js → elixir-yGlt97yR.js} +1 -1
- package/dist/web/assets/{elm-BLvIF2ZJ.js → elm-Bgc7A4ej.js} +1 -1
- package/dist/web/assets/{embeddings-DgQZkbYX.js → embeddings-BPcF2rPH.js} +1 -1
- package/dist/web/assets/{erb-yf3e-otT.js → erb-i7RV7Mgu.js} +1 -1
- package/dist/web/assets/{erlang-u1gFvkzN.js → erlang-BF9Lu8b3.js} +1 -1
- package/dist/web/assets/{erlang-repl-ygAXsKis.js → erlang-repl-CwtXgIsP.js} +1 -1
- package/dist/web/assets/{excel-Dr1VKgu5.js → excel-CoCCOh1G.js} +1 -1
- package/dist/web/assets/{fix-CQ9USTvQ.js → fix-DPMCJ8fg.js} +1 -1
- package/dist/web/assets/{flix-CK8VWwdt.js → flix-DnqM5wSr.js} +1 -1
- package/dist/web/assets/{fortran-ChxBIVaA.js → fortran-BIogvxTs.js} +1 -1
- package/dist/web/assets/{fsharp-C2VB7uZ8.js → fsharp-BB0Klq7T.js} +1 -1
- package/dist/web/assets/{gams-cNOVPE3r.js → gams-CrDnIzMO.js} +1 -1
- package/dist/web/assets/{gauss-Bqbzwh3H.js → gauss-DPqf_7wG.js} +1 -1
- package/dist/web/assets/{gcode-CCf3GJpC.js → gcode-DrFUoPm6.js} +1 -1
- package/dist/web/assets/{gherkin-zMG7sQxB.js → gherkin-BhNnk7p6.js} +1 -1
- package/dist/web/assets/{glsl-ChXPtZtn.js → glsl-Dt2D_ceQ.js} +1 -1
- package/dist/web/assets/{gml-Dkbq2p7u.js → gml-B99j-iGN.js} +1 -1
- package/dist/web/assets/{go-C_rm61mN.js → go-vo9AETVa.js} +1 -1
- package/dist/web/assets/{golo-BHw2HzNW.js → golo-CblP64f1.js} +1 -1
- package/dist/web/assets/{gradle-dmNWlxt5.js → gradle-CrTckNQc.js} +1 -1
- package/dist/web/assets/{groovy-BYRQ-Iq8.js → groovy-Bt9GtKxe.js} +1 -1
- package/dist/web/assets/{haml-CUGq_1r0.js → haml-DvJ_-R8m.js} +1 -1
- package/dist/web/assets/{handlebars-ClqAsR9Y.js → handlebars-C6Gt0Yxn.js} +1 -1
- package/dist/web/assets/{haskell-D1EUHyyy.js → haskell-DF2pQwvn.js} +1 -1
- package/dist/web/assets/{haxe-D5_584-N.js → haxe-D0xvaxiF.js} +1 -1
- package/dist/web/assets/{hsp-CxOObZJt.js → hsp-C6pWfp4u.js} +1 -1
- package/dist/web/assets/{htmlbars-BcxYs9JO.js → htmlbars-BORPrLad.js} +1 -1
- package/dist/web/assets/{http-IoGXsslz.js → http-DOfBwVD2.js} +1 -1
- package/dist/web/assets/{hy-DOezFVYJ.js → hy-Ds_8m9M4.js} +1 -1
- package/dist/web/assets/{index-CeFusmJF.js → index-8CwMSFu3.js} +8 -8
- package/dist/web/assets/{index-Df6PS_lJ.js → index-BCuNBDGw.js} +1 -1
- package/dist/web/assets/{index-Brj1Oahm.js → index-By9Gfw-Q.js} +1 -1
- package/dist/web/assets/{index-BWHJKdRK.js → index-C5fcbC9F.js} +1 -1
- package/dist/web/assets/{index-58vKJ_rW.js → index-CS79cRUw.js} +1 -1
- package/dist/web/assets/{index-BQMLPync.js → index-Djs_VhKs.js} +1 -1
- package/dist/web/assets/{index-BzCXH-MY.js → index-DkeQAS92.js} +1 -1
- package/dist/web/assets/{inform7-4DkSrciU.js → inform7-CycWHUYM.js} +1 -1
- package/dist/web/assets/{ini-BAOejxzX.js → ini-Dqot2gvf.js} +1 -1
- package/dist/web/assets/{irpf90-CPhvVsrR.js → irpf90-CC-czpc_.js} +1 -1
- package/dist/web/assets/{isbl-B9cEpNQ2.js → isbl-B09yO6kk.js} +1 -1
- package/dist/web/assets/{java-B4D9vUuB.js → java-CCi2jkz6.js} +1 -1
- package/dist/web/assets/{javascript-BUcy5JSl.js → javascript-D1P6LK-b.js} +1 -1
- package/dist/web/assets/{jboss-cli-rk3boy7C.js → jboss-cli-BAubHM2x.js} +1 -1
- package/dist/web/assets/{json-DMjBKfEa.js → json-Cpbzvk2j.js} +1 -1
- package/dist/web/assets/{julia-ByXC6uTj.js → julia-BCtJ-qSx.js} +1 -1
- package/dist/web/assets/{julia-repl-BRG6tLsN.js → julia-repl-wwBIF-51.js} +1 -1
- package/dist/web/assets/{kotlin-LVfLRQA6.js → kotlin-TQsrk-cQ.js} +1 -1
- package/dist/web/assets/{langfuse-U2OEF7K7-BHNkft2N.js → langfuse-U2OEF7K7-CZn-4_83.js} +3 -3
- package/dist/web/assets/{lasso-BcDeHYYs.js → lasso-CxrDgkB8.js} +1 -1
- package/dist/web/assets/{latex-BQLu7e0M.js → latex-Dx5D1LvA.js} +1 -1
- package/dist/web/assets/{ldif-MoWOvygf.js → ldif-CHuUnp8F.js} +1 -1
- package/dist/web/assets/{leaf-Dc_ryT_U.js → leaf-BGMI4wpN.js} +1 -1
- package/dist/web/assets/{less-xL-2sUOW.js → less-C9X8Hb5d.js} +1 -1
- package/dist/web/assets/{lisp-CQgkxiVN.js → lisp-CKgTvj0b.js} +1 -1
- package/dist/web/assets/{livecodeserver-CnHs8DDk.js → livecodeserver-Dvcifilt.js} +1 -1
- package/dist/web/assets/{livescript-Bq3GcA8X.js → livescript-C-5HpQtc.js} +1 -1
- package/dist/web/assets/{llms-DJAqua6W.js → llms--9GbEsAa.js} +1 -1
- package/dist/web/assets/{llvm-g2SZAh5n.js → llvm-CQWQrKZN.js} +1 -1
- package/dist/web/assets/{lsl-duYC8WGZ.js → lsl-B0S8WlXY.js} +1 -1
- package/dist/web/assets/{lua-BKi5mh_G.js → lua-opSykX_e.js} +1 -1
- package/dist/web/assets/{makefile-BqeicODu.js → makefile-BleNuj93.js} +1 -1
- package/dist/web/assets/{markdown-BG4LCYiF.js → markdown-DkTnsspf.js} +1 -1
- package/dist/web/assets/{mathematica-abL0r-fQ.js → mathematica-CSWTWKFD.js} +1 -1
- package/dist/web/assets/{matlab-UvEnHOa4.js → matlab-CMzIWY1g.js} +1 -1
- package/dist/web/assets/{maxima-WaftEzY-.js → maxima-DX_NdAF5.js} +1 -1
- package/dist/web/assets/{mel-B2MSGRGp.js → mel-fbkdu9e_.js} +1 -1
- package/dist/web/assets/{mercury-D-B5OKnw.js → mercury-DnixjAw6.js} +1 -1
- package/dist/web/assets/{mipsasm-BN0bNdeJ.js → mipsasm-CxsQAxBE.js} +1 -1
- package/dist/web/assets/{mizar-B9qd-OhV.js → mizar-CNJNhi8W.js} +1 -1
- package/dist/web/assets/{mojolicious-DojZjej7.js → mojolicious-DQjQSzH4.js} +1 -1
- package/dist/web/assets/{monkey-DTUG_uUK.js → monkey-BuvDb5Cg.js} +1 -1
- package/dist/web/assets/{moonscript-BxxoAw0w.js → moonscript-q6-TxIeT.js} +1 -1
- package/dist/web/assets/{n1ql-DoMSEnVI.js → n1ql-BAzbI-Kf.js} +1 -1
- package/dist/web/assets/{nginx-Ce5-hgf7.js → nginx-CgPxRmoX.js} +1 -1
- package/dist/web/assets/{nim--cUhot81.js → nim-Y774-80w.js} +1 -1
- package/dist/web/assets/{nix-CFzICQwT.js → nix-DL90C1A9.js} +1 -1
- package/dist/web/assets/{node-repl-8uW0BP3C.js → node-repl-BAH-4aO8.js} +1 -1
- package/dist/web/assets/{nsis-D85QEHck.js → nsis-Cag1K8pu.js} +1 -1
- package/dist/web/assets/{objectivec-CO4ZKM1N.js → objectivec-2AOmg7Fb.js} +1 -1
- package/dist/web/assets/{ocaml-MdZmIFP9.js → ocaml-CYr9n3jl.js} +1 -1
- package/dist/web/assets/{openscad-Dd_k-u5o.js → openscad-BMX-Qk_F.js} +1 -1
- package/dist/web/assets/{oxygene-C9_JJ-Tz.js → oxygene-DV8Kwi5Z.js} +1 -1
- package/dist/web/assets/{parser3--hakx1TP.js → parser3-gVJVwyss.js} +1 -1
- package/dist/web/assets/{perl-Bryi0MIt.js → perl-CqjBEZKS.js} +1 -1
- package/dist/web/assets/{pf-ZaeD0XU8.js → pf-qok5iX1r.js} +1 -1
- package/dist/web/assets/{pgsql-9scnk6gR.js → pgsql-BS0ptGTu.js} +1 -1
- package/dist/web/assets/{php-Fdiy0MkS.js → php-kWdk0F6D.js} +1 -1
- package/dist/web/assets/{php-template-BYeCSEy4.js → php-template-DQowOhOF.js} +1 -1
- package/dist/web/assets/{plaintext-FbFisAWv.js → plaintext-DtctCUuH.js} +1 -1
- package/dist/web/assets/{pony-B0HARvcw.js → pony-BzPWCeVb.js} +1 -1
- package/dist/web/assets/{powershell-DUssROtG.js → powershell-D1Xb8Pnx.js} +1 -1
- package/dist/web/assets/{processing-BQZO45D3.js → processing-BcLgJ-ad.js} +1 -1
- package/dist/web/assets/{profile-CcGplmcc.js → profile-D2YuE2tN.js} +1 -1
- package/dist/web/assets/{prolog-B0NhCbAQ.js → prolog-cbf9nEFr.js} +1 -1
- package/dist/web/assets/{properties-CWjoVJ5W.js → properties-BsD67rYU.js} +1 -1
- package/dist/web/assets/{protobuf-D58gQeRM.js → protobuf-BObX6a5a.js} +1 -1
- package/dist/web/assets/{puppet-Ba9doIt2.js → puppet-CvJOCWWw.js} +1 -1
- package/dist/web/assets/{purebasic-BrH-D46w.js → purebasic-CKsYYjhg.js} +1 -1
- package/dist/web/assets/{python-CjvAeSv8.js → python-LuPUaF8e.js} +1 -1
- package/dist/web/assets/{python-repl-Jgv_SkQ0.js → python-repl-BNDDtIuA.js} +1 -1
- package/dist/web/assets/{q-DgYB_ewM.js → q-iW6HwAxF.js} +1 -1
- package/dist/web/assets/{qml-C7I-vh-W.js → qml-CaT0tW8S.js} +1 -1
- package/dist/web/assets/{r-DUpFDXxH.js → r-DBoUpgfg.js} +1 -1
- package/dist/web/assets/{reasonml-Dxs-bF-2.js → reasonml-CV6zVGNT.js} +1 -1
- package/dist/web/assets/{rib-CQL270qQ.js → rib-8Ox4ZZxr.js} +1 -1
- package/dist/web/assets/{roboconf-krxtbKe1.js → roboconf-CaWw3vEJ.js} +1 -1
- package/dist/web/assets/{routeros-BGBHdfxg.js → routeros-DZuoGNbX.js} +1 -1
- package/dist/web/assets/{rsl-CxAtY_02.js → rsl-D435zTs_.js} +1 -1
- package/dist/web/assets/{ruby-DJm1xcVx.js → ruby-Bpnl5leP.js} +1 -1
- package/dist/web/assets/{ruleslanguage-BnhvTD6g.js → ruleslanguage-d1jaVL2t.js} +1 -1
- package/dist/web/assets/{rust-DQe5T9WQ.js → rust-_XzUPcJX.js} +1 -1
- package/dist/web/assets/{sas-6xbHPzOh.js → sas-D2nsObqn.js} +1 -1
- package/dist/web/assets/{scala-DZlwYVr9.js → scala-D5O0jaRL.js} +1 -1
- package/dist/web/assets/{scheme-DXL_Buip.js → scheme-B1s6egle.js} +1 -1
- package/dist/web/assets/{scilab-CKRl_kfB.js → scilab-Dde56007.js} +1 -1
- package/dist/web/assets/{scss-jr09pBlW.js → scss-j5LXnIyV.js} +1 -1
- package/dist/web/assets/{shell-CxU4VQpG.js → shell-qeht7kvG.js} +1 -1
- package/dist/web/assets/{smali-BsXFpLll.js → smali-DqpFuxTr.js} +1 -1
- package/dist/web/assets/{smalltalk-D2nr_49h.js → smalltalk-BJipSjpG.js} +1 -1
- package/dist/web/assets/{sml-B16pEEUV.js → sml-BwTqiu2x.js} +1 -1
- package/dist/web/assets/{sqf-BRaN4nE_.js → sqf-BeI49Hag.js} +1 -1
- package/dist/web/assets/{sql-CeIac2_e.js → sql-DW_5amaf.js} +1 -1
- package/dist/web/assets/{sql_more-ZIMlJNGg.js → sql_more-DGnGnKZF.js} +1 -1
- package/dist/web/assets/{stan-DmpIhD_z.js → stan-CZro_4hI.js} +1 -1
- package/dist/web/assets/{stata-0ytqR1Ib.js → stata-C4SBQoKJ.js} +1 -1
- package/dist/web/assets/{stdio-PVTCK7WZ-C_E3pv0k.js → stdio-YPS6T26I-D8D73-f-.js} +1 -1
- package/dist/web/assets/{step21-C5gS7qwT.js → step21-BzIPRteI.js} +1 -1
- package/dist/web/assets/{stylus-DUzDJYfR.js → stylus-DJICcqbR.js} +1 -1
- package/dist/web/assets/{subunit-BgugsJpP.js → subunit-Cs9rVey-.js} +1 -1
- package/dist/web/assets/{swift-Cq31xV9A.js → swift-CGstItND.js} +1 -1
- package/dist/web/assets/{taggerscript-D6rUQ5Ju.js → taggerscript-DNQQCUhH.js} +1 -1
- package/dist/web/assets/{tap-DkraFPBQ.js → tap-RuaqtcHb.js} +1 -1
- package/dist/web/assets/{tcl-87kkAxdg.js → tcl-yKcgwGzI.js} +1 -1
- package/dist/web/assets/{thrift-CHkbhRQC.js → thrift-aIIWVf1c.js} +1 -1
- package/dist/web/assets/{tp-D5drOrfs.js → tp-bIe96RTe.js} +1 -1
- package/dist/web/assets/{twig-JUSSxmsN.js → twig-hiHSs1AP.js} +1 -1
- package/dist/web/assets/{typescript-DxY7tpO6.js → typescript-BhNKgKZ0.js} +1 -1
- package/dist/web/assets/{vala-BKhreswN.js → vala-DOGhBEmL.js} +1 -1
- package/dist/web/assets/{vbnet-BHYN5PHo.js → vbnet-Cbz-z6AW.js} +1 -1
- package/dist/web/assets/{vbscript-eErGIKc5.js → vbscript-ChcS2gY9.js} +1 -1
- package/dist/web/assets/{vbscript-html-BVPWl6WP.js → vbscript-html-SdY2oJMk.js} +1 -1
- package/dist/web/assets/{verilog-DbaUNZdo.js → verilog-CXnd9XvY.js} +1 -1
- package/dist/web/assets/{vhdl-UR-HSHjG.js → vhdl-DU-MPXBT.js} +1 -1
- package/dist/web/assets/{vim-Dk1XUiA7.js → vim-BLXZENow.js} +1 -1
- package/dist/web/assets/{x86asm-B9c_N4c6.js → x86asm-4So3Hav3.js} +1 -1
- package/dist/web/assets/{xl-swOLfPCO.js → xl-W5T-Pr7d.js} +1 -1
- package/dist/web/assets/{xml-BpZLXHyv.js → xml-DwKWdh_5.js} +1 -1
- package/dist/web/assets/{xquery-RWTIln5p.js → xquery-B5Lron-I.js} +1 -1
- package/dist/web/assets/{yaml-k20kwc4p.js → yaml-CqCoSwCx.js} +1 -1
- package/dist/web/assets/{zephir-7ED-2Mm2.js → zephir-BbxJ_pNe.js} +1 -1
- package/dist/web/index.html +2 -2
- package/package.json +2 -2
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{g as Ss,O as jt,h as ks,c as qt,f as Ts,J as Ms,S as vs,R as Dt}from"./index-Df6PS_lJ.js";import{x as Os,b2 as y,b3 as Wt,b4 as Is,b5 as As,b6 as Ft,a0 as kn,U as ve,aA as Ht,Z as Rs,$ as Cs,W as N,a1 as Ps,b as ot,Q as ie,V as Es,a2 as Ns,b7 as Us,b8 as tt,b9 as b,ba as w,bb as E,bc as Bs,bd as At}from"./index-CeFusmJF.js";import{t as Ie}from"./index-BzCXH-MY.js";var Jt=class extends Ss{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(r){throw new jt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(r.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await Os(this.zodSchema,e);if(n.success)return n.data;throw new jt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(s=>{const{message:a}=s;return Array.isArray(a.content)?Tn(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function Tn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function $s(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Ls=y({cache_control:As().optional().nullable(),defer_loading:Is().optional(),input_examples:Wt(Ft()).optional(),allowed_callers:Wt(Ft()).optional()}),Kt={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function js(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function qs(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ds(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Ws(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Fs={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=kn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Hs=t=>t();function Js(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Ks(t){function*e(){for(const n of t)Js(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Xs(t)}function Xs(t){const e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function ct(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const n=ke(e,"cache_control");n!==void 0&&(t.cache_control=n);const r=ke(e,"citations");r!==void 0&&(t.citations=r);const s=ke(e,"context");s!==void 0&&(t.context=s);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ut(t,e){const n=ke(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function Xt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function zs(t){const e=[],n=t.response_metadata,r="model_provider"in n&&n?.model_provider==="anthropic";for(const s of t.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:Ks(s.annotations)}):e.push({type:"text",text:s.text});else if(s.type==="tool_call")e.push({type:"tool_use",id:s.id??"",name:s.name,input:s.args});else if(s.type==="tool_call_chunk"){const a=Hs(()=>{if(typeof s.args!="string")return s.args;try{return JSON.parse(s.args)}catch{return{}}});e.push({type:"tool_use",id:s.id??"",name:s.name??"",input:a})}else if(s.type==="reasoning"&&r)e.push({type:"thinking",thinking:s.reasoning,signature:String(s.signature)});else if(s.type==="server_tool_call"&&r)s.name==="web_search"?e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args}):s.name==="code_execution"&&e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args});else if(s.type==="server_tool_call_result"&&r)if(s.name==="web_search"&&Array.isArray(s.output.urls)){const a=s.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId??"",content:a})}else s.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId??"",content:s.output}):s.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId??"",content:s.output});else{if(s.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(s.type==="file"){const a=s.metadata;if(s.fileId){e.push(Z({type:"document",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){const i=ct(s.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:s.url}},a));continue}}if(s.data){const i=ct(s.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(s.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(s.data),media_type:"text/plain"}},a));else if(Xt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(s.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(s.type==="image"){const a=s.metadata;if(s.fileId){e.push(ut({type:"image",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){e.push(ut({type:"image",source:{type:"url",url:s.url}},a));continue}if(s.data){const i=ct(s.mimeType)||"image/png";Xt(i)&&e.push(ut({type:"image",source:{type:"base64",data:oe(s.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else s.type==="video"||(s.type==="text-plain"?s.data&&e.push(Z({type:"document",source:{type:"text",data:oe(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&r&&e.push(s.value))}return e}function lt(t){const e=kn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
1
|
+
import{g as Ss,O as jt,h as ks,c as qt,f as Ts,J as Ms,S as vs,R as Dt}from"./index-BCuNBDGw.js";import{x as Os,b2 as y,b3 as Wt,b4 as Is,b5 as As,b6 as Ft,a0 as kn,U as ve,aA as Ht,Z as Rs,$ as Cs,W as N,a1 as Ps,b as ot,Q as ie,V as Es,a2 as Ns,b7 as Us,b8 as tt,b9 as b,ba as w,bb as E,bc as Bs,bd as At}from"./index-8CwMSFu3.js";import{t as Ie}from"./index-DkeQAS92.js";var Jt=class extends Ss{static lc_name(){return"AnthropicToolsOutputParser"}lc_namespace=["langchain","anthropic","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){let e=t;if(typeof t=="string")try{e=JSON.parse(t)}catch(r){throw new jt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(r.message)}`,t)}else e=t;if(this.zodSchema===void 0)return e;const n=await Os(this.zodSchema,e);if(n.success)return n.data;throw new jt(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(n.error.issues)}`,JSON.stringify(e,null,2))}async parseResult(t){const e=t.flatMap(s=>{const{message:a}=s;return Array.isArray(a.content)?Tn(a.content)[0]:[]});if(e[0]===void 0)throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}};function Tn(t){const e=[];for(const n of t)n.type==="tool_use"&&e.push({name:n.name,args:n.input,id:n.id,type:"tool_call"});return e}function $s(t){if(t)return t==="any"?{type:"any"}:t==="auto"?{type:"auto"}:t==="none"?{type:"none"}:typeof t=="string"?{type:"tool",name:t}:t}const Ls=y({cache_control:As().optional().nullable(),defer_loading:Is().optional(),input_examples:Wt(Ft()).optional(),allowed_callers:Wt(Ft()).optional()}),Kt={tool_search_tool_regex_20251119:"advanced-tool-use-2025-11-20",tool_search_tool_bm25_20251119:"advanced-tool-use-2025-11-20",memory_20250818:"context-management-2025-06-27",web_fetch_20250910:"web-fetch-2025-09-10",code_execution_20250825:"code-execution-2025-08-25",computer_20251124:"computer-use-2025-11-24",computer_20250124:"computer-use-2025-01-24",mcp_toolset:"mcp-client-2025-11-20"};function js(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="thinking"}function qs(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="redacted_thinking"}function Ds(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="search_result"}function Ws(t){return typeof t!="object"||t==null||!("type"in t)||t.type!=="image"||!("source"in t)||typeof t.source!="object"||t.source==null||!("type"in t.source)?!1:t.source.type==="base64"?!(!("media_type"in t.source)||typeof t.source.media_type!="string"||!("data"in t.source)||typeof t.source.data!="string"):t.source.type==="url"?!(!("url"in t.source)||typeof t.source.url!="string"):!1}const Fs={providerName:"anthropic",fromStandardTextBlock(t){return{type:"text",text:t.text,..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}},fromStandardImageBlock(t){if(t.source_type==="url"){const e=kn({dataUrl:t.url,asTypedArray:!1});return e?{type:"image",source:{type:"base64",data:e.data,media_type:e.mime_type},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}:{type:"image",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}}}else{if(t.source_type==="base64")return{type:"image",source:{type:"base64",data:t.data,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{}};throw new Error(`Unsupported image source type: ${t.source_type}`)}},fromStandardFileBlock(t){const e=(t.mime_type??"").split(";")[0];if(t.source_type==="url"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"url",url:t.url},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file url source: ${t.mime_type}`)}else if(t.source_type==="text"){if(e==="text/plain"||e==="")return{type:"document",source:{type:"text",data:t.text,media_type:t.mime_type??""},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file text source: ${t.mime_type}`)}else if(t.source_type==="base64"){if(e==="application/pdf"||e==="")return{type:"document",source:{type:"base64",data:t.data,media_type:"application/pdf"},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};if(["image/jpeg","image/png","image/gif","image/webp"].includes(e))return{type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:t.data,media_type:e}}]},..."cache_control"in(t.metadata??{})?{cache_control:t.metadata.cache_control}:{},..."citations"in(t.metadata??{})?{citations:t.metadata.citations}:{},..."context"in(t.metadata??{})?{context:t.metadata.context}:{},..."title"in(t.metadata??{})?{title:t.metadata.title}:{}};throw new Error(`Unsupported file mime type for file base64 source: ${t.mime_type}`)}else throw new Error(`Unsupported file source type: ${t.source_type}`)}},Hs=t=>t();function Js(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="citation"}function Ks(t){function*e(){for(const n of t)Js(n)&&(n.source==="char"?yield{type:"char_location",file_id:n.url??"",start_char_index:n.startIndex??0,end_char_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="page"?yield{type:"page_location",file_id:n.url??"",start_page_number:n.startIndex??0,end_page_number:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="block"?yield{type:"content_block_location",file_id:n.url??"",start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,document_title:n.title??null,document_index:0,cited_text:n.citedText??""}:n.source==="url"?yield{type:"web_search_result_location",url:n.url??"",title:n.title??null,encrypted_index:String(n.startIndex??0),cited_text:n.citedText??""}:n.source==="search"&&(yield{type:"search_result_location",title:n.title??null,start_block_index:n.startIndex??0,end_block_index:n.endIndex??0,search_result_index:0,source:n.source??"",cited_text:n.citedText??""}))}return Array.from(e())}function oe(t){return typeof t=="string"?t:Xs(t)}function Xs(t){const e=[];for(let n=0,{length:r}=t;n<r;n++)e.push(String.fromCharCode(t[n]));return btoa(e.join(""))}function ct(t){return(t??"").split(";")[0].toLowerCase()}function ke(t,e){if(t!=null&&typeof t=="object"&&e in t)return t[e]}function Z(t,e){const n=ke(e,"cache_control");n!==void 0&&(t.cache_control=n);const r=ke(e,"citations");r!==void 0&&(t.citations=r);const s=ke(e,"context");s!==void 0&&(t.context=s);const a=ke(e,"title");return a!==void 0&&(t.title=a),t}function ut(t,e){const n=ke(e,"cache_control");return n!==void 0&&(t.cache_control=n),t}function Xt(t){return new Set(["image/jpeg","image/png","image/gif","image/webp"]).has(t)}function zs(t){const e=[],n=t.response_metadata,r="model_provider"in n&&n?.model_provider==="anthropic";for(const s of t.contentBlocks)if(s.type==="text")s.annotations?e.push({type:"text",text:s.text,citations:Ks(s.annotations)}):e.push({type:"text",text:s.text});else if(s.type==="tool_call")e.push({type:"tool_use",id:s.id??"",name:s.name,input:s.args});else if(s.type==="tool_call_chunk"){const a=Hs(()=>{if(typeof s.args!="string")return s.args;try{return JSON.parse(s.args)}catch{return{}}});e.push({type:"tool_use",id:s.id??"",name:s.name??"",input:a})}else if(s.type==="reasoning"&&r)e.push({type:"thinking",thinking:s.reasoning,signature:String(s.signature)});else if(s.type==="server_tool_call"&&r)s.name==="web_search"?e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args}):s.name==="code_execution"&&e.push({type:"server_tool_use",name:s.name,id:s.id??"",input:s.args});else if(s.type==="server_tool_call_result"&&r)if(s.name==="web_search"&&Array.isArray(s.output.urls)){const a=s.output.urls.map(i=>({type:"web_search_result",title:"",encrypted_content:"",url:i}));e.push({type:"web_search_tool_result",tool_use_id:s.toolCallId??"",content:a})}else s.name==="code_execution"?e.push({type:"code_execution_tool_result",tool_use_id:s.toolCallId??"",content:s.output}):s.name==="mcp_tool_result"&&e.push({type:"mcp_tool_result",tool_use_id:s.toolCallId??"",content:s.output});else{if(s.type==="audio")throw new Error("Anthropic does not support audio content blocks.");if(s.type==="file"){const a=s.metadata;if(s.fileId){e.push(Z({type:"document",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){const i=ct(s.mimeType);if(i==="application/pdf"||i===""){e.push(Z({type:"document",source:{type:"url",url:s.url}},a));continue}}if(s.data){const i=ct(s.mimeType);if(i===""||i==="application/pdf")e.push(Z({type:"document",source:{type:"base64",data:oe(s.data),media_type:"application/pdf"}},a));else if(i==="text/plain")e.push(Z({type:"document",source:{type:"text",data:oe(s.data),media_type:"text/plain"}},a));else if(Xt(i))e.push(Z({type:"document",source:{type:"content",content:[{type:"image",source:{type:"base64",data:oe(s.data),media_type:i}}]}},a));else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${i}`);continue}throw new Error("File content block must include a fileId, url, or data property.")}else if(s.type==="image"){const a=s.metadata;if(s.fileId){e.push(ut({type:"image",source:{type:"file",file_id:s.fileId}},a));continue}if(s.url){e.push(ut({type:"image",source:{type:"url",url:s.url}},a));continue}if(s.data){const i=ct(s.mimeType)||"image/png";Xt(i)&&e.push(ut({type:"image",source:{type:"base64",data:oe(s.data),media_type:i}},a));continue}throw new Error("Image content block must include a fileId, url, or data property.")}else s.type==="video"||(s.type==="text-plain"?s.data&&e.push(Z({type:"document",source:{type:"text",data:oe(s.data),media_type:"text/plain"}},s.metadata)):s.type==="non_standard"&&r&&e.push(s.value))}return e}function lt(t){const e=kn({dataUrl:t});if(e)return{type:"base64",media_type:e.mime_type,data:e.data};let n;try{n=new URL(t)}catch{throw new Error([`Malformed image URL: ${JSON.stringify(t)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
2
2
|
|
|
3
3
|
`))}if(n.protocol==="http:"||n.protocol==="https:")return{type:"url",url:t};throw new Error([`Invalid image URL protocol: ${JSON.stringify(n.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`,"Example: data:image/png;base64,/9j/4AAQSk...","Example: https://example.com/image.jpg"].join(`
|
|
4
4
|
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{c as at,f as rt,g as Ct,O as Ot,h as yt,J as It,R as U}from"./index-Df6PS_lJ.js";import{b as ut,Q as vt,S as _t,U as Et,V as Tt,W as wt,X as St,Y as At,y as lt,Z as Rt,$ as xt,a0 as k,x as kt,a1 as ct,a2 as bt}from"./index-CeFusmJF.js";import{E as Nt,c as Mt}from"./embeddings-DgQZkbYX.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const{$schema:e,...n}=I(ut(t)?vt(t):t);return n}function Dt(t){const{$schema:e,...n}=I(t);return n}function E(t,e,n=[]){if(t==null||typeof t!="object")return;const s=t;if(Array.isArray(s.enum)&&s.enum.some(i=>i==="")){const i=n.length?` at path "${n.join(".")}"`:"",o=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${o}${i}. Gemini API rejects empty strings in enums.`)}if(s.type==="object"&&s.properties&&typeof s.properties=="object")for(const[i,o]of Object.entries(s.properties))E(o,e,[...n,i]);s.items&&E(s.items,e,[...n,"[]"]);for(const i of["anyOf","oneOf","allOf"]){const o=s[i];Array.isArray(o)&&o.forEach((a,u)=>E(a,e,[...n,`${i}[${u}]`]))}s.additionalProperties&&typeof s.additionalProperties=="object"&&E(s.additionalProperties,e,[...n,"additionalProperties"])}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Gt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let b;const Ut=new Uint8Array(16);function Lt(){if(!b){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");b=crypto.getRandomValues.bind(crypto)}return b(Ut)}const Pt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),L={randomUUID:Pt};function dt(t,e,n){if(L.randomUUID&&!t)return L.randomUUID();t=t||{};const s=t.random??t.rng?.()??Lt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Gt(s)}const D="__gemini_function_call_thought_signatures__",jt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Kt=t=>t();function Ft(t){return St.isInstance(t)?t.role:t.type}function Ht(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function $t(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Yt(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function Bt(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function P(t,e){if(Rt(t))return xt(t,Bt(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return $t(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function qt(t,e,n,s){if(At(t)){const u=t.name??Yt(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const d=Array.isArray(t.content)?t.content.map(p=>P(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:d}}}}]:[{functionResponse:{name:u,response:{result:d}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>P(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[D];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const d=Kt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?jt:""});return{functionCall:{name:u.name,args:u.args},...d?{thoughtSignature:d}:{}}})),[...o,...i]}function j(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!_t(o))throw new Error("Unsupported message input");const u=Ft(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const d=Ht(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===d)throw new Error("Google Generative AI requires alternate messages between authors");const l=qt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const f=i.content[i.content.length-1];if(!f)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return f.parts.push(...l),{mergeWithPreviousContent:!1,content:i.content}}let r=d;(r==="function"||r==="system"&&!n)&&(r="user");const c={role:r,parts:l};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,c]}},{content:[],mergeWithPreviousContent:!1}).content}function Vt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((l,r)=>("functionCall"in r&&r.functionCall&&l.push({...r,id:"id"in r.functionCall&&typeof r.functionCall.id=="string"?r.functionCall.id:dt()}),l),[]);let a;const u=s?.parts;Array.isArray(u)&&u.length===1&&"text"in u[0]&&u[0].text&&!u[0].thought?a=u[0].text:Array.isArray(u)&&u.length>0?a=u.map(l=>l.thought&&"text"in l&&l.text?{type:"thinking",thinking:l.text,...l.thoughtSignature?{signature:l.thoughtSignature}:{}}:"text"in l?{type:"text",text:l.text}:"inlineData"in l?{type:"inlineData",inlineData:l.inlineData}:"functionCall"in l?{type:"functionCall",functionCall:l.functionCall}:"functionResponse"in l?{type:"functionResponse",functionResponse:l.functionResponse}:"fileData"in l?{type:"fileData",fileData:l.fileData}:"executableCode"in l?{type:"executableCode",executableCode:l.executableCode}:"codeExecutionResult"in l?{type:"codeExecutionResult",codeExecutionResult:l.codeExecutionResult}:l):a=[];const d=o?.reduce((l,r)=>("thoughtSignature"in r&&typeof r.thoughtSignature=="string"&&(l[r.id]=r.thoughtSignature),l),{});let p="";return typeof a=="string"?p=a:Array.isArray(a)&&a.length>0&&(p=a.find(l=>"text"in l)?.text??p),{generations:[{text:p,message:new Et({content:a??"",tool_calls:o?.map(l=>({type:"tool_call",id:l.id,name:l.functionCall.name,args:l.functionCall.args})),additional_kwargs:{...i,[D]:d},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function Wt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,c)=>("functionCall"in c&&c.functionCall&&r.push({...c,id:"id"in c.functionCall&&typeof c.functionCall.id=="string"?c.functionCall.id:dt()}),r),[]);let a;const u=s?.parts;Array.isArray(u)&&u.every(r=>"text"in r&&!r.thought)?a=u.map(r=>r.text).join(""):Array.isArray(u)?a=u.map(r=>r.thought&&"text"in r&&r.text?{type:"thinking",thinking:r.text,...r.thoughtSignature?{signature:r.thoughtSignature}:{}}:"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let d="";a&&typeof a=="string"?d=a:Array.isArray(a)&&(d=a.find(r=>"text"in r)?.text??"");const p=[];o&&p.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const l=o?.reduce((r,c)=>("thoughtSignature"in c&&typeof c.thoughtSignature=="string"&&(r[c.id]=c.thoughtSignature),r),{});return new Tt({text:d,message:new wt({content:a||"",name:s?s.role:void 0,tool_call_chunks:p,additional_kwargs:{[D]:l},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Jt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(E(n,e.name),{name:e.name,description:e.description,parameters:n})}if(rt(e)){const n=Dt(e.function.parameters);return E(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function K(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends Ct{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await kt(this.zodSchema,t);if(e.success)return e.data;throw new Ot(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},H;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(H||(H={}));var $;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})($||($={}));var Y;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Y||(Y={}));const B=["user","model","function","system"];var q;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(q||(q={}));var V;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(V||(V={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var J;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(J||(J={}));var w;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(w||(w={}));var z;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(z||(z={}));var T;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(T||(T={}));var Q;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Q||(Q={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class ft extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class pt extends m{}const zt="https://generativelanguage.googleapis.com",Qt="v1beta",Zt="0.24.1",Xt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class te{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Qt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||zt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function ee(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Xt}/${Zt}`),e.join(" ")}async function ne(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",ee(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function se(t,e,n,s,i,o){const a=new te(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},re(o)),{method:"POST",headers:await ne(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:d}=await se(t,e,n,s,i,o);return ie(u,d,a)}async function ie(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){oe(i,t)}return s.ok||await ae(s,t),s}function oe(t,e){let n=t;throw n.name==="AbortError"?(n=new pt(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof ft||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ae(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new ft(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function re(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function G(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return ue(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ue(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
1
|
+
import{c as at,f as rt,g as Ct,O as Ot,h as yt,J as It,R as U}from"./index-BCuNBDGw.js";import{b as ut,Q as vt,S as _t,U as Et,V as Tt,W as wt,X as St,Y as At,y as lt,Z as Rt,$ as xt,a0 as k,x as kt,a1 as ct,a2 as bt}from"./index-8CwMSFu3.js";import{E as Nt,c as Mt}from"./embeddings-BPcF2rPH.js";function I(t){if(typeof t=="object"&&t!==null){const e={...t};"additionalProperties"in e&&delete e.additionalProperties,"$schema"in e&&delete e.$schema,"strict"in e&&delete e.strict;for(const n in e)n in e&&(Array.isArray(e[n])?e[n]=e[n].map(I):typeof e[n]=="object"&&e[n]!==null&&(e[n]=I(e[n])));return e}return t}function N(t){const{$schema:e,...n}=I(ut(t)?vt(t):t);return n}function Dt(t){const{$schema:e,...n}=I(t);return n}function E(t,e,n=[]){if(t==null||typeof t!="object")return;const s=t;if(Array.isArray(s.enum)&&s.enum.some(i=>i==="")){const i=n.length?` at path "${n.join(".")}"`:"",o=e?` in tool "${e}"`:"";throw new Error(`Invalid enum: empty string not allowed${o}${i}. Gemini API rejects empty strings in enums.`)}if(s.type==="object"&&s.properties&&typeof s.properties=="object")for(const[i,o]of Object.entries(s.properties))E(o,e,[...n,i]);s.items&&E(s.items,e,[...n,"[]"]);for(const i of["anyOf","oneOf","allOf"]){const o=s[i];Array.isArray(o)&&o.forEach((a,u)=>E(a,e,[...n,`${i}[${u}]`]))}s.additionalProperties&&typeof s.additionalProperties=="object"&&E(s.additionalProperties,e,[...n,"additionalProperties"])}const h=[];for(let t=0;t<256;++t)h.push((t+256).toString(16).slice(1));function Gt(t,e=0){return(h[t[e+0]]+h[t[e+1]]+h[t[e+2]]+h[t[e+3]]+"-"+h[t[e+4]]+h[t[e+5]]+"-"+h[t[e+6]]+h[t[e+7]]+"-"+h[t[e+8]]+h[t[e+9]]+"-"+h[t[e+10]]+h[t[e+11]]+h[t[e+12]]+h[t[e+13]]+h[t[e+14]]+h[t[e+15]]).toLowerCase()}let b;const Ut=new Uint8Array(16);function Lt(){if(!b){if(typeof crypto>"u"||!crypto.getRandomValues)throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");b=crypto.getRandomValues.bind(crypto)}return b(Ut)}const Pt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),L={randomUUID:Pt};function dt(t,e,n){if(L.randomUUID&&!t)return L.randomUUID();t=t||{};const s=t.random??t.rng?.()??Lt();if(s.length<16)throw new Error("Random bytes length must be >= 16");return s[6]=s[6]&15|64,s[8]=s[8]&63|128,Gt(s)}const D="__gemini_function_call_thought_signatures__",jt="ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ==",Kt=t=>t();function Ft(t){return St.isInstance(t)?t.role:t.type}function Ht(t){switch(t){case"supervisor":case"ai":case"model":return"model";case"system":return"system";case"human":return"user";case"tool":case"function":return"function";default:throw new Error(`Unknown / unsupported author: ${t}`)}}function $t(t){if("mimeType"in t&&"data"in t)return{inlineData:{mimeType:t.mimeType,data:t.data}};if("mimeType"in t&&"fileUri"in t)return{fileData:{mimeType:t.mimeType,fileUri:t.fileUri}};throw new Error("Invalid media content")}function Yt(t,e){return e.map(n=>lt(n)?n.tool_calls??[]:[]).flat().find(n=>n.id===t.tool_call_id)?.name}function Bt(t){return{providerName:"Google Gemini",fromStandardTextBlock(e){return{text:e.text}},fromStandardImageBlock(e){if(!t)throw new Error("This model does not support images");if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardAudioBlock(e){if(!t)throw new Error("This model does not support audio");if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)},fromStandardFileBlock(e){if(!t)throw new Error("This model does not support files");if(e.source_type==="text")return{text:e.text};if(e.source_type==="url"){const n=k({dataUrl:e.url});return n?{inlineData:{mimeType:n.mime_type,data:n.data}}:{fileData:{mimeType:e.mime_type??"",fileUri:e.url}}}if(e.source_type==="base64")return{inlineData:{mimeType:e.mime_type??"",data:e.data}};throw new Error(`Unsupported source type: ${e.source_type}`)}}}function P(t,e){if(Rt(t))return xt(t,Bt(e));if(t.type==="text")return{text:t.text};if(t.type==="executableCode")return{executableCode:t.executableCode};if(t.type==="codeExecutionResult")return{codeExecutionResult:t.codeExecutionResult};if(t.type==="image_url"){if(!e)throw new Error("This model does not support images");let n;if(typeof t.image_url=="string")n=t.image_url;else if(typeof t.image_url=="object"&&"url"in t.image_url)n=t.image_url.url;else throw new Error("Please provide image as base64 encoded data URL");const[s,i]=n.split(",");if(!s.startsWith("data:"))throw new Error("Please provide image as base64 encoded data URL");const[o,a]=s.replace(/^data:/,"").split(";");if(a!=="base64")throw new Error("Please provide image as base64 encoded data URL");return{inlineData:{data:i,mimeType:o}}}else{if(t.type==="media")return $t(t);if(t.type==="tool_use")return{functionCall:{name:t.name,args:t.input}};if(t.type==="tool_call")return{functionCall:{name:t.name,args:t.args}};if(t.type?.includes("/")&&t.type.split("/").length===2&&"data"in t&&typeof t.data=="string")return{inlineData:{mimeType:t.type,data:t.data}};if("functionCall"in t)return;throw"type"in t?new Error(`Unknown content type ${t.type}`):new Error(`Unknown content ${JSON.stringify(t)}`)}}function qt(t,e,n,s){if(At(t)){const u=t.name??Yt(t,n);if(u===void 0)throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${t.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`);const d=Array.isArray(t.content)?t.content.map(p=>P(p,e)).filter(p=>p!==void 0):t.content;return t.status==="error"?[{functionResponse:{name:u,response:{error:{details:d}}}}]:[{functionResponse:{name:u,response:{result:d}}}]}let i=[];const o=[];typeof t.content=="string"&&t.content&&o.push({text:t.content}),Array.isArray(t.content)&&o.push(...t.content.map(u=>P(u,e)).filter(u=>u!==void 0));const a=t.additional_kwargs?.[D];return lt(t)&&t.tool_calls?.length&&(i=t.tool_calls.map(u=>{const d=Kt(()=>{if(u.id){const p=a?.[u.id];if(p)return p}return s?.includes("gemini-3")?jt:""});return{functionCall:{name:u.name,args:u.args},...d?{thoughtSignature:d}:{}}})),[...o,...i]}function j(t,e,n=!1,s){return t.reduce((i,o,a)=>{if(!_t(o))throw new Error("Unsupported message input");const u=Ft(o);if(u==="system"&&a!==0)throw new Error("System message should be the first one");const d=Ht(u),p=i.content[i.content.length];if(!i.mergeWithPreviousContent&&p&&p.role===d)throw new Error("Google Generative AI requires alternate messages between authors");const l=qt(o,e,t.slice(0,a),s);if(i.mergeWithPreviousContent){const f=i.content[i.content.length-1];if(!f)throw new Error("There was a problem parsing your system message. Please try a prompt without one.");return f.parts.push(...l),{mergeWithPreviousContent:!1,content:i.content}}let r=d;(r==="function"||r==="system"&&!n)&&(r="user");const c={role:r,parts:l};return{mergeWithPreviousContent:u==="system"&&!n,content:[...i.content,c]}},{content:[],mergeWithPreviousContent:!1}).content}function Vt(t,e){if(!t.candidates||t.candidates.length===0||!t.candidates[0])return{generations:[],llmOutput:{filters:t.promptFeedback}};const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((l,r)=>("functionCall"in r&&r.functionCall&&l.push({...r,id:"id"in r.functionCall&&typeof r.functionCall.id=="string"?r.functionCall.id:dt()}),l),[]);let a;const u=s?.parts;Array.isArray(u)&&u.length===1&&"text"in u[0]&&u[0].text&&!u[0].thought?a=u[0].text:Array.isArray(u)&&u.length>0?a=u.map(l=>l.thought&&"text"in l&&l.text?{type:"thinking",thinking:l.text,...l.thoughtSignature?{signature:l.thoughtSignature}:{}}:"text"in l?{type:"text",text:l.text}:"inlineData"in l?{type:"inlineData",inlineData:l.inlineData}:"functionCall"in l?{type:"functionCall",functionCall:l.functionCall}:"functionResponse"in l?{type:"functionResponse",functionResponse:l.functionResponse}:"fileData"in l?{type:"fileData",fileData:l.fileData}:"executableCode"in l?{type:"executableCode",executableCode:l.executableCode}:"codeExecutionResult"in l?{type:"codeExecutionResult",codeExecutionResult:l.codeExecutionResult}:l):a=[];const d=o?.reduce((l,r)=>("thoughtSignature"in r&&typeof r.thoughtSignature=="string"&&(l[r.id]=r.thoughtSignature),l),{});let p="";return typeof a=="string"?p=a:Array.isArray(a)&&a.length>0&&(p=a.find(l=>"text"in l)?.text??p),{generations:[{text:p,message:new Et({content:a??"",tool_calls:o?.map(l=>({type:"tool_call",id:l.id,name:l.functionCall.name,args:l.functionCall.args})),additional_kwargs:{...i,[D]:d},usage_metadata:e?.usageMetadata}),generationInfo:i}],llmOutput:{tokenUsage:{promptTokens:e?.usageMetadata?.input_tokens,completionTokens:e?.usageMetadata?.output_tokens,totalTokens:e?.usageMetadata?.total_tokens}}}}function Wt(t,e){if(!t.candidates||t.candidates.length===0)return null;const[n]=t.candidates,{content:s,...i}=n,o=s.parts?.reduce((r,c)=>("functionCall"in c&&c.functionCall&&r.push({...c,id:"id"in c.functionCall&&typeof c.functionCall.id=="string"?c.functionCall.id:dt()}),r),[]);let a;const u=s?.parts;Array.isArray(u)&&u.every(r=>"text"in r&&!r.thought)?a=u.map(r=>r.text).join(""):Array.isArray(u)?a=u.map(r=>r.thought&&"text"in r&&r.text?{type:"thinking",thinking:r.text,...r.thoughtSignature?{signature:r.thoughtSignature}:{}}:"text"in r?{type:"text",text:r.text}:"inlineData"in r?{type:"inlineData",inlineData:r.inlineData}:"functionCall"in r?{type:"functionCall",functionCall:r.functionCall}:"functionResponse"in r?{type:"functionResponse",functionResponse:r.functionResponse}:"fileData"in r?{type:"fileData",fileData:r.fileData}:"executableCode"in r?{type:"executableCode",executableCode:r.executableCode}:"codeExecutionResult"in r?{type:"codeExecutionResult",codeExecutionResult:r.codeExecutionResult}:r):a=[];let d="";a&&typeof a=="string"?d=a:Array.isArray(a)&&(d=a.find(r=>"text"in r)?.text??"");const p=[];o&&p.push(...o.map(r=>({type:"tool_call_chunk",id:r.id,name:r.functionCall.name,args:JSON.stringify(r.functionCall.args)})));const l=o?.reduce((r,c)=>("thoughtSignature"in c&&typeof c.thoughtSignature=="string"&&(r[c.id]=c.thoughtSignature),r),{});return new Tt({text:d,message:new wt({content:a||"",name:s?s.role:void 0,tool_call_chunks:p,additional_kwargs:{[D]:l},response_metadata:{model_provider:"google-genai"},usage_metadata:e.usageMetadata}),generationInfo:i})}function Jt(t){return t.every(e=>"functionDeclarations"in e&&Array.isArray(e.functionDeclarations))?t:[{functionDeclarations:t.map(e=>{if(at(e)){const n=N(e.schema);return n.type==="object"&&"properties"in n&&Object.keys(n.properties).length===0?{name:e.name,description:e.description}:(E(n,e.name),{name:e.name,description:e.description,parameters:n})}if(rt(e)){const n=Dt(e.function.parameters);return E(n,e.function.name),{name:e.function.name,description:e.function.description??"A function available to call.",parameters:n}}return e})}]}function K(t,e){const n={input_tokens:t?.promptTokenCount??0,output_tokens:t?.candidatesTokenCount??0,total_tokens:t?.totalTokenCount??0};if(t?.cachedContentTokenCount&&(n.input_token_details??={},n.input_token_details.cache_read=t.cachedContentTokenCount),e==="gemini-3-pro-preview"){const s=Math.max(0,t?.promptTokenCount??-2e5),i=Math.max(0,t?.cachedContentTokenCount??-2e5);s&&(n.input_token_details={...n.input_token_details,over_200k:s}),i&&(n.input_token_details={...n.input_token_details,cache_read_over_200k:i})}return n}var F=class extends Ct{static lc_name(){return"GoogleGenerativeAIToolsOutputParser"}lc_namespace=["langchain","google_genai","output_parsers"];returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(t){super(t),this.keyName=t.keyName,this.returnSingle=t.returnSingle??this.returnSingle,this.zodSchema=t.zodSchema}async _validateResult(t){if(this.zodSchema===void 0)return t;const e=await kt(this.zodSchema,t);if(e.success)return e.data;throw new Ot(`Failed to parse. Text: "${JSON.stringify(t,null,2)}". Error: ${JSON.stringify(e.error.issues)}`,JSON.stringify(t,null,2))}async parseResult(t){const e=t.flatMap(s=>{const{message:i}=s;return!("tool_calls"in i)||!Array.isArray(i.tool_calls)?[]:i.tool_calls});if(e[0]===void 0)throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser.");const[n]=e;return await this._validateResult(n.args)}},H;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})(H||(H={}));var $;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})($||($={}));var Y;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(Y||(Y={}));const B=["user","model","function","system"];var q;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",t.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(q||(q={}));var V;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(V||(V={}));var W;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(W||(W={}));var J;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(J||(J={}));var w;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.BLOCKLIST="BLOCKLIST",t.PROHIBITED_CONTENT="PROHIBITED_CONTENT",t.SPII="SPII",t.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",t.OTHER="OTHER"})(w||(w={}));var z;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(z||(z={}));var T;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(T||(T={}));var Q;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Q||(Q={}));class m extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}}class _ extends m{constructor(e,n){super(e),this.response=n}}class ft extends m{constructor(e,n,s,i){super(e),this.status=n,this.statusText=s,this.errorDetails=i}}class y extends m{}class pt extends m{}const zt="https://generativelanguage.googleapis.com",Qt="v1beta",Zt="0.24.1",Xt="genai-js";var v;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(v||(v={}));class te{constructor(e,n,s,i,o){this.model=e,this.task=n,this.apiKey=s,this.stream=i,this.requestOptions=o}toString(){var e,n;const s=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Qt;let o=`${((n=this.requestOptions)===null||n===void 0?void 0:n.baseUrl)||zt}/${s}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}}function ee(t){const e=[];return t?.apiClient&&e.push(t.apiClient),e.push(`${Xt}/${Zt}`),e.join(" ")}async function ne(t){var e;const n=new Headers;n.append("Content-Type","application/json"),n.append("x-goog-api-client",ee(t.requestOptions)),n.append("x-goog-api-key",t.apiKey);let s=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(s){if(!(s instanceof Headers))try{s=new Headers(s)}catch(i){throw new y(`unable to convert customHeaders value ${JSON.stringify(s)} to Headers: ${i.message}`)}for(const[i,o]of s.entries()){if(i==="x-goog-api-key")throw new y(`Cannot set reserved header name ${i}`);if(i==="x-goog-api-client")throw new y(`Header name ${i} can only be set using the apiClient field`);n.append(i,o)}}return n}async function se(t,e,n,s,i,o){const a=new te(t,e,n,s,o);return{url:a.toString(),fetchOptions:Object.assign(Object.assign({},re(o)),{method:"POST",headers:await ne(a),body:i})}}async function R(t,e,n,s,i,o={},a=fetch){const{url:u,fetchOptions:d}=await se(t,e,n,s,i,o);return ie(u,d,a)}async function ie(t,e,n=fetch){let s;try{s=await n(t,e)}catch(i){oe(i,t)}return s.ok||await ae(s,t),s}function oe(t,e){let n=t;throw n.name==="AbortError"?(n=new pt(`Request aborted when fetching ${e.toString()}: ${t.message}`),n.stack=t.stack):t instanceof ft||t instanceof y||(n=new m(`Error fetching from ${e.toString()}: ${t.message}`),n.stack=t.stack),n}async function ae(t,e){let n="",s;try{const i=await t.json();n=i.error.message,i.error.details&&(n+=` ${JSON.stringify(i.error.details)}`,s=i.error.details)}catch{}throw new ft(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${n}`,t.status,t.statusText,s)}function re(t){const e={};if(t?.signal!==void 0||t?.timeout>=0){const n=new AbortController;t?.timeout>=0&&setTimeout(()=>n.abort(),t.timeout),t?.signal&&t.signal.addEventListener("abort",()=>{n.abort()}),e.signal=n.signal}return e}function G(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return ue(t)}else if(t.promptFeedback)throw new _(`Text not available. ${O(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Z(t)[0]}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),x(t.candidates[0]))throw new _(`${O(t)}`,t);return Z(t)}else if(t.promptFeedback)throw new _(`Function call not available. ${O(t)}`,t)},t}function ue(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.text&&o.push(a.text),a.executableCode&&o.push("\n```"+a.executableCode.language+`
|
|
2
2
|
`+a.executableCode.code+"\n```\n"),a.codeExecutionResult&&o.push("\n```\n"+a.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Z(t){var e,n,s,i;const o=[];if(!((n=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||n===void 0)&&n.parts)for(const a of(i=(s=t.candidates)===null||s===void 0?void 0:s[0].content)===null||i===void 0?void 0:i.parts)a.functionCall&&o.push(a.functionCall);if(o.length>0)return o}const le=[w.RECITATION,w.SAFETY,w.LANGUAGE];function x(t){return!!t.finishReason&&le.includes(t.finishReason)}function O(t){var e,n,s;let i="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)i+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(i+=` due to ${t.promptFeedback.blockReason}`),!((n=t.promptFeedback)===null||n===void 0)&&n.blockReasonMessage&&(i+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((s=t.candidates)===null||s===void 0)&&s[0]){const o=t.candidates[0];x(o)&&(i+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(i+=`: ${o.finishMessage}`))}return i}function S(t){return this instanceof S?(this.v=t,this):new S(t)}function ce(t,e,n){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=n.apply(t,e||[]),i,o=[];return i={},a("next"),a("throw"),a("return"),i[Symbol.asyncIterator]=function(){return this},i;function a(c){s[c]&&(i[c]=function(f){return new Promise(function(g,C){o.push([c,f,g,C])>1||u(c,f)})})}function u(c,f){try{d(s[c](f))}catch(g){r(o[0][3],g)}}function d(c){c.value instanceof S?Promise.resolve(c.value.v).then(p,l):r(o[0][2],c)}function p(c){u("next",c)}function l(c){u("throw",c)}function r(c,f){c(f),o.shift(),o.length&&u(o[0][0],o[0][1])}}const X=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function de(t){const e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),n=ge(e),[s,i]=n.tee();return{stream:pe(s),response:fe(i)}}async function fe(t){const e=[],n=t.getReader();for(;;){const{done:s,value:i}=await n.read();if(s)return G(he(e));e.push(i)}}function pe(t){return ce(this,arguments,function*(){const n=t.getReader();for(;;){const{value:s,done:i}=yield S(n.read());if(i)break;yield yield S(G(s))}})}function ge(t){const e=t.getReader();return new ReadableStream({start(s){let i="";return o();function o(){return e.read().then(({value:a,done:u})=>{if(u){if(i.trim()){s.error(new m("Failed to parse stream"));return}s.close();return}i+=a;let d=i.match(X),p;for(;d;){try{p=JSON.parse(d[1])}catch{s.error(new m(`Error parsing JSON response: "${d[1]}"`));return}s.enqueue(p),i=i.substring(d[0].length),d=i.match(X)}return o()}).catch(a=>{let u=a;throw u.stack=a.stack,u.name==="AbortError"?u=new pt("Request aborted when reading from the stream"):u=new m("Error reading from the stream"),u})}}})}function he(t){const e=t[t.length-1],n={promptFeedback:e?.promptFeedback};for(const s of t){if(s.candidates){let i=0;for(const o of s.candidates)if(n.candidates||(n.candidates=[]),n.candidates[i]||(n.candidates[i]={index:i}),n.candidates[i].citationMetadata=o.citationMetadata,n.candidates[i].groundingMetadata=o.groundingMetadata,n.candidates[i].finishReason=o.finishReason,n.candidates[i].finishMessage=o.finishMessage,n.candidates[i].safetyRatings=o.safetyRatings,o.content&&o.content.parts){n.candidates[i].content||(n.candidates[i].content={role:o.content.role||"user",parts:[]});const a={};for(const u of o.content.parts)u.text&&(a.text=u.text),u.functionCall&&(a.functionCall=u.functionCall),u.executableCode&&(a.executableCode=u.executableCode),u.codeExecutionResult&&(a.codeExecutionResult=u.codeExecutionResult),Object.keys(a).length===0&&(a.text=""),n.candidates[i].content.parts.push(a)}i++}s.usageMetadata&&(n.usageMetadata=s.usageMetadata)}return n}async function gt(t,e,n,s){const i=await R(e,v.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(n),s);return de(i)}async function ht(t,e,n,s){const o=await(await R(e,v.GENERATE_CONTENT,t,!1,JSON.stringify(n),s)).json();return{response:G(o)}}function mt(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function A(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(const n of t)typeof n=="string"?e.push({text:n}):e.push(n);return me(e)}function me(t){const e={role:"user",parts:[]},n={role:"function",parts:[]};let s=!1,i=!1;for(const o of t)"functionResponse"in o?(n.parts.push(o),i=!0):(e.parts.push(o),s=!0);if(s&&i)throw new m("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!s&&!i)throw new m("No content is provided for sending chat message.");return s?e:n}function Ce(t,e){var n;let s={model:e?.model,generationConfig:e?.generationConfig,safetySettings:e?.safetySettings,tools:e?.tools,toolConfig:e?.toolConfig,systemInstruction:e?.systemInstruction,cachedContent:(n=e?.cachedContent)===null||n===void 0?void 0:n.name,contents:[]};const i=t.generateContentRequest!=null;if(t.contents){if(i)throw new y("CountTokensRequest must have one of contents or generateContentRequest, not both.");s.contents=t.contents}else if(i)s=Object.assign(Object.assign({},s),t.generateContentRequest);else{const o=A(t);s.contents=[o]}return{generateContentRequest:s}}function tt(t){let e;return t.contents?e=t:e={contents:[A(t)]},t.systemInstruction&&(e.systemInstruction=mt(t.systemInstruction)),e}function Oe(t){return typeof t=="string"||Array.isArray(t)?{content:A(t)}:t}const et=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],ye={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function Ie(t){let e=!1;for(const n of t){const{role:s,parts:i}=n;if(!e&&s!=="user")throw new m(`First content should be with role 'user', got ${s}`);if(!B.includes(s))throw new m(`Each item should include role field. Got ${s} but valid roles are: ${JSON.stringify(B)}`);if(!Array.isArray(i))throw new m("Content should have 'parts' property with an array of Parts");if(i.length===0)throw new m("Each Content should have at least one part");const o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(const u of i)for(const d of et)d in u&&(o[d]+=1);const a=ye[s];for(const u of et)if(!a.includes(u)&&o[u]>0)throw new m(`Content with role '${s}' can't contain '${u}' part`);e=!0}}function nt(t){var e;if(t.candidates===void 0||t.candidates.length===0)return!1;const n=(e=t.candidates[0])===null||e===void 0?void 0:e.content;if(n===void 0||n.parts===void 0||n.parts.length===0)return!1;for(const s of n.parts)if(s===void 0||Object.keys(s).length===0||s.text!==void 0&&s.text==="")return!1;return!0}const st="SILENT_ERROR";class ve{constructor(e,n,s,i={}){this.model=n,this.params=s,this._requestOptions=i,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,s?.history&&(Ie(s.history),this._history=s.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,n={}){var s,i,o,a,u,d;await this._sendPromise;const p=A(e),l={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(d=this.params)===null||d===void 0?void 0:d.cachedContent,contents:[...this._history,p]},r=Object.assign(Object.assign({},this._requestOptions),n);let c;return this._sendPromise=this._sendPromise.then(()=>ht(this._apiKey,this.model,l,r)).then(f=>{var g;if(nt(f.response)){this._history.push(p);const C=Object.assign({parts:[],role:"model"},(g=f.response.candidates)===null||g===void 0?void 0:g[0].content);this._history.push(C)}else{const C=O(f.response);C&&console.warn(`sendMessage() was unsuccessful. ${C}. Inspect response object for details.`)}c=f}).catch(f=>{throw this._sendPromise=Promise.resolve(),f}),await this._sendPromise,c}async sendMessageStream(e,n={}){var s,i,o,a,u,d;await this._sendPromise;const p=A(e),l={safetySettings:(s=this.params)===null||s===void 0?void 0:s.safetySettings,generationConfig:(i=this.params)===null||i===void 0?void 0:i.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(a=this.params)===null||a===void 0?void 0:a.toolConfig,systemInstruction:(u=this.params)===null||u===void 0?void 0:u.systemInstruction,cachedContent:(d=this.params)===null||d===void 0?void 0:d.cachedContent,contents:[...this._history,p]},r=Object.assign(Object.assign({},this._requestOptions),n),c=gt(this._apiKey,this.model,l,r);return this._sendPromise=this._sendPromise.then(()=>c).catch(f=>{throw new Error(st)}).then(f=>f.response).then(f=>{if(nt(f)){this._history.push(p);const g=Object.assign({},f.candidates[0].content);g.role||(g.role="model"),this._history.push(g)}else{const g=O(f);g&&console.warn(`sendMessageStream() was unsuccessful. ${g}. Inspect response object for details.`)}}).catch(f=>{f.message!==st&&console.error(f)}),c}}async function _e(t,e,n,s){return(await R(e,v.COUNT_TOKENS,t,!1,JSON.stringify(n),s)).json()}async function Ee(t,e,n,s){return(await R(e,v.EMBED_CONTENT,t,!1,JSON.stringify(n),s)).json()}async function Te(t,e,n,s){const i=n.requests.map(a=>Object.assign(Object.assign({},a),{model:e}));return(await R(e,v.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:i}),s)).json()}class it{constructor(e,n,s={}){this.apiKey=e,this._requestOptions=s,n.model.includes("/")?this.model=n.model:this.model=`models/${n.model}`,this.generationConfig=n.generationConfig||{},this.safetySettings=n.safetySettings||[],this.tools=n.tools,this.toolConfig=n.toolConfig,this.systemInstruction=mt(n.systemInstruction),this.cachedContent=n.cachedContent}async generateContent(e,n={}){var s;const i=tt(e),o=Object.assign(Object.assign({},this._requestOptions),n);return ht(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}async generateContentStream(e,n={}){var s;const i=tt(e),o=Object.assign(Object.assign({},this._requestOptions),n);return gt(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(s=this.cachedContent)===null||s===void 0?void 0:s.name},i),o)}startChat(e){var n;return new ve(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},e),this._requestOptions)}async countTokens(e,n={}){const s=Ce(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),i=Object.assign(Object.assign({},this._requestOptions),n);return _e(this.apiKey,this.model,s,i)}async embedContent(e,n={}){const s=Oe(e),i=Object.assign(Object.assign({},this._requestOptions),n);return Ee(this.apiKey,this.model,s,i)}async batchEmbedContents(e,n={}){const s=Object.assign(Object.assign({},this._requestOptions),n);return Te(this.apiKey,this.model,e,s)}}class M{constructor(e){this.apiKey=e}getGenerativeModel(e,n){if(!e.model)throw new m("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new it(this.apiKey,e,n)}getGenerativeModelFromCachedContent(e,n,s){if(!e.name)throw new y("Cached content must contain a `name` field.");if(!e.model)throw new y("Cached content must contain a `model` field.");const i=["model","systemInstruction"];for(const a of i)if(n?.[a]&&e[a]&&n?.[a]!==e[a]){if(a==="model"){const u=n.model.startsWith("models/")?n.model.replace("models/",""):n.model,d=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(u===d)continue}throw new y(`Different value for "${a}" specified in modelParams (${n[a]}) and cachedContent (${e[a]})`)}const o=Object.assign(Object.assign({},n),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new it(this.apiKey,o,s)}}function ot(t,e){const n=we(t);return{tools:n,toolConfig:Ae(n,e)}}function we(t){let e=[];const n=[];return t.forEach(s=>{if(at(s)){const[i]=Jt([s]);i.functionDeclarations&&e.push(...i.functionDeclarations)}else if(rt(s)){const{functionDeclarations:i}=Se(s);if(i)e.push(...i);else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool")}else n.push(s)}),n.find(s=>"functionDeclarations"in s)?n.map(s=>{if(e?.length>0&&"functionDeclarations"in s){const i={functionDeclarations:[...s.functionDeclarations||[],...e]};return e=[],i}return s}):[...n,...e.length>0?[{functionDeclarations:e}]:[]]}function Se(t){return{functionDeclarations:[{name:t.function.name,description:t.function.description,parameters:I(t.function.parameters)}]}}function Ae(t,e){if(!t.length||!e)return;const{toolChoice:n,allowedFunctionNames:s}=e,i={any:T.ANY,auto:T.AUTO,none:T.NONE};if(n&&["any","auto","none"].includes(n))return{functionCallingConfig:{mode:i[n]??"MODE_UNSPECIFIED",allowedFunctionNames:s}};if(typeof n=="string"||s)return{functionCallingConfig:{mode:T.ANY,allowedFunctionNames:[...s??[],...n&&typeof n=="string"?[n]:[]]}}}const Re={"gemini-embedding-001":{maxInputTokens:2048,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-lite-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-06-05":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-04-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-preview-09-2025":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro-preview-05-06":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-05-20":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-flash-preview":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-live-2.5-flash-preview-native-audio":{maxInputTokens:131072,imageInputs:!1,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-flash-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-flash-lite-preview-06-17":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-2.5-flash-image":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-pro-preview-tts":{maxInputTokens:8e3,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:16e3,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!0,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-2.5-flash-image-preview":{maxInputTokens:32768,imageInputs:!0,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!0,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1},"gemini-1.5-flash-8b":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-3-pro-preview":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:64e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash-lite":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-flash":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1},"gemini-flash-lite-latest":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.5-pro":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-2.0-flash":{maxInputTokens:1048576,imageInputs:!0,audioInputs:!0,pdfInputs:!0,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0},"gemini-1.5-pro":{maxInputTokens:1e6,imageInputs:!0,audioInputs:!0,pdfInputs:!1,videoInputs:!0,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!1}};var Ne=class extends yt{static lc_name(){return"ChatGoogleGenerativeAI"}lc_serializable=!0;get lc_secrets(){return{apiKey:"GOOGLE_API_KEY"}}lc_namespace=["langchain","chat_models","google_genai"];get lc_aliases(){return{apiKey:"google_api_key"}}model;temperature;maxOutputTokens;topP;topK;stopSequences=[];safetySettings;apiKey;streaming=!1;json;streamUsage=!0;convertSystemMessageToHumanContent;thinkingConfig;client;get _isMultimodalModel(){return this.model.includes("vision")||this.model.startsWith("gemini-1.5")||this.model.startsWith("gemini-2")||this.model.startsWith("gemma-3-")&&!this.model.startsWith("gemma-3-1b")||this.model.startsWith("gemini-3")}constructor(t){if(super(t),this.model=t.model.replace(/^models\//,""),this.maxOutputTokens=t.maxOutputTokens??this.maxOutputTokens,this.maxOutputTokens&&this.maxOutputTokens<0)throw new Error("`maxOutputTokens` must be a positive integer");if(this.temperature=t.temperature??this.temperature,this.temperature&&(this.temperature<0||this.temperature>2))throw new Error("`temperature` must be in the range of [0.0,2.0]");if(this.topP=t.topP??this.topP,this.topP&&this.topP<0)throw new Error("`topP` must be a positive integer");if(this.topP&&this.topP>1)throw new Error("`topP` must be below 1.");if(this.topK=t.topK??this.topK,this.topK&&this.topK<0)throw new Error("`topK` must be a positive integer");if(this.stopSequences=t.stopSequences??this.stopSequences,this.apiKey=t.apiKey??ct("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor");if(this.safetySettings=t.safetySettings??this.safetySettings,this.safetySettings&&this.safetySettings.length>0&&new Set(this.safetySettings.map(e=>e.category)).size!==this.safetySettings.length)throw new Error("The categories in `safetySettings` array must be unique");this.streaming=t.streaming??this.streaming,this.json=t.json,this.thinkingConfig=t.thinkingConfig??this.thinkingConfig,this.client=new M(this.apiKey).getGenerativeModel({model:this.model,safetySettings:this.safetySettings,generationConfig:{stopSequences:this.stopSequences,maxOutputTokens:this.maxOutputTokens,temperature:this.temperature,topP:this.topP,topK:this.topK,...this.json?{responseMimeType:"application/json"}:{},...this.thinkingConfig?{thinkingConfig:this.thinkingConfig}:{}}},{apiVersion:t.apiVersion,baseUrl:t.baseUrl,customHeaders:t.customHeaders}),this.streamUsage=t.streamUsage??this.streamUsage}useCachedContent(t,e,n){this.apiKey&&(this.client=new M(this.apiKey).getGenerativeModelFromCachedContent(t,e,n))}get useSystemInstruction(){return typeof this.convertSystemMessageToHumanContent=="boolean"?!this.convertSystemMessageToHumanContent:this.computeUseSystemInstruction}get computeUseSystemInstruction(){return this.model==="gemini-1.0-pro-001"||this.model.startsWith("gemini-pro-vision")||this.model.startsWith("gemini-1.0-pro-vision")?!1:this.model!=="gemini-pro"}getLsParams(t){return{ls_provider:"google_genai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:this.client.generationConfig.temperature,ls_max_tokens:this.client.generationConfig.maxOutputTokens,ls_stop:t.stop}}_combineLLMOutput(){return[]}_llmType(){return"googlegenerativeai"}bindTools(t,e){return this.withConfig({tools:ot(t)?.tools,...e})}invocationParams(t){const e=t?.tools?.length?ot(t.tools,{toolChoice:t.tool_choice,allowedFunctionNames:t.allowedFunctionNames}):void 0;return t?.responseSchema?(this.client.generationConfig.responseSchema=t.responseSchema,this.client.generationConfig.responseMimeType="application/json"):(this.client.generationConfig.responseSchema=void 0,this.client.generationConfig.responseMimeType=this.json?"application/json":void 0),{...e?.tools?{tools:e.tools}:{},...e?.toolConfig?{toolConfig:e.toolConfig}:{}}}async _generate(t,e,n){e.signal?.throwIfAborted();const s=j(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[p]=s;this.client.systemInstruction=p,i=s.slice(1)}const o=this.invocationParams(e);if(this.streaming){const p={},l=this._streamResponseChunks(t,e,n),r=[];for await(const c of l){const f=c.generationInfo?.completion??0;r[f]===void 0?r[f]=c:r[f]=r[f].concat(c)}return{generations:r.filter(c=>c!==void 0),llmOutput:{estimatedTokenUsage:p}}}const a=await this.completionWithRetry({...o,contents:i});let u;"usageMetadata"in a.response&&(u=K(a.response.usageMetadata,this.model));const d=Vt(a.response,{usageMetadata:u});return d.generations?.length>0&&await n?.handleLLMNewToken(d.generations[0]?.text??""),d}async*_streamResponseChunks(t,e,n){const s=j(t,this._isMultimodalModel,this.useSystemInstruction,this.model);let i=s;if(s[0].role==="system"){const[r]=s;this.client.systemInstruction=r,i=s.slice(1)}const o={...this.invocationParams(e),contents:i},a=await this.caller.callWithOptions({signal:e?.signal},async()=>{const{stream:r}=await this.client.generateContentStream(o,{signal:e?.signal});return r});let u,d=0,p=0,l=0;for await(const r of a){if(e.signal?.aborted)return;if("usageMetadata"in r&&r.usageMetadata!==void 0&&this.streamUsage!==!1&&e.streamUsage!==!1){u=K(r.usageMetadata,this.model);const f=r.usageMetadata.promptTokenCount??0;u.input_tokens=Math.max(0,f-d),d=f;const g=r.usageMetadata.candidatesTokenCount??0;u.output_tokens=Math.max(0,g-p),p=g;const C=r.usageMetadata.totalTokenCount??0;u.total_tokens=Math.max(0,C-l),l=C}const c=Wt(r,{usageMetadata:u});c&&(yield c,await n?.handleLLMNewToken(c.text??""))}}async completionWithRetry(t,e){return this.caller.callWithOptions({signal:e?.signal},async()=>{try{return await this.client.generateContent(t,{signal:e?.signal})}catch(n){throw n.message?.includes("400 Bad Request")&&(n.status=400),n}})}get profile(){return Re[this.model]??{}}withStructuredOutput(t,e){const n=t,s=e?.name,i=e?.method,o=e?.includeRaw;if(i==="jsonMode")throw new Error('ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.');let a,u;if(i==="functionCalling"){let r=s??"extract",c;if(ut(n)){const f=N(n);c=[{functionDeclarations:[{name:r,description:f.description??"A function available to call.",parameters:f}]}],u=new F({returnSingle:!0,keyName:r,zodSchema:n})}else{let f;typeof n.name=="string"&&typeof n.parameters=="object"&&n.parameters!=null?(f=n,f.parameters=I(n.parameters),r=n.name):f={name:r,description:n.description??"",parameters:I(n)},c=[{functionDeclarations:[f]}],u=new F({returnSingle:!0,keyName:r})}a=this.bindTools(c).withConfig({allowedFunctionNames:[r]})}else{const r=N(n);a=this.withConfig({responseSchema:r}),u=new It}if(!o)return a.pipe(u).withConfig({runName:"ChatGoogleGenerativeAIStructuredOutput"});const d=U.assign({parsed:(r,c)=>u.invoke(r.raw,c)}),p=U.assign({parsed:()=>null}),l=d.withFallbacks({fallbacks:[p]});return bt.from([{raw:a},l]).withConfig({runName:"StructuredOutputRunnable"})}},Me=class extends Nt{apiKey;modelName="embedding-001";model="embedding-001";taskType;title;stripNewLines=!0;maxBatchSize=100;client;constructor(t){if(super(t??{}),this.modelName=t?.model?.replace(/^models\//,"")??t?.modelName?.replace(/^models\//,"")??this.modelName,this.model=this.modelName,this.taskType=t?.taskType??this.taskType,this.title=t?.title??this.title,this.title&&this.taskType!=="RETRIEVAL_DOCUMENT")throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT");if(this.apiKey=t?.apiKey??ct("GOOGLE_API_KEY"),!this.apiKey)throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor");this.client=new M(this.apiKey).getGenerativeModel({model:this.model},{baseUrl:t?.baseUrl})}_convertToContent(t){return{content:{role:"user",parts:[{text:this.stripNewLines?t.replace(/\n/g," "):t}]},taskType:this.taskType,title:this.title}}async _embedQueryContent(t){const e=this._convertToContent(t);return(await this.client.embedContent(e)).embedding.values??[]}async _embedDocumentsContent(t){const e=Mt(t,this.maxBatchSize),n=e.map(s=>({requests:s.map(i=>this._convertToContent(i))}));return(await Promise.allSettled(n.map(s=>this.client.batchEmbedContents(s)))).flatMap((s,i)=>s.status==="fulfilled"?s.value.embeddings.map(o=>o.values||[]):Array(e[i].length).fill([]))}embedQuery(t){return this.caller.call(this._embedQueryContent.bind(this),t)}embedDocuments(t){return this.caller.call(this._embedDocumentsContent.bind(this),t)}};export{Ne as ChatGoogleGenerativeAI,Me as GoogleGenerativeAIEmbeddings};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{o as E,s as x,i as P,v as $,p as S,A as b,a as C,e as N,m as O,_ as g,b as A,c as I,d as L,f as J,T as f,g as F,C as R,h as M,j as y,k as B,l as _,n as j,q as Z}from"./index-
|
|
1
|
+
import{o as E,s as x,i as P,v as $,p as S,A as b,a as C,e as N,m as O,_ as g,b as A,c as I,d as L,f as J,T as f,g as F,C as R,h as M,j as y,k as B,l as _,n as j,q as Z}from"./index-8CwMSFu3.js";import{B as W,i as q,a as H,b as K,c as V}from"./index-BCuNBDGw.js";var z={};j(z,{BaseToolkit:()=>G,DynamicStructuredTool:()=>k,DynamicTool:()=>D,StructuredTool:()=>T,Tool:()=>w,ToolInputParsingException:()=>f,isLangChainTool:()=>V,isRunnableToolLike:()=>K,isStructuredTool:()=>H,isStructuredToolParams:()=>q,tool:()=>Q});var T=class extends W{extras;returnDirect=!1;verboseParsingErrors=!1;get lc_namespace(){return["langchain","tools"]}responseFormat="content";defaultConfig;constructor(t){super(t??{}),this.verboseParsingErrors=t?.verboseParsingErrors??this.verboseParsingErrors,this.responseFormat=t?.responseFormat??this.responseFormat,this.defaultConfig=t?.defaultConfig??this.defaultConfig,this.metadata=t?.metadata??this.metadata,this.extras=t?.extras??this.extras}async invoke(t,e){let a,s=N(O(this.defaultConfig,e));return g(t)?(a=t.args,s={...s,toolCall:t}):a=t,this.call(a,s)}async call(t,e,a){const s=g(t)?t.args:t;let u;if(A(this.schema))try{u=await I(this.schema,s)}catch(c){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
|
|
2
2
|
Details: ${c.message}`),L(c)&&(o=`${o}
|
|
3
3
|
|
|
4
4
|
${J(c)}`),new f(o,JSON.stringify(t))}else{const c=F(s,this.schema);if(!c.valid){let o="Received tool input did not match expected schema";throw this.verboseParsingErrors&&(o=`${o}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as a}from"./index-
|
|
1
|
+
import{r as a}from"./index-8CwMSFu3.js";import{r as s}from"./inform7-CKh91FfW.js";function c(t,f){for(var o=0;o<f.length;o++){const r=f[o];if(typeof r!="string"&&!Array.isArray(r)){for(const e in r)if(e!=="default"&&!(e in t)){const n=Object.getOwnPropertyDescriptor(r,e);n&&Object.defineProperty(t,e,n.get?n:{enumerable:!0,get:()=>r[e]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var i=s();const m=a(i),l=c({__proto__:null,default:m},[i]);export{l as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as s}from"./ini-CUN5Fz6a.js";function c(t,n){for(var o=0;o<n.length;o++){const e=n[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const i=Object.getOwnPropertyDescriptor(e,r);i&&Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var a=s();const p=f(a),g=c({__proto__:null,default:p},[a]);export{g as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as p}from"./index-
|
|
1
|
+
import{r as p}from"./index-8CwMSFu3.js";import{r as a}from"./irpf90-BGwK5upn.js";function s(t,i){for(var o=0;o<i.length;o++){const r=i[o];if(typeof r!="string"&&!Array.isArray(r)){for(const e in r)if(e!=="default"&&!(e in t)){const f=Object.getOwnPropertyDescriptor(r,e);f&&Object.defineProperty(t,e,f.get?f:{enumerable:!0,get:()=>r[e]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=a();const c=p(n),g=s({__proto__:null,default:c},[n]);export{g as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as a}from"./index-
|
|
1
|
+
import{r as a}from"./index-8CwMSFu3.js";import{r as f}from"./isbl-BW2-1xqY.js";function l(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=f();const c=a(n),b=l({__proto__:null,default:c},[n]);export{b as i};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as s}from"./index-
|
|
1
|
+
import{r as s}from"./index-8CwMSFu3.js";import{r as i}from"./java-BopHZ59q.js";function c(t,n){for(var o=0;o<n.length;o++){const e=n[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const a=Object.getOwnPropertyDescriptor(e,r);a&&Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var f=i();const p=s(f),g=c({__proto__:null,default:p},[f]);export{g as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as c}from"./index-
|
|
1
|
+
import{r as c}from"./index-8CwMSFu3.js";import{r as n}from"./javascript-Bcajz3YC.js";function p(t,s){for(var o=0;o<s.length;o++){const r=s[o];if(typeof r!="string"&&!Array.isArray(r)){for(const e in r)if(e!=="default"&&!(e in t)){const a=Object.getOwnPropertyDescriptor(r,e);a&&Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>r[e]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var i=n();const f=c(i),g=p({__proto__:null,default:f},[i]);export{g as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as a}from"./index-
|
|
1
|
+
import{r as a}from"./index-8CwMSFu3.js";import{r as f}from"./jboss-cli-7Bb2wtKY.js";function l(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=f();const c=a(n),b=l({__proto__:null,default:c},[n]);export{b as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as i}from"./json-_cGKMkqV.js";function c(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const n=Object.getOwnPropertyDescriptor(e,r);n&&Object.defineProperty(t,r,n.get?n:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var a=i();const p=f(a),g=c({__proto__:null,default:p},[a]);export{g as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as s}from"./julia-CflsGA1_.js";function u(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const a=Object.getOwnPropertyDescriptor(e,r);a&&Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=s();const l=f(n),g=u({__proto__:null,default:l},[n]);export{g as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n}from"./index-
|
|
1
|
+
import{r as n}from"./index-8CwMSFu3.js";import{r as p}from"./julia-repl-DTkCRO_Z.js";function f(t,l){for(var o=0;o<l.length;o++){const e=l[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const a=Object.getOwnPropertyDescriptor(e,r);a&&Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var i=p();const s=n(i),g=f({__proto__:null,default:s},[i]);export{g as j};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as s}from"./kotlin-DSmpQSGN.js";function l(r,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const t in e)if(t!=="default"&&!(t in r)){const n=Object.getOwnPropertyDescriptor(e,t);n&&Object.defineProperty(r,t,n.get?n:{enumerable:!0,get:()=>e[t]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var a=s();const c=f(a),g=l({__proto__:null,default:c},[a]);export{g as k};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-
|
|
2
|
-
import{bq as $c,br as eo,bs as jc,t as R,bt as Wr,b7 as Gr,bu as ve,b4 as Lc,bp as Dc,b9 as kn,b2 as re,bb as Fc,b3 as Uc,bv as Vc,K as y,aQ as Re,e as mn,bw as Bc,bx as En,A as He,by as Ss,n as X,aC as hn,aA as se,U as P,ab as ae,j as zc,C as Hc,bz as Wc,z as Do,aY as Ii,bA as oe,aE as xn,bB as _n,X as Pi,S as Ue,bC as to,Q as Me,V as Cs,W as Qt,aJ as yr,bD as Gc,bE as Kc,bF as Jc,bG as qc,bH as Yc,bI as Xc,bJ as Zc,bK as Qc,bL as eu,bM as tu,bN as nu,bO as ru,bP as su,bQ as ou,bR as iu,bS as au,bT as lu,bU as cu,bV as uu,bW as hu,a1 as du,bX as fu,bY as pu,bZ as mu,p as vn,m as $e,a2 as it,aN as en,b_ as gu,Y as yu,aZ as Fo,aO as wu,b$ as Uo,c0 as Vo,c1 as wr,c2 as bt,b5 as no,ax as Ts,aw as ks,az as bu,ad as _u,as as ro,ay as so,an as te,av as nt,o as K,c3 as Le,c4 as Oi,b as oo,l as j,c5 as vu,c6 as Su,c7 as Cu,ac as Ni,at as Tu,x as ku,aR as Eu,T as xu,c8 as Dn,c9 as De,s as ie,ca as Ri,cb as tn,cc as Mn,cd as Mu,ce as Ke,cf as _t,cg as z,au as Au,f as io,aB as Iu,a as Pu,ch as $i,ci as Fn,cj as gt,ck as Ou,bl as Nu,bj as Ru,bi as $u,cl as ju,H as ji,cm as Xn,cn as Bo,u as nn,bg as Zn,E as Lu,co as Du,J as zo,cp as Fu,cq as Uu,cr as Vu,O as Bu,cs as zu,ct as Hu,cu as Ho}from"./index-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/client-A6Te1Nrl.js","assets/index-8CwMSFu3.js","assets/index-Br5Lp-nB.css","assets/display-A5IEINAP-cWKELVdp.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{bq as $c,br as eo,bs as jc,t as R,bt as Wr,b7 as Gr,bu as ve,b4 as Lc,bp as Dc,b9 as kn,b2 as re,bb as Fc,b3 as Uc,bv as Vc,K as y,aQ as Re,e as mn,bw as Bc,bx as En,A as He,by as Ss,n as X,aC as hn,aA as se,U as P,ab as ae,j as zc,C as Hc,bz as Wc,z as Do,aY as Ii,bA as oe,aE as xn,bB as _n,X as Pi,S as Ue,bC as to,Q as Me,V as Cs,W as Qt,aJ as yr,bD as Gc,bE as Kc,bF as Jc,bG as qc,bH as Yc,bI as Xc,bJ as Zc,bK as Qc,bL as eu,bM as tu,bN as nu,bO as ru,bP as su,bQ as ou,bR as iu,bS as au,bT as lu,bU as cu,bV as uu,bW as hu,a1 as du,bX as fu,bY as pu,bZ as mu,p as vn,m as $e,a2 as it,aN as en,b_ as gu,Y as yu,aZ as Fo,aO as wu,b$ as Uo,c0 as Vo,c1 as wr,c2 as bt,b5 as no,ax as Ts,aw as ks,az as bu,ad as _u,as as ro,ay as so,an as te,av as nt,o as K,c3 as Le,c4 as Oi,b as oo,l as j,c5 as vu,c6 as Su,c7 as Cu,ac as Ni,at as Tu,x as ku,aR as Eu,T as xu,c8 as Dn,c9 as De,s as ie,ca as Ri,cb as tn,cc as Mn,cd as Mu,ce as Ke,cf as _t,cg as z,au as Au,f as io,aB as Iu,a as Pu,ch as $i,ci as Fn,cj as gt,ck as Ou,bl as Nu,bj as Ru,bi as $u,cl as ju,H as ji,cm as Xn,cn as Bo,u as nn,bg as Zn,E as Lu,co as Du,J as zo,cp as Fu,cq as Uu,cr as Vu,O as Bu,cs as zu,ct as Hu,cu as Ho}from"./index-8CwMSFu3.js";import{a as Qn,S as jr,b as Wu,t as Li,T as Gu,D as Ku}from"./index-DkeQAS92.js";import{h as Un,s as Di,g as Fi,d as Ju,l as qu,m as Yu,I as Xu,C as Zu,n as Qu,t as eh,o as th,p as nh,q as rh,r as sh,u as oh,v as ih,w as ah,x as lh,y as ch,z as uh,R as hh,A as Wo,e as dh}from"./index-BCuNBDGw.js";import{E as Ui,a as fh,e as ph}from"./embeddings-BPcF2rPH.js";import{L as Vi,o as mh,l as gh}from"./llms--9GbEsAa.js";var Kr,Hn,Jr=0,qr=0;function yh(t,e,n){var r=0,s=e||new Array(16);t=t||{};var o=t.node,i=t.clockseq;if(t._v6||(o||(o=Kr),i==null&&(i=Hn)),o==null||i==null){var a=t.random||(t.rng||$c)();o==null&&(o=[a[0],a[1],a[2],a[3],a[4],a[5]],!Kr&&!t._v6&&(o[0]|=1,Kr=o)),i==null&&(i=(a[6]<<8|a[7])&16383,Hn===void 0&&!t._v6&&(Hn=i))}var l=t.msecs!==void 0?t.msecs:Date.now(),c=t.nsecs!==void 0?t.nsecs:qr+1,u=l-Jr+(c-qr)/1e4;if(u<0&&t.clockseq===void 0&&(i=i+1&16383),(u<0||l>Jr)&&t.nsecs===void 0&&(c=0),c>=1e4)throw new Error("uuid.v1(): Can't create more than 10M uuids/sec");Jr=l,qr=c,Hn=i,l+=122192928e5;var d=((l&268435455)*1e4+c)%4294967296;s[r++]=d>>>24&255,s[r++]=d>>>16&255,s[r++]=d>>>8&255,s[r++]=d&255;var h=l/4294967296*1e4&268435455;s[r++]=h>>>8&255,s[r++]=h&255,s[r++]=h>>>24&15|16,s[r++]=h>>>16&255,s[r++]=i>>>8|128,s[r++]=i&255;for(var f=0;f<6;++f)s[r+f]=o[f];return e||eo(s)}function wh(t){var e=typeof t=="string"?jc(t):t,n=bh(e);return typeof t=="string"?eo(n):n}function bh(t,e=!1){return Uint8Array.of((t[6]&15)<<4|t[7]>>4&15,(t[7]&15)<<4|(t[4]&240)>>4,(t[4]&15)<<4|(t[5]&240)>>4,(t[5]&15)<<4|(t[0]&240)>>4,(t[0]&15)<<4|(t[1]&240)>>4,(t[1]&15)<<4|(t[2]&240)>>4,96|t[2]&15,t[3],t[8],t[9],t[10],t[11],t[12],t[13],t[14],t[15])}function Go(t,e){var n=Object.keys(t);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(t);e&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(t,s).enumerable})),n.push.apply(n,r)}return n}function Ko(t){for(var e=1;e<arguments.length;e++){var n=arguments[e]!=null?arguments[e]:{};e%2?Go(Object(n),!0).forEach(function(r){_h(t,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(n)):Go(Object(n)).forEach(function(r){Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(n,r))})}return t}function _h(t,e,n){return(e=vh(e))in t?Object.defineProperty(t,e,{value:n,enumerable:!0,configurable:!0,writable:!0}):t[e]=n,t}function vh(t){var e=Sh(t,"string");return typeof e=="symbol"?e:e+""}function Sh(t,e){if(typeof t!="object"||!t)return t;var n=t[Symbol.toPrimitive];if(n!==void 0){var r=n.call(t,e);if(typeof r!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(e==="string"?String:Number)(t)}function Ch(t={},e,n=0){var r=yh(Ko(Ko({},t),{},{_v6:!0}),new Uint8Array(16));return r=wh(r),eo(r)}async function*Bi(t){for await(const e of t)if(e.event==="on_chat_model_stream"&&e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}}R(Bi,"streamEventsToAISDK");function zi(t){return new ReadableStream({async start(e){try{for await(const n of t)e.enqueue(n);e.close()}catch(n){e.error(n)}}})}R(zi,"createReadableStreamFromGenerator");async function*Hi(t){for await(const e of t)switch(e.event){case"on_chat_model_stream":if(e.data?.chunk?.text){const n=e.data.chunk.text;typeof n=="string"&&n.length>0&&(yield n)}break;case"on_tool_start":yield`
|
|
3
3
|
🔧 Using tool: ${e.name}
|
|
4
4
|
`;break;case"on_tool_end":yield`
|
|
5
5
|
✅ Tool completed: ${e.name}
|
|
@@ -387,7 +387,7 @@ You can then use these server-specific tools in subsequent steps.
|
|
|
387
387
|
Here are the tools *currently* available to you (this list includes server management tools and will
|
|
388
388
|
change when you connect to a server):
|
|
389
389
|
{tool_descriptions}
|
|
390
|
-
`;function gr(t,e,n,r,s,o){if(typeof t=="object"&&t!==null){const i=t;return{query:i.prompt,maxSteps:i.maxSteps,manageConnector:i.manageConnector,externalHistory:i.externalHistory,outputSchema:i.schema,signal:i.signal}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s,signal:o}}R(gr,"normalizeRunOptions");var Zt,Ty=(Zt=class{static getPackageVersion(){return ji()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Mc({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new xt,this.telemetry=Xn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],y.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.exposeResourcesAsTools=e.exposeResourcesAsTools??!0,this.exposePromptsAsTools=e.exposePromptsAsTools??!0,this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new xt(this.disallowedTools),this.telemetry=Xn.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new xt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new xi(this.client,this.adapter)}else this.adapter=e.adapter??new xt(this.disallowedTools);if(this.telemetry=Xn.getInstance(),this.llm){const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:R(()=>this.getMetadata(),"metadataProvider"),tagsProvider:R(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:R(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:R(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:R(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await nn(async()=>{const{MCPClient:s}=await import("./client-hyRgVCty.js").then(o=>o.c);return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await $o(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new xi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=Object.values(this.sessions).map(l=>l.connector),o=await this.adapter.createToolsFromConnectors(s),i=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(s):[],a=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(s):[];this._tools=[...o,...i,...a],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${o.length} tools, ${i.length} resources, ${a.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Sy;this.systemMessage=Rc(e,n,Cy,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof oe))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Tc({runLimit:this.maxSteps})],s=sc({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new oe(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof oe)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new xt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){y.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof P)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof se)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof j)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof P||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(a,l,c,u,d);const f=this.stream(a,l,c,u,d,h);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(a,l,c,u,d);let f=!1;const m=Date.now();let p=!1,C=null,T=0;try{if(c&&!this._initialized?(await this.initialize(),f=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),f=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const b=this.serverManager.tools,E=new Set(b.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(E.size!==S.size||[...E].some(x=>!S.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...E].join(", ")}`),this._tools=b,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const k=u??this.conversationHistory,_=[];for(const b of k)(this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b))&&_.push(b);const g=a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:a.replace(/\n/g," ");y.info(`💬 Received query: '${g}'`),y.info("🏁 Starting agent execution");const v=3;let M=0;const w=[..._,new se(a)];for(;M<=v;){const b={messages:w};let E=!1;const S=await this._agentExecutor.stream(b,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...h&&{signal:h}});for await(const x of S){if(h?.aborted)break;for(const[I,O]of Object.entries(x))if(y.debug(`📦 Node '${I}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let F=O.messages;Array.isArray(F)||(F=[F]);for(const ce of F)w.includes(ce)||w.push(ce);for(const ce of F){if("tool_calls"in ce&&Array.isArray(ce.tool_calls)&&ce.tool_calls.length>0)for(const Ie of ce.tool_calls){const we=Ie.name||"unknown",ht=Ie.args||{};this.toolsUsedNames.push(we),T++;let Je=JSON.stringify(ht);Je.length>100&&(Je=`${Je.slice(0,97)}...`),y.info(`🔧 Tool call: ${we} with input: ${Je}`),yield{action:{tool:we,toolInput:ht,log:`Calling tool ${we}`},observation:""}}if(this._isToolMessageLike(ce)){const Ie=ce.content;let we=String(Ie);if(we.length>100&&(we=`${we.slice(0,97)}...`),we=we.replace(/\n/g," "),y.info(`📄 Tool result: ${we}`),this.useServerManager&&this.serverManager){const ht=this.serverManager.tools,Je=new Set(ht.map(fn=>fn.name)),Lo=new Set(this._tools.map(fn=>fn.name));if(Je.size!==Lo.size||[...Je].some(fn=>!Lo.has(fn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Je].join(", ")}`),this._tools=ht,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),E=!0,M++,y.info(`🔃 Restarting execution with updated tools (restart ${M}/${v})`);break}}}this._isAIMessageLike(ce)&&!this._messageHasToolCalls(ce)&&(C=this._normalizeOutput(this._getMessageContent(ce)),y.info("✅ Agent finished with output"))}if(E)break}if(E)break}if(!E)break;if(M>v){y.warn(`⚠️ Max restarts (${v}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const b=w.slice(_.length);for(const E of b)this.addToHistory(E)}if(d&&C)try{y.info("🔧 Attempting structured output...");const b=await this._attemptStructuredOutput(C,this.llm,d);return this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(b)}`)),y.info("✅ Structured output successful"),p=!0,b}catch(b){throw y.error(`❌ Structured output failed: ${b}`),new Error(`Failed to generate structured output: ${b instanceof Error?b.message:String(b)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),p=!0,C||"No output generated"}catch(k){throw y.error(`❌ Error running query: ${k}`),f&&c&&(y.info("🧹 Cleaning up resources after error"),await this.close()),k}finally{const k=Date.now()-m;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0,v=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(M=>M.publicIdentifier),totalToolsAvailable:v.length,toolsAvailableNames:v.map(M=>M.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,stepsTaken:T,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:C||"",executionTimeMs:k,errorType:p?null:"execution_error",conversationHistoryLength:g}),c&&!this.client&&f&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new xt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await nn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-CIPa27wl.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o,i){const a=gr(e,n,r,s,o,i);let{query:l}=a;const{maxSteps:c,manageConnector:u,externalHistory:d,outputSchema:h,signal:f}=a;let m=!1;const p=Date.now();let C=!1,T=0,k=0,_="";h&&(l=this._enhanceQueryWithSchema(l,h));try{u&&!this._initialized?(await this.initialize(),m=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),m=!0);const g=this._agentExecutor;if(!g)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const v=typeof l=="string"&&l.length>50?`${l.slice(0,50).replace(/\n/g," ")}...`:typeof l=="string"?l.replace(/\n/g," "):String(l);y.info(`💬 Received query for streamEvents: '${v}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${v}`),this.addToHistory(new se({content:l})));const M=d??this.conversationHistory,w=[];for(const S of M)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?w.push(S):y.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const b=[...w,new se(l)];y.info("callbacks",this.callbacks);const E=g.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(const S of E){if(f?.aborted)break;if(T++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(k+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){_||(_="");const I=this._normalizeOutput(x.content);_+=I,y.debug(`📝 Accumulated response length: ${_.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!_){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?_=x[0].text:typeof x=="string"?_=x:x&&typeof x=="object"&&"output"in x&&(_=x.output)}}}if(h&&_){y.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,I=null;this._attemptStructuredOutput(_,this.llm,h).then(F=>(S=!0,x=F,F)).catch(F=>{throw S=!0,I=F,F});let O=0;for(;!S;)await new Promise(F=>setTimeout(F,2e3)),S||(O++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${O*2}s)`,elapsed:O*2}});if(I)throw I;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(S){y.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&_&&this.addToHistory(new P(_));console.log(`
|
|
390
|
+
`;function gr(t,e,n,r,s,o){if(typeof t=="object"&&t!==null){const i=t;return{query:i.prompt,maxSteps:i.maxSteps,manageConnector:i.manageConnector,externalHistory:i.externalHistory,outputSchema:i.schema,signal:i.signal}}return{query:t,maxSteps:e,manageConnector:n,externalHistory:r,outputSchema:s,signal:o}}R(gr,"normalizeRunOptions");var Zt,Ty=(Zt=class{static getPackageVersion(){return ji()}llm;client;connectors;maxSteps;autoInitialize;memoryEnabled;disallowedTools;additionalTools;toolsUsedNames=[];exposeResourcesAsTools=!0;exposePromptsAsTools=!0;useServerManager;verbose;observe;systemPrompt;systemPromptTemplateOverride;additionalInstructions;_initialized=!1;conversationHistory=[];_agentExecutor=null;sessions={};systemMessage=null;_tools=[];adapter;serverManager=null;telemetry;modelProvider;modelName;observabilityManager;callbacks=[];metadata={};tags=[];isRemote=!1;remoteAgent=null;isSimplifiedMode=!1;llmString;llmConfig;mcpServersConfig;clientOwnedByAgent=!1;constructor(e){if(e.agentId){this.isRemote=!0,this.remoteAgent=new Mc({agentId:e.agentId,apiKey:e.apiKey,baseUrl:e.baseUrl}),this.maxSteps=e.maxSteps??5,this.memoryEnabled=e.memoryEnabled??!0,this.autoInitialize=e.autoInitialize??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.connectors=[],this.disallowedTools=[],this.additionalTools=[],this.useServerManager=!1,this.adapter=new xt,this.telemetry=Xn.getInstance(),this.modelProvider="remote",this.modelName="remote-agent",this.observabilityManager=new Qs({customCallbacks:e.callbacks,agentId:e.agentId}),this.callbacks=[];return}if(!e.llm)throw new Error("llm is required for local execution. For remote execution, provide agentId instead.");if(typeof e.llm=="string"){if(this.isSimplifiedMode=!0,this.llmString=e.llm,this.llmConfig=e.llmConfig,this.mcpServersConfig=e.mcpServers,!this.mcpServersConfig||Object.keys(this.mcpServersConfig).length===0)throw new Error("Simplified mode requires 'mcpServers' configuration. Provide an object with server configurations, e.g., { filesystem: { command: 'npx', args: [...] } }");this.llm=void 0,this.client=void 0,this.clientOwnedByAgent=!0,this.connectors=[],y.info(`🎯 Simplified mode enabled: LLM will be created from '${this.llmString}'`)}else if(this.isSimplifiedMode=!1,this.llm=e.llm,this.client=e.client,this.connectors=e.connectors??[],this.clientOwnedByAgent=!1,!this.client&&this.connectors.length===0)throw new Error("Explicit mode requires either 'client' or at least one 'connector'. Alternatively, use simplified mode with 'llm' as a string and 'mcpServers' config.");if(this.maxSteps=e.maxSteps??5,this.autoInitialize=e.autoInitialize??!1,this.memoryEnabled=e.memoryEnabled??!0,this.systemPrompt=e.systemPrompt??null,this.systemPromptTemplateOverride=e.systemPromptTemplate??null,this.additionalInstructions=e.additionalInstructions??null,this.disallowedTools=e.disallowedTools??[],this.additionalTools=e.additionalTools??[],this.toolsUsedNames=e.toolsUsedNames??[],this.exposeResourcesAsTools=e.exposeResourcesAsTools??!0,this.exposePromptsAsTools=e.exposePromptsAsTools??!0,this.useServerManager=e.useServerManager??!1,this.verbose=e.verbose??!1,this.observe=e.observe??!0,this.isSimplifiedMode)this.adapter=e.adapter??new xt(this.disallowedTools),this.telemetry=Xn.getInstance(),this.modelProvider="unknown",this.modelName="unknown";else{if(this.useServerManager){if(!this.client)throw new Error("'client' must be provided when 'useServerManager' is true.");this.adapter=e.adapter??new xt(this.disallowedTools),this.serverManager=e.serverManagerFactory?.(this.client)??new xi(this.client,this.adapter)}else this.adapter=e.adapter??new xt(this.disallowedTools);if(this.telemetry=Xn.getInstance(),this.llm){const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}else this.modelProvider="unknown",this.modelName="unknown"}this.observabilityManager=new Qs({customCallbacks:e.callbacks,verbose:this.verbose,observe:this.observe,agentId:e.agentId,metadataProvider:R(()=>this.getMetadata(),"metadataProvider"),tagsProvider:R(()=>this.getTags(),"tagsProvider")}),Object.defineProperty(this,"agentExecutor",{get:R(()=>this._agentExecutor,"get"),configurable:!0}),Object.defineProperty(this,"tools",{get:R(()=>this._tools,"get"),configurable:!0}),Object.defineProperty(this,"initialized",{get:R(()=>this._initialized,"get"),configurable:!0})}async initialize(){if(this.isRemote){this._initialized=!0;return}if(y.info("🚀 Initializing MCP agent and connecting to services..."),this.isSimplifiedMode){if(y.info("🎯 Simplified mode: Creating client and LLM from configuration..."),this.mcpServersConfig){y.info(`Creating MCPClient with ${Object.keys(this.mcpServersConfig).length} server(s)...`);const{MCPClient:r}=await nn(async()=>{const{MCPClient:s}=await import("./client-A6Te1Nrl.js").then(o=>o.c);return{MCPClient:s}},__vite__mapDeps([0,1,2]));this.client=new r({mcpServers:this.mcpServersConfig}),y.info("✅ MCPClient created successfully")}if(this.llmString){y.info(`Creating LLM from string: ${this.llmString}...`);try{this.llm=await $o(this.llmString,this.llmConfig),y.info("✅ LLM created successfully");const[r,s]=Bo(this.llm);this.modelProvider=r,this.modelName=s}catch(r){throw new Error(`Failed to create LLM from string '${this.llmString}': ${r?.message||r}`)}}if(this.useServerManager){if(!this.client)throw new Error("'client' must be available when 'useServerManager' is true.");this.serverManager=new xi(this.client,this.adapter)}}this.callbacks=await this.observabilityManager.getCallbacks();const e=await this.observabilityManager.getHandlerNames();if(e.length>0&&y.info(`📊 Observability enabled with: ${e.join(", ")}`),this.useServerManager&&this.serverManager){await this.serverManager.initialize();const r=this.serverManager.tools;this._tools=r,this._tools.push(...this.additionalTools),y.info(`🔧 Server manager mode active with ${r.length} management tools`),await this.createSystemMessageFromTools(this._tools)}else{if(this.client){if(this.sessions=this.client.getAllActiveSessions(),y.info(`🔌 Found ${Object.keys(this.sessions).length} existing sessions`),Object.keys(this.sessions).filter(s=>s!=="code_mode").length===0&&(y.info("🔄 No active sessions found, creating new ones..."),this.sessions=await this.client.createAllSessions(),y.info(`✅ Created ${Object.keys(this.sessions).length} new sessions`)),this.client.codeMode){const s=this.sessions.code_mode;if(s)this._tools=await this.adapter.createToolsFromConnectors([s.connector]),y.info(`🛠️ Created ${this._tools.length} code mode tools`);else throw new Error("Code mode enabled but code_mode session not found")}else{const s=Object.values(this.sessions).map(l=>l.connector),o=await this.adapter.createToolsFromConnectors(s),i=this.exposeResourcesAsTools?await this.adapter.createResourcesFromConnectors(s):[],a=this.exposePromptsAsTools?await this.adapter.createPromptsFromConnectors(s):[];this._tools=[...o,...i,...a],y.info(`🛠️ Created ${this._tools.length} LangChain items from client: ${o.length} tools, ${i.length} resources, ${a.length} prompts`)}this._tools.push(...this.additionalTools)}else{y.info(`🔗 Connecting to ${this.connectors.length} direct connectors...`);for(const i of this.connectors)i.isClientConnected||await i.connect();const r=await this.adapter.createToolsFromConnectors(this.connectors),s=await this.adapter.createResourcesFromConnectors(this.connectors),o=await this.adapter.createPromptsFromConnectors(this.connectors);this._tools=[...r,...s,...o],this._tools.push(...this.additionalTools),y.info(`🛠️ Created ${this._tools.length} LangChain items from connectors: ${r.length} tools, ${s.length} resources, ${o.length} prompts`)}y.info(`🧰 Found ${this._tools.length} tools across all connectors`),await this.createSystemMessageFromTools(this._tools)}this._agentExecutor=this.createAgent(),this._initialized=!0;const n=this.getMCPServerInfo();Object.keys(n).length>0&&(this.setMetadata(n),y.debug(`MCP server info added to metadata: ${JSON.stringify(n)}`)),y.info("✨ Agent initialization complete")}async createSystemMessageFromTools(e){const n=this.systemPromptTemplateOverride??Sy;this.systemMessage=Rc(e,n,Cy,this.useServerManager,this.disallowedTools,this.systemPrompt??void 0,this.additionalInstructions??void 0),this.memoryEnabled&&(this.conversationHistory=[this.systemMessage,...this.conversationHistory.filter(r=>!(r instanceof oe))])}createAgent(){if(!this.llm)throw new Error("LLM is required to create agent");const e=this.systemMessage?.content??"You are a helpful assistant.",n=this._tools.map(o=>o.name);y.info(`🧠 Agent ready with tools: ${n.join(", ")}`);const r=[Tc({runLimit:this.maxSteps})],s=sc({model:this.llm,tools:this._tools,systemPrompt:e,middleware:r});return y.debug(`Created agent with max_steps=${this.maxSteps} (via ModelCallLimitMiddleware) and ${this.callbacks.length} callbacks`),s}getConversationHistory(){return[...this.conversationHistory]}clearConversationHistory(){this.conversationHistory=this.memoryEnabled&&this.systemMessage?[this.systemMessage]:[]}addToHistory(e){this.memoryEnabled&&this.conversationHistory.push(e)}getSystemMessage(){return this.systemMessage}setSystemMessage(e){this.systemMessage=new oe(e),this.memoryEnabled&&(this.conversationHistory=this.conversationHistory.filter(n=>!(n instanceof oe)),this.conversationHistory.unshift(this.systemMessage)),this._initialized&&this._tools.length&&(this._agentExecutor=this.createAgent(),y.debug("Agent recreated with new system message"))}setDisallowedTools(e){this.disallowedTools=e,this.adapter=new xt(this.disallowedTools),this._initialized&&y.debug("Agent already initialized. Changes will take effect on next initialization.")}getDisallowedTools(){return this.disallowedTools}setMetadata(e){const n=this.sanitizeMetadata(e);this.metadata={...this.metadata,...n},y.debug(`Metadata set: ${JSON.stringify(this.metadata)}`)}getMetadata(){return{...this.metadata}}setTags(e){const n=this.sanitizeTags(e);this.tags=[...new Set([...this.tags,...n])],y.debug(`Tags set: ${JSON.stringify(this.tags)}`)}getTags(){return[...this.tags]}sanitizeMetadata(e){const n={};for(const[r,s]of Object.entries(e)){if(typeof r!="string"||r.length===0){y.warn(`Invalid metadata key: ${r}. Skipping.`);continue}const o=r.replace(/[^\w-]/g,"_");if(s==null)n[o]=s;else if(typeof s=="string"||typeof s=="number"||typeof s=="boolean")n[o]=s;else if(Array.isArray(s)){const i=s.filter(a=>typeof a=="string"||typeof a=="number"||typeof a=="boolean");i.length>0&&(n[o]=i)}else if(typeof s=="object")try{const i=JSON.stringify(s);i.length>1e3?(y.warn(`Metadata value for key '${o}' is too large. Truncating.`),n[o]=`${i.substring(0,1e3)}...`):n[o]=s}catch(i){y.warn(`Failed to serialize metadata value for key '${o}': ${i}. Skipping.`)}else y.warn(`Unsupported metadata value type for key '${o}': ${typeof s}. Skipping.`)}return n}sanitizeTags(e){return e.filter(n=>typeof n=="string"&&n.length>0).map(n=>n.replace(/[^\w:-]/g,"_")).filter(n=>n.length<=50)}getMCPServerInfo(){const e={};try{if(this.client){const n=this.client.getServerNames();e.mcp_servers_count=n.length,e.mcp_server_names=n;const r={};for(const s of n)try{const o=this.client.getServerConfig(s);if(o){let i="unknown";o.command?i="command":o.url?i="http":o.ws_url&&(i="websocket"),r[s]={type:i,has_args:!!o.args,has_env:!!o.env,has_headers:!!o.headers,url:o.url||null,command:o.command||null}}}catch(o){y.warn(`Failed to get config for server '${s}': ${o}`),r[s]={type:"error",error:"config_unavailable"}}e.mcp_server_configs=r}else this.connectors&&this.connectors.length>0&&(e.mcp_servers_count=this.connectors.length,e.mcp_server_names=this.connectors.map(n=>n.publicIdentifier),e.mcp_server_types=this.connectors.map(n=>n.constructor.name))}catch(n){y.warn(`Failed to collect MCP server info: ${n}`),e.error="collection_failed"}return e}_normalizeOutput(e){try{if(typeof e=="string")return e;if(e&&typeof e=="object"&&"content"in e)return this._normalizeOutput(e.content);if(Array.isArray(e)){const n=[];for(const r of e)if(typeof r=="object"&&r!==null)"text"in r&&typeof r.text=="string"?n.push(r.text):"content"in r?n.push(this._normalizeOutput(r.content)):n.push(String(r));else{const s=r&&typeof r=="object"&&"text"in r?r.text:null;if(typeof s=="string")n.push(s);else{const o=r&&typeof r=="object"&&"content"in r?r.content:r;n.push(this._normalizeOutput(o))}}return n.join("")}return String(e)}catch{return String(e)}}_isAIMessageLike(e){if(e instanceof P)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="ai"||r==="assistant")return!0}catch{}if(typeof n._getType=="function")try{const r=n._getType();if(r==="ai"||r==="assistant")return!0}catch{}return"type"in n?n.type==="ai"||n.type==="assistant":"role"in n?n.role==="ai"||n.role==="assistant":!1}_messageHasToolCalls(e){return typeof e=="object"&&e!==null&&"tool_calls"in e&&Array.isArray(e.tool_calls)?e.tool_calls.length>0:!1}_isHumanMessageLike(e){if(e instanceof se)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{const r=n.getType();if(r==="human"||r==="user")return!0}catch{}return"type"in n&&(n.type==="human"||n.type==="user")||"role"in n&&(n.role==="human"||n.role==="user")}_isToolMessageLike(e){if(e instanceof j)return!0;if(typeof e!="object"||e===null)return!1;const n=e;if(typeof n.getType=="function")try{if(n.getType()==="tool")return!0}catch{}return"type"in n&&n.type==="tool"}_getMessageContent(e){if(e instanceof P||e&&typeof e=="object"&&"content"in e)return e.content}async _consumeAndReturn(e){for(;;){const{done:n,value:r}=await e.next();if(n)return r}}async run(e,n,r,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return this.remoteAgent.run(a,l,c,u,d);const f=this.stream(a,l,c,u,d,h);return this._consumeAndReturn(f)}async*stream(e,n,r=!0,s,o,i){const{query:a,maxSteps:l,manageConnector:c,externalHistory:u,outputSchema:d,signal:h}=gr(e,n,r,s,o,i);if(this.isRemote&&this.remoteAgent)return await this.remoteAgent.run(a,l,c,u,d);let f=!1;const m=Date.now();let p=!1,C=null,T=0;try{if(c&&!this._initialized?(await this.initialize(),f=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),f=!0),!this._agentExecutor)throw new Error("MCP agent failed to initialize");if(this.useServerManager&&this.serverManager){const b=this.serverManager.tools,E=new Set(b.map(x=>x.name)),S=new Set(this._tools.map(x=>x.name));(E.size!==S.size||[...E].some(x=>!S.has(x)))&&(y.info(`🔄 Tools changed before execution, updating agent. New tools: ${[...E].join(", ")}`),this._tools=b,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent())}const k=u??this.conversationHistory,_=[];for(const b of k)(this._isHumanMessageLike(b)||this._isAIMessageLike(b)||this._isToolMessageLike(b))&&_.push(b);const g=a.length>50?`${a.slice(0,50).replace(/\n/g," ")}...`:a.replace(/\n/g," ");y.info(`💬 Received query: '${g}'`),y.info("🏁 Starting agent execution");const v=3;let M=0;const w=[..._,new se(a)];for(;M<=v;){const b={messages:w};let E=!1;const S=await this._agentExecutor.stream(b,{streamMode:"updates",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...h&&{signal:h}});for await(const x of S){if(h?.aborted)break;for(const[I,O]of Object.entries(x))if(y.debug(`📦 Node '${I}' output: ${JSON.stringify(O)}`),O&&typeof O=="object"&&"messages"in O){let F=O.messages;Array.isArray(F)||(F=[F]);for(const ce of F)w.includes(ce)||w.push(ce);for(const ce of F){if("tool_calls"in ce&&Array.isArray(ce.tool_calls)&&ce.tool_calls.length>0)for(const Ie of ce.tool_calls){const we=Ie.name||"unknown",ht=Ie.args||{};this.toolsUsedNames.push(we),T++;let Je=JSON.stringify(ht);Je.length>100&&(Je=`${Je.slice(0,97)}...`),y.info(`🔧 Tool call: ${we} with input: ${Je}`),yield{action:{tool:we,toolInput:ht,log:`Calling tool ${we}`},observation:""}}if(this._isToolMessageLike(ce)){const Ie=ce.content;let we=String(Ie);if(we.length>100&&(we=`${we.slice(0,97)}...`),we=we.replace(/\n/g," "),y.info(`📄 Tool result: ${we}`),this.useServerManager&&this.serverManager){const ht=this.serverManager.tools,Je=new Set(ht.map(fn=>fn.name)),Lo=new Set(this._tools.map(fn=>fn.name));if(Je.size!==Lo.size||[...Je].some(fn=>!Lo.has(fn))){y.info(`🔄 Tools changed during execution. New tools: ${[...Je].join(", ")}`),this._tools=ht,this._tools.push(...this.additionalTools),await this.createSystemMessageFromTools(this._tools),this._agentExecutor=this.createAgent(),E=!0,M++,y.info(`🔃 Restarting execution with updated tools (restart ${M}/${v})`);break}}}this._isAIMessageLike(ce)&&!this._messageHasToolCalls(ce)&&(C=this._normalizeOutput(this._getMessageContent(ce)),y.info("✅ Agent finished with output"))}if(E)break}if(E)break}if(!E)break;if(M>v){y.warn(`⚠️ Max restarts (${v}) reached. Continuing with current tools.`);break}}if(this.memoryEnabled){const b=w.slice(_.length);for(const E of b)this.addToHistory(E)}if(d&&C)try{y.info("🔧 Attempting structured output...");const b=await this._attemptStructuredOutput(C,this.llm,d);return this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(b)}`)),y.info("✅ Structured output successful"),p=!0,b}catch(b){throw y.error(`❌ Structured output failed: ${b}`),new Error(`Failed to generate structured output: ${b instanceof Error?b.message:String(b)}`)}return y.info(`🎉 Agent execution complete in ${((Date.now()-m)/1e3).toFixed(2)} seconds`),p=!0,C||"No output generated"}catch(k){throw y.error(`❌ Error running query: ${k}`),f&&c&&(y.info("🧹 Cleaning up resources after error"),await this.close()),k}finally{const k=Date.now()-m;let _=0;this.client?_=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(_=this.connectors.length);const g=this.memoryEnabled?this.conversationHistory.length:0,v=this._tools||[];await this.telemetry.trackAgentExecution({executionMethod:"stream",query:a,success:p,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:_,serverIdentifiers:this.connectors.map(M=>M.publicIdentifier),totalToolsAvailable:v.length,toolsAvailableNames:v.map(M=>M.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:l??null,manageConnector:c??!0,externalHistoryUsed:u!==void 0,stepsTaken:T,toolsUsedCount:this.toolsUsedNames.length,toolsUsedNames:this.toolsUsedNames,response:C||"",executionTimeMs:k,errorType:p?null:"execution_error",conversationHistoryLength:g}),c&&!this.client&&f&&(y.info("🧹 Closing agent after stream completion"),await this.close())}}async flush(){this.isRemote&&this.remoteAgent||(y.debug("Flushing observability traces..."),await this.observabilityManager.flush())}async close(){if(this.isRemote&&this.remoteAgent){await this.remoteAgent.close();return}y.info("🔌 Closing MCPAgent resources…"),await this.observabilityManager.shutdown();try{if(this._agentExecutor=null,this._tools=[],this.client)this.clientOwnedByAgent?(y.info("🔄 Closing internally-created client (simplified mode) and cleaning up resources"),await this.client.close(),this.sessions={},this.client=void 0):(y.info("🔄 Closing client and cleaning up resources"),await this.client.close(),this.sessions={});else for(const e of this.connectors)y.info("🔄 Disconnecting connector"),await e.disconnect();this.isSimplifiedMode&&this.llm&&(y.debug("🔄 Clearing LLM reference (simplified mode)"),this.llm=void 0),"connectorToolMap"in this.adapter&&(this.adapter=new xt)}finally{this._initialized=!1,y.info("👋 Agent closed successfully")}}async*prettyStreamEvents(e,n,r=!0,s,o){const{prettyStreamEvents:i}=await nn(async()=>{const{prettyStreamEvents:l}=await import("./display-A5IEINAP-cWKELVdp.js");return{prettyStreamEvents:l}},__vite__mapDeps([3,1,2])),a="";for await(const l of i(this.streamEvents(e,n,r,s,o)))yield;return a}async*streamEvents(e,n,r=!0,s,o,i){const a=gr(e,n,r,s,o,i);let{query:l}=a;const{maxSteps:c,manageConnector:u,externalHistory:d,outputSchema:h,signal:f}=a;let m=!1;const p=Date.now();let C=!1,T=0,k=0,_="";h&&(l=this._enhanceQueryWithSchema(l,h));try{u&&!this._initialized?(await this.initialize(),m=!0):!this._initialized&&this.autoInitialize&&(await this.initialize(),m=!0);const g=this._agentExecutor;if(!g)throw new Error("MCP agent failed to initialize");this.maxSteps=c??this.maxSteps;const v=typeof l=="string"&&l.length>50?`${l.slice(0,50).replace(/\n/g," ")}...`:typeof l=="string"?l.replace(/\n/g," "):String(l);y.info(`💬 Received query for streamEvents: '${v}'`),this.memoryEnabled&&(y.info(`🔄 Adding user message to history: ${v}`),this.addToHistory(new se({content:l})));const M=d??this.conversationHistory,w=[];for(const S of M)this._isHumanMessageLike(S)||this._isAIMessageLike(S)||this._isToolMessageLike(S)?w.push(S):y.info(`⚠️ Skipped message of type: ${S.constructor?.name||typeof S}`);const b=[...w,new se(l)];y.info("callbacks",this.callbacks);const E=g.streamEvents({messages:b},{streamMode:"messages",version:"v2",callbacks:this.callbacks,metadata:this.getMetadata(),tags:this.getTags(),runName:this.metadata.trace_name||"mcp-use-agent",recursionLimit:this.maxSteps*3,...this.metadata.session_id&&{sessionId:this.metadata.session_id},...f&&{signal:f}});for await(const S of E){if(f?.aborted)break;if(T++,!(!S||typeof S!="object")){if(S.event==="on_chat_model_stream"&&S.data?.chunk?.content&&(k+=S.data.chunk.content.length),S.event==="on_chat_model_stream"&&S.data?.chunk){const x=S.data.chunk;if(x.content){_||(_="");const I=this._normalizeOutput(x.content);_+=I,y.debug(`📝 Accumulated response length: ${_.length}`)}}if(yield S,S.event==="on_chain_end"&&S.data?.output&&!_){const x=S.data.output;Array.isArray(x)&&x.length>0&&x[0]?.text?_=x[0].text:typeof x=="string"?_=x:x&&typeof x=="object"&&"output"in x&&(_=x.output)}}}if(h&&_){y.info("🔧 Attempting structured output conversion...");try{let S=!1,x=null,I=null;this._attemptStructuredOutput(_,this.llm,h).then(F=>(S=!0,x=F,F)).catch(F=>{throw S=!0,I=F,F});let O=0;for(;!S;)await new Promise(F=>setTimeout(F,2e3)),S||(O++,yield{event:"on_structured_output_progress",data:{message:`Converting to structured output... (${O*2}s)`,elapsed:O*2}});if(I)throw I;x&&(yield{event:"on_structured_output",data:{output:x}},this.memoryEnabled&&this.addToHistory(new P(`Structured result: ${JSON.stringify(x)}`)),y.info("✅ Structured output successful"))}catch(S){y.warn(`⚠️ Structured output failed: ${S}`),yield{event:"on_structured_output_error",data:{error:S instanceof Error?S.message:String(S)}}}}else this.memoryEnabled&&_&&this.addToHistory(new P(_));console.log(`
|
|
391
391
|
|
|
392
392
|
`),y.info(`🎉 StreamEvents complete - ${T} events emitted`),C=!0}catch(g){throw y.error(`❌ Error during streamEvents: ${g}`),m&&u&&(y.info("🧹 Cleaning up resources after initialization error in streamEvents"),await this.close()),g}finally{const g=Date.now()-p;let v=0;this.client?v=Object.keys(this.client.getAllActiveSessions()).length:this.connectors&&(v=this.connectors.length);const M=this.memoryEnabled?this.conversationHistory.length:0;await this.telemetry.trackAgentExecution({executionMethod:"streamEvents",query:l,success:C,modelProvider:this.modelProvider,modelName:this.modelName,serverCount:v,serverIdentifiers:this.connectors.map(w=>w.publicIdentifier),totalToolsAvailable:this._tools.length,toolsAvailableNames:this._tools.map(w=>w.name),maxStepsConfigured:this.maxSteps,memoryEnabled:this.memoryEnabled,useServerManager:this.useServerManager,maxStepsUsed:c??null,manageConnector:u??!0,externalHistoryUsed:d!==void 0,response:`[STREAMED RESPONSE - ${k} chars]`,executionTimeMs:g,errorType:C?null:"streaming_error",conversationHistoryLength:M}),u&&!this.client&&m&&(y.info("🧹 Closing agent after streamEvents completion"),await this.close())}}async _attemptStructuredOutput(e,n,r){y.info(`🔄 Attempting structured output with schema: ${JSON.stringify(r,null,2)}`),y.info(`🔄 Raw result: ${JSON.stringify(e,null,2)}`);let s=null,o="";if(y.debug(`🔄 Structured output requested, schema: ${JSON.stringify(Zn(r),null,2)}`),n&&"withStructuredOutput"in n&&typeof n.withStructuredOutput=="function")s=n.withStructuredOutput(r);else if(n)s=n;else throw new Error("LLM is required for structured output");const i=Zn(r),{$schema:a,additionalProperties:l,...c}=i;o=JSON.stringify(c,null,2),y.info(`🔄 Schema description: ${o}`);let u="";typeof e=="string"?u=e:e&&typeof e=="object"&&(u=JSON.stringify(e)),y.info("rawResult",e),u||(u=JSON.stringify(e));const d=3;let h="";for(let f=1;f<=d;f++){y.info(`🔄 Structured output attempt ${f}/${d}`);let m=`
|
|
393
393
|
Please format the following information according to the EXACT schema specified below.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as l}from"./lasso-BciudTQ1.js";function i(t,a){for(var o=0;o<a.length;o++){const e=a[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=l();const c=f(n),g=i({__proto__:null,default:c},[n]);export{g as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as s}from"./index-
|
|
1
|
+
import{r as s}from"./index-8CwMSFu3.js";import{r as l}from"./latex-CHdb8PhR.js";function i(r,n){for(var o=0;o<n.length;o++){const e=n[o];if(typeof e!="string"&&!Array.isArray(e)){for(const t in e)if(t!=="default"&&!(t in r)){const a=Object.getOwnPropertyDescriptor(e,t);a&&Object.defineProperty(r,t,a.get?a:{enumerable:!0,get:()=>e[t]})}}}return Object.freeze(Object.defineProperty(r,Symbol.toStringTag,{value:"Module"}))}var f=l();const c=s(f),g=i({__proto__:null,default:c},[f]);export{g as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as a}from"./index-
|
|
1
|
+
import{r as a}from"./index-8CwMSFu3.js";import{r as s}from"./ldif-jBEfafs_.js";function l(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const f=Object.getOwnPropertyDescriptor(e,r);f&&Object.defineProperty(t,r,f.get?f:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=s();const c=a(n),d=l({__proto__:null,default:c},[n]);export{d as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as s}from"./index-
|
|
1
|
+
import{r as s}from"./index-8CwMSFu3.js";import{r as l}from"./leaf-CQphRTnn.js";function i(t,f){for(var o=0;o<f.length;o++){const e=f[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const a=Object.getOwnPropertyDescriptor(e,r);a&&Object.defineProperty(t,r,a.get?a:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=l();const c=s(n),g=i({__proto__:null,default:c},[n]);export{g as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as l}from"./less-D0Ccux41.js";function i(t,n){for(var o=0;o<n.length;o++){const e=n[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var a=l();const c=f(a),g=i({__proto__:null,default:c},[a]);export{g as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as p}from"./index-
|
|
1
|
+
import{r as p}from"./index-8CwMSFu3.js";import{r as a}from"./lisp-DfrNO5te.js";function f(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var n=a();const l=p(n),g=f({__proto__:null,default:l},[n]);export{g as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n}from"./index-
|
|
1
|
+
import{r as n}from"./index-8CwMSFu3.js";import{r as a}from"./livecodeserver-WU_wnUq8.js";function f(t,i){for(var o=0;o<i.length;o++){const e=i[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const s=Object.getOwnPropertyDescriptor(e,r);s&&Object.defineProperty(t,r,s.get?s:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=a();const l=n(c),v=f({__proto__:null,default:l},[c]);export{v as l};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as n}from"./index-
|
|
1
|
+
import{r as n}from"./index-8CwMSFu3.js";import{r as p}from"./livescript-oQhn4lAX.js";function a(t,s){for(var o=0;o<s.length;o++){const e=s[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const i=Object.getOwnPropertyDescriptor(e,r);i&&Object.defineProperty(t,r,i.get?i:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var c=p();const f=n(c),g=a({__proto__:null,default:f},[c]);export{g as l};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{x as O,y as M,z as R,n as b,C as L,G as N,B as x,D as J,R as P}from"./index-
|
|
1
|
+
import{x as O,y as M,z as R,n as b,C as L,G as N,B as x,D as J,R as P}from"./index-8CwMSFu3.js";import{O as k,d as E,e as T}from"./index-BCuNBDGw.js";function C(n,e){if(n.function===void 0)return;let t;if(e?.partial)try{t=R(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(r){throw new k([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${r.message}`].join(`
|
|
2
2
|
`))}const s={name:n.function.name,args:t,type:"tool_call"};return e?.returnId&&(s.id=n.id),s}function z(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function A(n,e){return{name:n.function?.name,args:n.function?.arguments,id:n.id,error:e,type:"invalid_tool_call"}}var S=class extends E{static lc_name(){return"JsonOutputToolsParser"}returnId=!1;lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;constructor(n){super(n),this.returnId=n?.returnId??this.returnId}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(n){return await this.parsePartialResult(n,!1)}async parsePartialResult(n,e=!0){const t=n[0].message;let s;if(M(t)&&t.tool_calls?.length?s=t.tool_calls.map(a=>{const{id:l,...u}=a;return this.returnId?{id:l,...u}:u}):t.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(t.additional_kwargs.tool_calls)).map(l=>C(l,{returnId:this.returnId,partial:e}))),!s)return[];const r=[];for(const a of s)if(a!==void 0){const l={type:a.name,args:a.args,id:a.id};r.push(l)}return r}},B=class extends S{static lc_name(){return"JsonOutputKeyToolsParser"}lc_namespace=["langchain","output_parsers","openai_tools"];lc_serializable=!0;returnId=!1;keyName;returnSingle=!1;zodSchema;constructor(n){super(n),this.keyName=n.keyName,this.returnSingle=n.returnSingle??this.returnSingle,this.zodSchema=n.zodSchema}async _validateResult(n){if(this.zodSchema===void 0)return n;const e=await O(this.zodSchema,n);if(e.success)return e.data;throw new k(`Failed to parse. Text: "${JSON.stringify(n,null,2)}". Error: ${JSON.stringify(e.error?.issues)}`,JSON.stringify(n,null,2))}async parsePartialResult(n){const t=(await super.parsePartialResult(n)).filter(r=>r.type===this.keyName);let s=t;if(t.length)return this.returnId||(s=t.map(r=>r.args)),this.returnSingle?s[0]:s}async parseResult(n){const t=(await super.parsePartialResult(n,!1)).filter(a=>a.type===this.keyName);let s=t;return t.length?(this.returnId||(s=t.map(a=>a.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(a=>this._validateResult(a)))):void 0}},F={};b(F,{JsonOutputKeyToolsParser:()=>B,JsonOutputToolsParser:()=>S,convertLangChainToolCallToOpenAI:()=>z,makeInvalidToolCall:()=>A,parseToolCall:()=>C});var K={};b(K,{BaseLLM:()=>I,LLM:()=>U});var I=class f extends T{lc_namespace=["langchain","llms",this._llmType()];async invoke(e,t){const s=f._convertInputToPromptValue(e);return(await this.generatePrompt([s],t,t?.callbacks)).generations[0][0].text}async*_streamResponseChunks(e,t,s){throw new Error("Not implemented.")}_separateRunnableConfigFromCallOptionsCompat(e){const[t,s]=super._separateRunnableConfigFromCallOptions(e);return s.signal=t.signal,[t,s]}async*_streamIterator(e,t){if(this._streamResponseChunks===f.prototype._streamResponseChunks)yield this.invoke(e,t);else{const s=f._convertInputToPromptValue(e),[r,a]=this._separateRunnableConfigFromCallOptionsCompat(t),l=await L.configure(r.callbacks,this.callbacks,r.tags,this.tags,r.metadata,this.metadata,{verbose:this.verbose}),u={options:a,invocation_params:this?.invocationParams(a),batch_size:1},h=await l?.handleLLMStart(this.toJSON(),[s.toString()],r.runId,void 0,u,void 0,void 0,r.runName);let o=new N({text:""});try{for await(const i of this._streamResponseChunks(s.toString(),a,h?.[0]))o?o=o.concat(i):o=i,typeof i.text=="string"&&(yield i.text)}catch(i){throw await Promise.all((h??[]).map(d=>d?.handleLLMError(i))),i}await Promise.all((h??[]).map(i=>i?.handleLLMEnd({generations:[[o]]})))}}async generatePrompt(e,t,s){const r=e.map(a=>a.toString());return this.generate(r,t,s)}invocationParams(e){return{}}_flattenLLMResult(e){const t=[];for(let s=0;s<e.generations.length;s+=1){const r=e.generations[s];if(s===0)t.push({generations:[r],llmOutput:e.llmOutput});else{const a=e.llmOutput?{...e.llmOutput,tokenUsage:{}}:void 0;t.push({generations:[r],llmOutput:a})}}return t}async _generateUncached(e,t,s,r){let a;if(r!==void 0&&r.length===e.length)a=r;else{const o=await L.configure(s.callbacks,this.callbacks,s.tags,this.tags,s.metadata,this.metadata,{verbose:this.verbose}),i={options:t,invocation_params:this?.invocationParams(t),batch_size:e.length};a=await o?.handleLLMStart(this.toJSON(),e,s.runId,void 0,i,void 0,void 0,s?.runName)}const l=!!a?.[0].handlers.find(x);let u;if(l&&e.length===1&&this._streamResponseChunks!==f.prototype._streamResponseChunks)try{const o=await this._streamResponseChunks(e[0],t,a?.[0]);let i;for await(const d of o)i===void 0?i=d:i=J(i,d);if(i===void 0)throw new Error("Received empty response from chat model call.");u={generations:[[i]],llmOutput:{}},await a?.[0].handleLLMEnd(u)}catch(o){throw await a?.[0].handleLLMError(o),o}else{try{u=await this._generate(e,t,a?.[0])}catch(i){throw await Promise.all((a??[]).map(d=>d?.handleLLMError(i))),i}const o=this._flattenLLMResult(u);await Promise.all((a??[]).map((i,d)=>i?.handleLLMEnd(o[d])))}const h=a?.map(o=>o.runId)||void 0;return Object.defineProperty(u,P,{value:h?{runIds:h}:void 0,configurable:!0}),u}async _generateCached({prompts:e,cache:t,llmStringKey:s,parsedOptions:r,handledOptions:a,runId:l}){const u=await L.configure(a.callbacks,this.callbacks,a.tags,this.tags,a.metadata,this.metadata,{verbose:this.verbose}),h={options:r,invocation_params:this?.invocationParams(r),batch_size:e.length},o=await u?.handleLLMStart(this.toJSON(),e,l,void 0,h,void 0,void 0,a?.runName),i=[],v=(await Promise.allSettled(e.map(async(c,m)=>{const _=await t.lookup(c,s);return _==null&&i.push(m),_}))).map((c,m)=>({result:c,runManager:o?.[m]})).filter(({result:c})=>c.status==="fulfilled"&&c.value!=null||c.status==="rejected"),p=[];await Promise.all(v.map(async({result:c,runManager:m},_)=>{if(c.status==="fulfilled"){const y=c.value;return p[_]=y.map(w=>(w.generationInfo={...w.generationInfo,tokenUsage:{}},w)),y.length&&await m?.handleLLMNewToken(y[0].text),m?.handleLLMEnd({generations:[y]},void 0,void 0,void 0,{cached:!0})}else return await m?.handleLLMError(c.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(c.reason)}));const g={generations:p,missingPromptIndices:i,startedRunManagers:o};return Object.defineProperty(g,P,{value:o?{runIds:o?.map(c=>c.runId)}:void 0,configurable:!0}),g}async generate(e,t,s){if(!Array.isArray(e))throw new Error("Argument 'prompts' is expected to be a string[]");let r;Array.isArray(t)?r={stop:t}:r=t;const[a,l]=this._separateRunnableConfigFromCallOptionsCompat(r);if(a.callbacks=a.callbacks??s,!this.cache)return this._generateUncached(e,l,a);const{cache:u}=this,h=this._getSerializedCacheKeyParametersForCall(l),{generations:o,missingPromptIndices:i,startedRunManagers:d}=await this._generateCached({prompts:e,cache:u,llmStringKey:h,parsedOptions:l,handledOptions:a,runId:a.runId});let v={};if(i.length>0){const p=await this._generateUncached(i.map(g=>e[g]),l,a,d!==void 0?i.map(g=>d?.[g]):void 0);await Promise.all(p.generations.map(async(g,c)=>{const m=i[c];return o[m]=g,u.update(e[m],h,g)})),v=p.llmOutput??{}}return{generations:o,llmOutput:v}}_identifyingParams(){return{}}_modelType(){return"base_llm"}},U=class extends I{async _generate(n,e,t){return{generations:await Promise.all(n.map((r,a)=>this._call(r,{...e,promptIndex:a},t).then(l=>[{text:l}])))}}};export{I as B,B as J,U as L,z as c,K as l,A as m,F as o,C as p};
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{r as f}from"./index-
|
|
1
|
+
import{r as f}from"./index-8CwMSFu3.js";import{r as s}from"./llvm-Ctq8Ea1M.js";function i(t,n){for(var o=0;o<n.length;o++){const e=n[o];if(typeof e!="string"&&!Array.isArray(e)){for(const r in e)if(r!=="default"&&!(r in t)){const l=Object.getOwnPropertyDescriptor(e,r);l&&Object.defineProperty(t,r,l.get?l:{enumerable:!0,get:()=>e[r]})}}}return Object.freeze(Object.defineProperty(t,Symbol.toStringTag,{value:"Module"}))}var a=s();const c=f(a),u=i({__proto__:null,default:c},[a]);export{u as l};
|