wrong-notebook 2026.10.21 → 2026.10.22-1
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/.next/BUILD_ID +1 -1
- package/.next/build-manifest.json +3 -3
- package/.next/prerender-manifest.json +3 -3
- package/.next/server/app/_global-error.html +1 -1
- package/.next/server/app/_global-error.rsc +1 -1
- package/.next/server/app/_global-error.segments/__PAGE__.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_full.segment.rsc +1 -1
- package/.next/server/app/_global-error.segments/_tree.segment.rsc +1 -1
- package/.next/server/app/_not-found/page.js.nft.json +1 -1
- package/.next/server/app/_not-found/page_client-reference-manifest.js +1 -1
- package/.next/server/app/admin/page.js.nft.json +1 -1
- package/.next/server/app/admin/page_client-reference-manifest.js +1 -1
- package/.next/server/app/admin/user/[id]/page.js.nft.json +1 -1
- package/.next/server/app/admin/user/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/api/admin/dashboard/route.js +1 -1
- package/.next/server/app/api/admin/dashboard/route.js.nft.json +1 -1
- package/.next/server/app/api/ai/models/route.js +2 -2
- package/.next/server/app/api/ai/models/route.js.nft.json +1 -1
- package/.next/server/app/api/ai/test/route.js +3 -3
- package/.next/server/app/api/ai/test/route.js.nft.json +1 -1
- package/.next/server/app/api/analytics/route.js +1 -1
- package/.next/server/app/api/analytics/route.js.nft.json +1 -1
- package/.next/server/app/api/analyze/route.js +2 -2
- package/.next/server/app/api/analyze/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/figure/route.js +2 -2
- package/.next/server/app/api/error-items/[id]/figure/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/fix-latex/route.js +2 -2
- package/.next/server/app/api/error-items/[id]/fix-latex/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/geogebra/route.js +4 -3
- package/.next/server/app/api/error-items/[id]/geogebra/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/reanswer/route.js +5 -4
- package/.next/server/app/api/error-items/[id]/reanswer/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/retag/route.js +6 -6
- package/.next/server/app/api/error-items/[id]/retag/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/[id]/svg-animation/route.js +2 -2
- package/.next/server/app/api/error-items/[id]/svg-animation/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/list/route.js +1 -1
- package/.next/server/app/api/error-items/list/route.js.nft.json +1 -1
- package/.next/server/app/api/error-items/route.js +6 -6
- package/.next/server/app/api/error-items/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js +5 -5
- package/.next/server/app/api/exams/[id]/questions/[questionId]/regenerate/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/results/route.js +6 -6
- package/.next/server/app/api/exams/[id]/results/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/retry/route.js +5 -5
- package/.next/server/app/api/exams/[id]/retry/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/[id]/route.js +3 -3
- package/.next/server/app/api/exams/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/exams/route.js +4 -4
- package/.next/server/app/api/exams/route.js.nft.json +1 -1
- package/.next/server/app/api/export/route.js +1 -1
- package/.next/server/app/api/export/route.js.nft.json +1 -1
- package/.next/server/app/api/geogebra-analyze/route.js +4 -4
- package/.next/server/app/api/geogebra-analyze/route.js.nft.json +1 -1
- package/.next/server/app/api/import/route.js +6 -6
- package/.next/server/app/api/import/route.js.nft.json +1 -1
- package/.next/server/app/api/notebooks/[id]/retag/route.js +3 -3
- package/.next/server/app/api/notebooks/[id]/retag/route.js.nft.json +1 -1
- package/.next/server/app/api/openclaw/batch-upload/route.js +5 -5
- package/.next/server/app/api/openclaw/batch-upload/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/generate/route.js +4 -4
- package/.next/server/app/api/practice/generate/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/record/[id]/route.js +4 -4
- package/.next/server/app/api/practice/record/[id]/route.js.nft.json +1 -1
- package/.next/server/app/api/practice/record/route.js +4 -3
- package/.next/server/app/api/practice/record/route.js.nft.json +1 -1
- package/.next/server/app/api/reanswer/route.js +4 -4
- package/.next/server/app/api/reanswer/route.js.nft.json +1 -1
- package/.next/server/app/api/register/route.js +1 -1
- package/.next/server/app/api/register/route.js.nft.json +1 -1
- package/.next/server/app/api/register/status/route.js +1 -1
- package/.next/server/app/api/register/status/route.js.nft.json +1 -1
- package/.next/server/app/api/settings/route.js +5 -4
- package/.next/server/app/api/settings/route.js.nft.json +1 -1
- package/.next/server/app/api/stats/practice/route.js +1 -1
- package/.next/server/app/api/stats/practice/route.js.nft.json +1 -1
- package/.next/server/app/error-items/[id]/page.js.nft.json +1 -1
- package/.next/server/app/error-items/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/[id]/page.js.nft.json +1 -1
- package/.next/server/app/exams/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/[id]/print/page.js.nft.json +1 -1
- package/.next/server/app/exams/[id]/print/page_client-reference-manifest.js +1 -1
- package/.next/server/app/exams/page.js.nft.json +1 -1
- package/.next/server/app/exams/page_client-reference-manifest.js +1 -1
- package/.next/server/app/latex-test/page.js.nft.json +1 -1
- package/.next/server/app/latex-test/page_client-reference-manifest.js +1 -1
- package/.next/server/app/login/page.js.nft.json +1 -1
- package/.next/server/app/login/page_client-reference-manifest.js +1 -1
- package/.next/server/app/notebooks/[id]/add/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/[id]/add/page_client-reference-manifest.js +1 -1
- package/.next/server/app/notebooks/[id]/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/[id]/page_client-reference-manifest.js +1 -1
- package/.next/server/app/notebooks/page.js.nft.json +1 -1
- package/.next/server/app/notebooks/page_client-reference-manifest.js +1 -1
- package/.next/server/app/page.js.nft.json +1 -1
- package/.next/server/app/page_client-reference-manifest.js +1 -1
- package/.next/server/app/practice/page.js.nft.json +1 -1
- package/.next/server/app/practice/page_client-reference-manifest.js +1 -1
- package/.next/server/app/print-preview/page.js.nft.json +1 -1
- package/.next/server/app/print-preview/page_client-reference-manifest.js +1 -1
- package/.next/server/app/register/page.js.nft.json +1 -1
- package/.next/server/app/register/page_client-reference-manifest.js +1 -1
- package/.next/server/app/stats/page.js.nft.json +1 -1
- package/.next/server/app/stats/page_client-reference-manifest.js +1 -1
- package/.next/server/app/tags/page.js.nft.json +1 -1
- package/.next/server/app/tags/page_client-reference-manifest.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__0-8hf14._.js → [root-of-the-server]__02j1w81._.js} +1 -1
- package/.next/server/chunks/{[root-of-the-server]__08gak8r._.js → [root-of-the-server]__03nfvnm._.js} +1 -1
- package/.next/server/chunks/{[root-of-the-server]__0gpohuv._.js → [root-of-the-server]__06_nln5._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__07jl92a._.js +1 -1
- package/.next/server/chunks/{[root-of-the-server]__08zi-xg._.js → [root-of-the-server]__0be5c5r._.js} +1 -1
- package/.next/server/chunks/{[root-of-the-server]__0994h9l._.js → [root-of-the-server]__0bqawi0._.js} +1 -1
- package/.next/server/chunks/[root-of-the-server]__0bsw5c9._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0cmxmwt._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__1utxo11._.js → [root-of-the-server]__0d5dpu4._.js} +2 -2
- package/.next/server/chunks/{[root-of-the-server]__05no8nw._.js → [root-of-the-server]__0d9ijed._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__0fnyu4s._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0j5231l._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__0m_f8ct._.js → [root-of-the-server]__0k-nf6a._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__0k-p1pj._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0lrdm1u._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0lro5a7._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0mfjf2y._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__0yds0ae._.js → [root-of-the-server]__0mqorxb._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__0no6umu._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0o9gtvd._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__0ynfeq-._.js → [root-of-the-server]__0obb4y-._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__0p3u6_q._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0rmrkd_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0tdibjz._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0vhjihq._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0vz88er._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0wf9znr._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__0zv7jom._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__11_-ncy._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__11_1z7m._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__11n87go._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__11p4ahb._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__122xu-0._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__131taws._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__14dnbrn._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__14jqm9_._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__152lbaw._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__04mu6-m._.js → [root-of-the-server]__16begv4._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__17duis5._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__17q3k-v._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__184u6de._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__18atlj8._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__18c7l6u._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__18zrkky._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1aaux7e._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1cceu4b._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1h09r50._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1j6mx-v._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1jdi-1f._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1ju8z29._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1kpo44g._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1lct0vi._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1loecue._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1mkpya8._.js +3 -0
- package/.next/server/chunks/{[root-of-the-server]__1a4i9sz._.js → [root-of-the-server]__1nwf3ua._.js} +2 -2
- package/.next/server/chunks/[root-of-the-server]__1p8hw44._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1rsn804._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1u-1vx4._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1v6nwhq._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__1vw740y._.js +1 -1
- package/.next/server/chunks/[root-of-the-server]__20465pr._.js +3 -0
- package/.next/server/chunks/[root-of-the-server]__207mxv8._.js +3 -0
- package/.next/server/chunks/_0-eguqv._.js +3 -0
- package/.next/server/chunks/_0389uce._.js +3 -0
- package/.next/server/chunks/_0_o8yhv._.js +3 -0
- package/.next/server/chunks/_0gwg6ba._.js +3 -0
- package/.next/server/chunks/_0rdo0a4._.js +3 -0
- package/.next/server/chunks/_13ffmxv._.js +1 -1
- package/.next/server/chunks/_167vv93._.js +3 -0
- package/.next/server/chunks/_16jdov0._.js +1 -1
- package/.next/server/chunks/{_1ve0z0w._.js → _1e1h1f1._.js} +1 -1
- package/.next/server/chunks/_1flar98._.js +3 -0
- package/.next/server/chunks/_1pvqo-q._.js +3 -0
- package/.next/server/chunks/src_lib_ai_prompts_ts_0z36zms._.js +15 -8
- package/.next/server/chunks/ssr/src_1gayunq._.js +1 -1
- package/.next/server/chunks/ssr/src_1o363ao._.js +1 -1
- package/.next/server/chunks/ssr/src_app_error-items_[id]_page_tsx_04xwwdm._.js +1 -1
- package/.next/server/chunks/ssr/src_app_notebooks_[id]_page_tsx_08njm-5._.js +1 -1
- package/.next/server/chunks/ssr/src_components_providers_tsx_09kw-mv._.js +10 -10
- package/.next/server/middleware-build-manifest.js +3 -3
- package/.next/server/middleware-manifest.json +5 -5
- package/.next/server/pages/500.html +1 -1
- package/.next/server/server-reference-manifest.js +1 -1
- package/.next/server/server-reference-manifest.json +1 -1
- package/.next/static/chunks/130ch9mnvb6mp.css +3 -0
- package/.next/static/chunks/17wdtw8hml2n6.js +191 -0
- package/.next/static/chunks/2a0kgntckcbvf.js +1 -0
- package/.next/static/chunks/{05q4yafxnvtzs.js → 2wnnnmbh85mq_.js} +1 -1
- package/.next/static/chunks/3hz1l3qoxv84t.js +1 -0
- package/launcher.js +16 -0
- package/package.json +1 -1
- package/prisma/seed.db +0 -0
- package/.next/server/chunks/[root-of-the-server]__00m7v48._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__01m28mx._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__07nvz1d._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0b3nww4._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0bs5unr._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0dfbwm3._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0els3c1._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0grkic-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0hj9oe2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0j-gv3-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0je3zje._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0na-z2m._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0ns_tws._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0p3hkz7._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0pli74s._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0qaih8c._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0ra48rd._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0sh6-yu._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0ssagl1._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0ws6c0v._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0ydrrdj._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0z-sjqh._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__0zp1e41._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__108ydjw._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__10yghm_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__11-sf2-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__11wobg2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__13_c7nc._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__14pcopd._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__150ei9u._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__15g7yjy._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__19nm3y_._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1e3crdc._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1g-xe1f._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1g3usdn._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1hmv25w._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1hq73__._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1ouzjax._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1pcgq22._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1q5nt5y._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1qt6_3b._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1v1dgs2._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1v9b8go._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1vzxn91._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1wgn76g._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1wkh9sj._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1xcmja4._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1y6fx9-._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1zos_p4._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__1zp0oig._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__203q6el._.js +0 -3
- package/.next/server/chunks/[root-of-the-server]__20bun16._.js +0 -3
- package/.next/server/chunks/_0ae3z2e._.js +0 -3
- package/.next/server/chunks/_0o1p57f._.js +0 -3
- package/.next/server/chunks/_0t6g4yt._.js +0 -3
- package/.next/server/chunks/_19fidvw._.js +0 -3
- package/.next/server/chunks/_1oqpwh8._.js +0 -3
- package/.next/server/chunks/_1q5w9fc._.js +0 -3
- package/.next/static/chunks/1ad3ir88_e_v6.css +0 -3
- package/.next/static/chunks/29erttsjondpe.js +0 -1
- package/.next/static/chunks/31rxdwy0u_t29.js +0 -1
- package/.next/static/chunks/37g3bsrs22xg7.js +0 -191
- /package/.next/static/{OpwRvHtdhPgxve2rKkWkK → PipzREVX2s4mdvp2gs1DS}/_buildManifest.js +0 -0
- /package/.next/static/{OpwRvHtdhPgxve2rKkWkK → PipzREVX2s4mdvp2gs1DS}/_clientMiddlewareManifest.js +0 -0
- /package/.next/static/{OpwRvHtdhPgxve2rKkWkK → PipzREVX2s4mdvp2gs1DS}/_ssgManifest.js +0 -0
|
@@ -24,7 +24,7 @@ Knowledge Points: ${t.join(", ")}
|
|
|
24
24
|
`;h.box("🎯 Generate Similar Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.normalizeGeneratedQuestion)(r)}catch(e){throw h.box("❌ Error during similar question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(e,t="zh",n,i,s,a){let l=(0,r.generateReanswerPrompt)(t,e,n,{candidateTags:a},s);h.box("🔄 Reanswer Question Request",{provider:"Azure OpenAI",endpoint:this.endpoint,model:this.model,deployment:this.deployment,questionLength:e.length,subject:n||"auto",hasImage:!!i}),h.debug({prompt:l},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t=await (0,u.withTruncationRetry)(t=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:l},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(t)},"Full API response"),!t||!t.choices||0===t.choices.length)throw h.error({response:JSON.stringify(t)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let r=t.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"AI raw response"),!r)throw Error("Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",a=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),d=this.extractTag(r,"wrong_answer_text")||"",p=this.extractTag(r,"mistake_analysis")||"",f=(0,c.normalizeMistakeStatusForSave)(this.extractTag(r,"mistake_status"),d);return h.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:a,wrongAnswerText:d,mistakeAnalysis:p,mistakeStatus:f,subject:(0,o.normalizeSubject)(this.extractTag(r,"subject")),difficultyStars:(0,o.parseDifficultyStars)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"Azure OpenAI",model:this.model,deployment:this.deployment,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"Azure OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.parseMasteryEvaluation)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"Azure OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.parseTagSuggestion)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"Azure OpenAI",deployment:this.deployment,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.withTruncationRetry)(r=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.parseFigure)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"Azure OpenAI",deployment:this.deployment,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.parseLatexFix)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s){let o=(0,r.generateSvgAnimationPrompt)(e,t,i,s);h.info({provider:"Azure OpenAI",deployment:this.deployment,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.withTruncationRetry)(e=>this.client.chat.completions.create({model:this.deployment,messages:[{role:"system",content:o},{role:"user",content:"请为上述题目制作 SVG 动画讲解。"}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.sanitizeSvgAnimation)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"Azure OpenAI error"),e instanceof Error){if(e.message===u.AI_OUTPUT_TRUNCATED||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}])},93963,e=>{"use strict";let t,r,n,i,s;var o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I,C,R,x,k,N,P,U,D,M,j,L,F,G,q,$,B,H,V,J,W,K,z,Y,X,Q,Z,ee,et,er,en,ei,es,eo,ea,el,eu,ec,ed,eh,ep,ef,em,eg,ey,e_,eE,ev,eb,ew,eA,eS,eT,eO,eI,eC,eR,ex,ek,eN,eP,eU,eD,eM,ej,eL,eF,eG,eq,e$,eB,eH,eV,eJ,eW,eK,ez,eY,eX,eQ,eZ,e0,e1,e2,e4,e6,e3,e8,e5,e9,e7,te,tt,tr=e.i(47334),tn=e.i(22734),ti=e.i(24868),ts=e.i(81111),to=e.i(88646);e.i(21365),e.i(96903),e.i(98449),e.i(29485),e.i(16735),e.i(42977);var ta=e.i(35065);e.i(17198),ta.default;var tl=e.i(14747);class tu{}function tc(e,t){return e.replace(/\{([^}]+)\}/g,(e,r)=>{if(Object.prototype.hasOwnProperty.call(t,r)){let e=t[r];return null!=e?String(e):""}throw Error(`Key '${r}' not found in valueMap.`)})}function td(e,t,r){for(let n=0;n<t.length-1;n++){let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))if(Array.isArray(r))e[s]=Array.from({length:r.length},()=>({}));else throw Error(`Value must be a list given an array path ${i}`);if(Array.isArray(e[s])){let i=e[s];if(Array.isArray(r))for(let e=0;e<i.length;e++)td(i[e],t.slice(n+1),r[e]);else for(let e of i)td(e,t.slice(n+1),r)}return}if(i.endsWith("[0]")){let s=i.slice(0,-3);s in e||(e[s]=[{}]),td(e[s][0],t.slice(n+1),r);return}e[i]&&"object"==typeof e[i]||(e[i]={}),e=e[i]}let n=t[t.length-1],i=e[n];if(void 0!==i){if(!r||"object"==typeof r&&0===Object.keys(r).length||r===i)return;if("object"==typeof i&&"object"==typeof r&&null!==i&&null!==r)Object.assign(i,r);else throw Error(`Cannot set value for an existing key. Key: ${n}`)}else"_self"!==n||"object"!=typeof r||null===r||Array.isArray(r)?e[n]=r:Object.assign(e,r)}function th(e,t,r){try{if(1===t.length&&"_self"===t[0])return e;for(let n=0;n<t.length;n++){if("object"!=typeof e||null===e)return r;let i=t[n];if(i.endsWith("[]")){let s=i.slice(0,-2);if(!(s in e))return r;{let i=e[s];if(!Array.isArray(i))return r;return i.map(e=>th(e,t.slice(n+1),r))}}e=e[i]}return e}catch(e){if(e instanceof TypeError)return r;throw e}}function tp(e){if("string"!=typeof e)throw Error("fromImageBytes must be a string");return e}function tf(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["metadata"]);null!=l&&td(o,["metadata"],l);let u=th(e,["done"]);null!=u&&td(o,["done"],u);let c=th(e,["error"]);null!=c&&td(o,["error"],c);let d=th(e,["response"]);return null!=d&&td(o,["response"],(r={},null!=(n=th(t=d,["sdkHttpResponse"]))&&td(r,["sdkHttpResponse"],n),null!=(i=th(t,["parent"]))&&td(r,["parent"],i),null!=(s=th(t,["documentName"]))&&td(r,["documentName"],s),r)),o}(o=eu||(eu={})).OUTCOME_UNSPECIFIED="OUTCOME_UNSPECIFIED",o.OUTCOME_OK="OUTCOME_OK",o.OUTCOME_FAILED="OUTCOME_FAILED",o.OUTCOME_DEADLINE_EXCEEDED="OUTCOME_DEADLINE_EXCEEDED",(a=ec||(ec={})).LANGUAGE_UNSPECIFIED="LANGUAGE_UNSPECIFIED",a.PYTHON="PYTHON",(l=ed||(ed={})).SCHEDULING_UNSPECIFIED="SCHEDULING_UNSPECIFIED",l.SILENT="SILENT",l.WHEN_IDLE="WHEN_IDLE",l.INTERRUPT="INTERRUPT",(u=eh||(eh={})).TYPE_UNSPECIFIED="TYPE_UNSPECIFIED",u.STRING="STRING",u.NUMBER="NUMBER",u.INTEGER="INTEGER",u.BOOLEAN="BOOLEAN",u.ARRAY="ARRAY",u.OBJECT="OBJECT",u.NULL="NULL",(c=ep||(ep={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",c.MODE_DYNAMIC="MODE_DYNAMIC",(d=ef||(ef={})).API_SPEC_UNSPECIFIED="API_SPEC_UNSPECIFIED",d.SIMPLE_SEARCH="SIMPLE_SEARCH",d.ELASTIC_SEARCH="ELASTIC_SEARCH",(h=em||(em={})).AUTH_TYPE_UNSPECIFIED="AUTH_TYPE_UNSPECIFIED",h.NO_AUTH="NO_AUTH",h.API_KEY_AUTH="API_KEY_AUTH",h.HTTP_BASIC_AUTH="HTTP_BASIC_AUTH",h.GOOGLE_SERVICE_ACCOUNT_AUTH="GOOGLE_SERVICE_ACCOUNT_AUTH",h.OAUTH="OAUTH",h.OIDC_AUTH="OIDC_AUTH",(p=eg||(eg={})).HTTP_IN_UNSPECIFIED="HTTP_IN_UNSPECIFIED",p.HTTP_IN_QUERY="HTTP_IN_QUERY",p.HTTP_IN_HEADER="HTTP_IN_HEADER",p.HTTP_IN_PATH="HTTP_IN_PATH",p.HTTP_IN_BODY="HTTP_IN_BODY",p.HTTP_IN_COOKIE="HTTP_IN_COOKIE",(f=ey||(ey={})).PHISH_BLOCK_THRESHOLD_UNSPECIFIED="PHISH_BLOCK_THRESHOLD_UNSPECIFIED",f.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",f.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",f.BLOCK_HIGH_AND_ABOVE="BLOCK_HIGH_AND_ABOVE",f.BLOCK_HIGHER_AND_ABOVE="BLOCK_HIGHER_AND_ABOVE",f.BLOCK_VERY_HIGH_AND_ABOVE="BLOCK_VERY_HIGH_AND_ABOVE",f.BLOCK_ONLY_EXTREMELY_HIGH="BLOCK_ONLY_EXTREMELY_HIGH",(m=e_||(e_={})).THINKING_LEVEL_UNSPECIFIED="THINKING_LEVEL_UNSPECIFIED",m.LOW="LOW",m.MEDIUM="MEDIUM",m.HIGH="HIGH",m.MINIMAL="MINIMAL",(g=eE||(eE={})).HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",g.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",g.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",g.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",g.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",g.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY",g.HARM_CATEGORY_IMAGE_HATE="HARM_CATEGORY_IMAGE_HATE",g.HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT="HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT",g.HARM_CATEGORY_IMAGE_HARASSMENT="HARM_CATEGORY_IMAGE_HARASSMENT",g.HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT="HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT",g.HARM_CATEGORY_JAILBREAK="HARM_CATEGORY_JAILBREAK",(y=ev||(ev={})).HARM_BLOCK_METHOD_UNSPECIFIED="HARM_BLOCK_METHOD_UNSPECIFIED",y.SEVERITY="SEVERITY",y.PROBABILITY="PROBABILITY",(_=eb||(eb={})).HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",_.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",_.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",_.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",_.BLOCK_NONE="BLOCK_NONE",_.OFF="OFF",(E=ew||(ew={})).FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",E.STOP="STOP",E.MAX_TOKENS="MAX_TOKENS",E.SAFETY="SAFETY",E.RECITATION="RECITATION",E.LANGUAGE="LANGUAGE",E.OTHER="OTHER",E.BLOCKLIST="BLOCKLIST",E.PROHIBITED_CONTENT="PROHIBITED_CONTENT",E.SPII="SPII",E.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",E.IMAGE_SAFETY="IMAGE_SAFETY",E.UNEXPECTED_TOOL_CALL="UNEXPECTED_TOOL_CALL",E.IMAGE_PROHIBITED_CONTENT="IMAGE_PROHIBITED_CONTENT",E.NO_IMAGE="NO_IMAGE",E.IMAGE_RECITATION="IMAGE_RECITATION",E.IMAGE_OTHER="IMAGE_OTHER",(v=eA||(eA={})).HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",v.NEGLIGIBLE="NEGLIGIBLE",v.LOW="LOW",v.MEDIUM="MEDIUM",v.HIGH="HIGH",(b=eS||(eS={})).HARM_SEVERITY_UNSPECIFIED="HARM_SEVERITY_UNSPECIFIED",b.HARM_SEVERITY_NEGLIGIBLE="HARM_SEVERITY_NEGLIGIBLE",b.HARM_SEVERITY_LOW="HARM_SEVERITY_LOW",b.HARM_SEVERITY_MEDIUM="HARM_SEVERITY_MEDIUM",b.HARM_SEVERITY_HIGH="HARM_SEVERITY_HIGH",(w=eT||(eT={})).URL_RETRIEVAL_STATUS_UNSPECIFIED="URL_RETRIEVAL_STATUS_UNSPECIFIED",w.URL_RETRIEVAL_STATUS_SUCCESS="URL_RETRIEVAL_STATUS_SUCCESS",w.URL_RETRIEVAL_STATUS_ERROR="URL_RETRIEVAL_STATUS_ERROR",w.URL_RETRIEVAL_STATUS_PAYWALL="URL_RETRIEVAL_STATUS_PAYWALL",w.URL_RETRIEVAL_STATUS_UNSAFE="URL_RETRIEVAL_STATUS_UNSAFE",(A=eO||(eO={})).BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",A.SAFETY="SAFETY",A.OTHER="OTHER",A.BLOCKLIST="BLOCKLIST",A.PROHIBITED_CONTENT="PROHIBITED_CONTENT",A.IMAGE_SAFETY="IMAGE_SAFETY",A.MODEL_ARMOR="MODEL_ARMOR",A.JAILBREAK="JAILBREAK",(S=eI||(eI={})).TRAFFIC_TYPE_UNSPECIFIED="TRAFFIC_TYPE_UNSPECIFIED",S.ON_DEMAND="ON_DEMAND",S.PROVISIONED_THROUGHPUT="PROVISIONED_THROUGHPUT",(T=eC||(eC={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",T.TEXT="TEXT",T.IMAGE="IMAGE",T.AUDIO="AUDIO",(O=eR||(eR={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",O.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",O.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",O.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",(I=ex||(ex={})).TUNING_MODE_UNSPECIFIED="TUNING_MODE_UNSPECIFIED",I.TUNING_MODE_FULL="TUNING_MODE_FULL",I.TUNING_MODE_PEFT_ADAPTER="TUNING_MODE_PEFT_ADAPTER",(C=ek||(ek={})).ADAPTER_SIZE_UNSPECIFIED="ADAPTER_SIZE_UNSPECIFIED",C.ADAPTER_SIZE_ONE="ADAPTER_SIZE_ONE",C.ADAPTER_SIZE_TWO="ADAPTER_SIZE_TWO",C.ADAPTER_SIZE_FOUR="ADAPTER_SIZE_FOUR",C.ADAPTER_SIZE_EIGHT="ADAPTER_SIZE_EIGHT",C.ADAPTER_SIZE_SIXTEEN="ADAPTER_SIZE_SIXTEEN",C.ADAPTER_SIZE_THIRTY_TWO="ADAPTER_SIZE_THIRTY_TWO",(R=eN||(eN={})).JOB_STATE_UNSPECIFIED="JOB_STATE_UNSPECIFIED",R.JOB_STATE_QUEUED="JOB_STATE_QUEUED",R.JOB_STATE_PENDING="JOB_STATE_PENDING",R.JOB_STATE_RUNNING="JOB_STATE_RUNNING",R.JOB_STATE_SUCCEEDED="JOB_STATE_SUCCEEDED",R.JOB_STATE_FAILED="JOB_STATE_FAILED",R.JOB_STATE_CANCELLING="JOB_STATE_CANCELLING",R.JOB_STATE_CANCELLED="JOB_STATE_CANCELLED",R.JOB_STATE_PAUSED="JOB_STATE_PAUSED",R.JOB_STATE_EXPIRED="JOB_STATE_EXPIRED",R.JOB_STATE_UPDATING="JOB_STATE_UPDATING",R.JOB_STATE_PARTIALLY_SUCCEEDED="JOB_STATE_PARTIALLY_SUCCEEDED",(x=eP||(eP={})).TUNING_TASK_UNSPECIFIED="TUNING_TASK_UNSPECIFIED",x.TUNING_TASK_I2V="TUNING_TASK_I2V",x.TUNING_TASK_T2V="TUNING_TASK_T2V",x.TUNING_TASK_R2V="TUNING_TASK_R2V",(k=eU||(eU={})).MEDIA_RESOLUTION_UNSPECIFIED="MEDIA_RESOLUTION_UNSPECIFIED",k.MEDIA_RESOLUTION_LOW="MEDIA_RESOLUTION_LOW",k.MEDIA_RESOLUTION_MEDIUM="MEDIA_RESOLUTION_MEDIUM",k.MEDIA_RESOLUTION_HIGH="MEDIA_RESOLUTION_HIGH",k.MEDIA_RESOLUTION_ULTRA_HIGH="MEDIA_RESOLUTION_ULTRA_HIGH",(N=eD||(eD={})).FEATURE_SELECTION_PREFERENCE_UNSPECIFIED="FEATURE_SELECTION_PREFERENCE_UNSPECIFIED",N.PRIORITIZE_QUALITY="PRIORITIZE_QUALITY",N.BALANCED="BALANCED",N.PRIORITIZE_COST="PRIORITIZE_COST",(P=eM||(eM={})).UNSPECIFIED="UNSPECIFIED",P.BLOCKING="BLOCKING",P.NON_BLOCKING="NON_BLOCKING",(U=ej||(ej={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",U.MODE_DYNAMIC="MODE_DYNAMIC",(D=eL||(eL={})).ENVIRONMENT_UNSPECIFIED="ENVIRONMENT_UNSPECIFIED",D.ENVIRONMENT_BROWSER="ENVIRONMENT_BROWSER",(M=eF||(eF={})).MODE_UNSPECIFIED="MODE_UNSPECIFIED",M.AUTO="AUTO",M.ANY="ANY",M.NONE="NONE",M.VALIDATED="VALIDATED",(j=eG||(eG={})).BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",j.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",j.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",j.BLOCK_NONE="BLOCK_NONE",(L=eq||(eq={})).DONT_ALLOW="DONT_ALLOW",L.ALLOW_ADULT="ALLOW_ADULT",L.ALLOW_ALL="ALLOW_ALL",(F=e$||(e$={})).auto="auto",F.en="en",F.ja="ja",F.ko="ko",F.hi="hi",F.zh="zh",F.pt="pt",F.es="es",(G=eB||(eB={})).MASK_MODE_DEFAULT="MASK_MODE_DEFAULT",G.MASK_MODE_USER_PROVIDED="MASK_MODE_USER_PROVIDED",G.MASK_MODE_BACKGROUND="MASK_MODE_BACKGROUND",G.MASK_MODE_FOREGROUND="MASK_MODE_FOREGROUND",G.MASK_MODE_SEMANTIC="MASK_MODE_SEMANTIC",(q=eH||(eH={})).CONTROL_TYPE_DEFAULT="CONTROL_TYPE_DEFAULT",q.CONTROL_TYPE_CANNY="CONTROL_TYPE_CANNY",q.CONTROL_TYPE_SCRIBBLE="CONTROL_TYPE_SCRIBBLE",q.CONTROL_TYPE_FACE_MESH="CONTROL_TYPE_FACE_MESH",($=eV||(eV={})).SUBJECT_TYPE_DEFAULT="SUBJECT_TYPE_DEFAULT",$.SUBJECT_TYPE_PERSON="SUBJECT_TYPE_PERSON",$.SUBJECT_TYPE_ANIMAL="SUBJECT_TYPE_ANIMAL",$.SUBJECT_TYPE_PRODUCT="SUBJECT_TYPE_PRODUCT",(B=eJ||(eJ={})).EDIT_MODE_DEFAULT="EDIT_MODE_DEFAULT",B.EDIT_MODE_INPAINT_REMOVAL="EDIT_MODE_INPAINT_REMOVAL",B.EDIT_MODE_INPAINT_INSERTION="EDIT_MODE_INPAINT_INSERTION",B.EDIT_MODE_OUTPAINT="EDIT_MODE_OUTPAINT",B.EDIT_MODE_CONTROLLED_EDITING="EDIT_MODE_CONTROLLED_EDITING",B.EDIT_MODE_STYLE="EDIT_MODE_STYLE",B.EDIT_MODE_BGSWAP="EDIT_MODE_BGSWAP",B.EDIT_MODE_PRODUCT_IMAGE="EDIT_MODE_PRODUCT_IMAGE",(H=eW||(eW={})).FOREGROUND="FOREGROUND",H.BACKGROUND="BACKGROUND",H.PROMPT="PROMPT",H.SEMANTIC="SEMANTIC",H.INTERACTIVE="INTERACTIVE",(V=eK||(eK={})).ASSET="ASSET",V.STYLE="STYLE",(J=ez||(ez={})).INSERT="INSERT",J.REMOVE="REMOVE",J.REMOVE_STATIC="REMOVE_STATIC",J.OUTPAINT="OUTPAINT",(W=eY||(eY={})).OPTIMIZED="OPTIMIZED",W.LOSSLESS="LOSSLESS",(K=eX||(eX={})).SUPERVISED_FINE_TUNING="SUPERVISED_FINE_TUNING",K.PREFERENCE_TUNING="PREFERENCE_TUNING",(z=eQ||(eQ={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",z.STATE_PENDING="STATE_PENDING",z.STATE_ACTIVE="STATE_ACTIVE",z.STATE_FAILED="STATE_FAILED",(Y=eZ||(eZ={})).STATE_UNSPECIFIED="STATE_UNSPECIFIED",Y.PROCESSING="PROCESSING",Y.ACTIVE="ACTIVE",Y.FAILED="FAILED",(X=e0||(e0={})).SOURCE_UNSPECIFIED="SOURCE_UNSPECIFIED",X.UPLOADED="UPLOADED",X.GENERATED="GENERATED",(Q=e1||(e1={})).TURN_COMPLETE_REASON_UNSPECIFIED="TURN_COMPLETE_REASON_UNSPECIFIED",Q.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",Q.RESPONSE_REJECTED="RESPONSE_REJECTED",Q.NEED_MORE_INPUT="NEED_MORE_INPUT",(Z=e2||(e2={})).MODALITY_UNSPECIFIED="MODALITY_UNSPECIFIED",Z.TEXT="TEXT",Z.IMAGE="IMAGE",Z.VIDEO="VIDEO",Z.AUDIO="AUDIO",Z.DOCUMENT="DOCUMENT",(ee=e4||(e4={})).VAD_SIGNAL_TYPE_UNSPECIFIED="VAD_SIGNAL_TYPE_UNSPECIFIED",ee.VAD_SIGNAL_TYPE_SOS="VAD_SIGNAL_TYPE_SOS",ee.VAD_SIGNAL_TYPE_EOS="VAD_SIGNAL_TYPE_EOS",(et=e6||(e6={})).START_SENSITIVITY_UNSPECIFIED="START_SENSITIVITY_UNSPECIFIED",et.START_SENSITIVITY_HIGH="START_SENSITIVITY_HIGH",et.START_SENSITIVITY_LOW="START_SENSITIVITY_LOW",(er=e3||(e3={})).END_SENSITIVITY_UNSPECIFIED="END_SENSITIVITY_UNSPECIFIED",er.END_SENSITIVITY_HIGH="END_SENSITIVITY_HIGH",er.END_SENSITIVITY_LOW="END_SENSITIVITY_LOW",(en=e8||(e8={})).ACTIVITY_HANDLING_UNSPECIFIED="ACTIVITY_HANDLING_UNSPECIFIED",en.START_OF_ACTIVITY_INTERRUPTS="START_OF_ACTIVITY_INTERRUPTS",en.NO_INTERRUPTION="NO_INTERRUPTION",(ei=e5||(e5={})).TURN_COVERAGE_UNSPECIFIED="TURN_COVERAGE_UNSPECIFIED",ei.TURN_INCLUDES_ONLY_ACTIVITY="TURN_INCLUDES_ONLY_ACTIVITY",ei.TURN_INCLUDES_ALL_INPUT="TURN_INCLUDES_ALL_INPUT",(es=e9||(e9={})).SCALE_UNSPECIFIED="SCALE_UNSPECIFIED",es.C_MAJOR_A_MINOR="C_MAJOR_A_MINOR",es.D_FLAT_MAJOR_B_FLAT_MINOR="D_FLAT_MAJOR_B_FLAT_MINOR",es.D_MAJOR_B_MINOR="D_MAJOR_B_MINOR",es.E_FLAT_MAJOR_C_MINOR="E_FLAT_MAJOR_C_MINOR",es.E_MAJOR_D_FLAT_MINOR="E_MAJOR_D_FLAT_MINOR",es.F_MAJOR_D_MINOR="F_MAJOR_D_MINOR",es.G_FLAT_MAJOR_E_FLAT_MINOR="G_FLAT_MAJOR_E_FLAT_MINOR",es.G_MAJOR_E_MINOR="G_MAJOR_E_MINOR",es.A_FLAT_MAJOR_F_MINOR="A_FLAT_MAJOR_F_MINOR",es.A_MAJOR_G_FLAT_MINOR="A_MAJOR_G_FLAT_MINOR",es.B_FLAT_MAJOR_G_MINOR="B_FLAT_MAJOR_G_MINOR",es.B_MAJOR_A_FLAT_MINOR="B_MAJOR_A_FLAT_MINOR",(eo=e7||(e7={})).MUSIC_GENERATION_MODE_UNSPECIFIED="MUSIC_GENERATION_MODE_UNSPECIFIED",eo.QUALITY="QUALITY",eo.DIVERSITY="DIVERSITY",eo.VOCALIZATION="VOCALIZATION",(ea=te||(te={})).PLAYBACK_CONTROL_UNSPECIFIED="PLAYBACK_CONTROL_UNSPECIFIED",ea.PLAY="PLAY",ea.PAUSE="PAUSE",ea.STOP="STOP",ea.RESET_CONTEXT="RESET_CONTEXT";class tm{constructor(e){const t={};for(const r of e.headers.entries())t[r[0]]=r[1];this.headers=t,this.responseInternal=e}json(){return this.responseInternal.json()}}class tg{get text(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning text from the first one.");let l="",u=!1,c=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"text"!==t&&"thought"!==t&&"thoughtSignature"!==t&&(null!==r||void 0!==r)&&c.push(t);if("string"==typeof e.text){if("boolean"==typeof e.thought&&e.thought)continue;u=!0,l+=e.text}}return c.length>0&&console.warn(`there are non-text parts ${c} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),u?l:void 0}get data(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning data from the first one.");let l="",u=[];for(let e of null!=(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?a:[]){for(let[t,r]of Object.entries(e))"inlineData"!==t&&(null!==r||void 0!==r)&&u.push(t);e.inlineData&&"string"==typeof e.inlineData.data&&(l+=atob(e.inlineData.data))}return u.length>0&&console.warn(`there are non-data parts ${u} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),l.length>0?btoa(l):void 0}get functionCalls(){var e,t,r,n,i,s,o,a;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning function calls from the first one.");let l=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.functionCall).map(e=>e.functionCall).filter(e=>void 0!==e);if((null==l?void 0:l.length)!==0)return l}get executableCode(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning executable code from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.executableCode).map(e=>e.executableCode).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.code}get codeExecutionResult(){var e,t,r,n,i,s,o,a,l;if((null==(n=null==(r=null==(t=null==(e=this.candidates)?void 0:e[0])?void 0:t.content)?void 0:r.parts)?void 0:n.length)===0)return;this.candidates&&this.candidates.length>1&&console.warn("there are multiple candidates in the response, returning code execution result from the first one.");let u=null==(a=null==(o=null==(s=null==(i=this.candidates)?void 0:i[0])?void 0:s.content)?void 0:o.parts)?void 0:a.filter(e=>e.codeExecutionResult).map(e=>e.codeExecutionResult).filter(e=>void 0!==e);if((null==u?void 0:u.length)!==0)return null==(l=null==u?void 0:u[0])?void 0:l.output}}class ty{}class t_{}class tE{}class tv{}class tb{}class tw{}class tA{}class tS{}class tT{}class tO{}class tI{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r,n=new tI;if(t){let t,n,i,s,o,a;t={},null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),null!=(a=th(e,["response"]))&&td(t,["response"],function(e){let t={},r=th(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["_self"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["gcsUri"]))&&td(i,["uri"],s),null!=(o=th(t,["bytesBase64Encoded"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["mimeType"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}else{let t,n,i,s,o,a;t={},null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),null!=(a=th(e,["response","generateVideoResponse"]))&&td(t,["response"],function(e){let t={},r=th(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["video"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["uri"]))&&td(i,["uri"],s),null!=(o=th(t,["encodedVideo"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["encoding"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(a)),r=t}return Object.assign(n,r),n}}class tC{}class tR{}class tx{}class tk{}class tN{}class tP{}class tU{}class tD{_fromAPIResponse({apiResponse:e,_isVertexAI:t}){var r;let n,i,s,o,a,l,u,c,d,h,p=new tD;return Object.assign(p,(a={},null!=(l=th(e,["name"]))&&td(a,["name"],l),null!=(u=th(e,["metadata"]))&&td(a,["metadata"],u),null!=(c=th(e,["done"]))&&td(a,["done"],c),null!=(d=th(e,["error"]))&&td(a,["error"],d),null!=(h=th(e,["response"]))&&td(a,["response"],(n={},null!=(i=th(r=h,["sdkHttpResponse"]))&&td(n,["sdkHttpResponse"],i),null!=(s=th(r,["parent"]))&&td(n,["parent"],s),null!=(o=th(r,["documentName"]))&&td(n,["documentName"],o),n)),a)),p}}class tM{}class tj{}class tL{}class tF{}class tG{get text(){var e,t,r;let n="",i=!1,s=[];for(let o of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(o))"text"!==e&&"thought"!==e&&null!==t&&s.push(e);if("string"==typeof o.text){if("boolean"==typeof o.thought&&o.thought)continue;i=!0,n+=o.text}}return s.length>0&&console.warn(`there are non-text parts ${s} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`),i?n:void 0}get data(){var e,t,r;let n="",i=[];for(let s of null!=(r=null==(t=null==(e=this.serverContent)?void 0:e.modelTurn)?void 0:t.parts)?r:[]){for(let[e,t]of Object.entries(s))"inlineData"!==e&&null!==t&&i.push(e);s.inlineData&&"string"==typeof s.inlineData.data&&(n+=atob(s.inlineData.data))}return i.length>0&&console.warn(`there are non-data parts ${i} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`),n.length>0?btoa(n):void 0}}class tq{get audioChunk(){if(this.serverContent&&this.serverContent.audioChunks&&this.serverContent.audioChunks.length>0)return this.serverContent.audioChunks[0]}}class t${_fromAPIResponse({apiResponse:e,_isVertexAI:t}){let r=new t$;return Object.assign(r,tf(e)),r}}function tB(e,t){if(!t||"string"!=typeof t)throw Error("model is required and must be a string");if(t.includes("..")||t.includes("?")||t.includes("&"))throw Error("invalid model parameter");if(e.isVertexAI())if(t.startsWith("publishers/")||t.startsWith("projects/")||t.startsWith("models/"))return t;else{if(!(t.indexOf("/")>=0))return`publishers/google/models/${t}`;let e=t.split("/",2);return`publishers/${e[0]}/models/${e[1]}`}return t.startsWith("models/")||t.startsWith("tunedModels/")?t:`models/${t}`}function tH(e,t){let r=tB(e,t);return r?r.startsWith("publishers/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/${r}`:r.startsWith("models/")&&e.isVertexAI()?`projects/${e.getProject()}/locations/${e.getLocation()}/publishers/google/${r}`:r:""}function tV(e){return Array.isArray(e)?e.map(e=>tJ(e)):[tJ(e)]}function tJ(e){if("object"==typeof e&&null!==e)return e;throw Error(`Could not parse input as Blob. Unsupported blob type: ${typeof e}`)}function tW(e){let t=tJ(e);if(t.mimeType&&t.mimeType.startsWith("image/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function tK(e){let t=tJ(e);if(t.mimeType&&t.mimeType.startsWith("audio/"))return t;throw Error(`Unsupported mime type: ${t.mimeType}`)}function tz(e){if(null==e)throw Error("PartUnion is required");if("object"==typeof e)return e;if("string"==typeof e)return{text:e};throw Error(`Unsupported part type: ${typeof e}`)}function tY(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("PartListUnion is required");return Array.isArray(e)?e.map(e=>tz(e)):[tz(e)]}function tX(e){return null!=e&&"object"==typeof e&&"parts"in e&&Array.isArray(e.parts)}function tQ(e){return null!=e&&"object"==typeof e&&"functionCall"in e}function tZ(e){return null!=e&&"object"==typeof e&&"functionResponse"in e}function t0(e){if(null==e)throw Error("ContentUnion is required");return tX(e)?e:{role:"user",parts:tY(e)}}function t1(e,t){if(!t)return[];if(e.isVertexAI()&&Array.isArray(t))return t.flatMap(e=>{let t=t0(e);return t.parts&&t.parts.length>0&&void 0!==t.parts[0].text?[t.parts[0].text]:[]});if(e.isVertexAI()){let e=t0(t);return e.parts&&e.parts.length>0&&void 0!==e.parts[0].text?[e.parts[0].text]:[]}return Array.isArray(t)?t.map(e=>t0(e)):[t0(t)]}function t2(e){if(null==e||Array.isArray(e)&&0===e.length)throw Error("contents are required");if(!Array.isArray(e)){if(tQ(e)||tZ(e))throw Error("To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them");return[t0(e)]}let t=[],r=[],n=tX(e[0]);for(let i of e){let e=tX(i);if(e!=n)throw Error("Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them");if(e)t.push(i);else if(tQ(i)||tZ(i))throw Error("To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them");else r.push(i)}return n||t.push({role:"user",parts:tY(r)}),t}function t4(e){let t={},r=["items"],n=["anyOf"],i=["properties"];if(e.type&&e.anyOf)throw Error("type and anyOf cannot be both populated.");let s=e.anyOf;for(let[o,a]of(null!=s&&2==s.length&&("null"===s[0].type?(t.nullable=!0,e=s[1]):"null"===s[1].type&&(t.nullable=!0,e=s[0])),e.type instanceof Array&&function(e,t){e.includes("null")&&(t.nullable=!0);let r=e.filter(e=>"null"!==e);if(1===r.length)t.type=Object.values(eh).includes(r[0].toUpperCase())?r[0].toUpperCase():eh.TYPE_UNSPECIFIED;else for(let e of(t.anyOf=[],r))t.anyOf.push({type:Object.values(eh).includes(e.toUpperCase())?e.toUpperCase():eh.TYPE_UNSPECIFIED})}(e.type,t),Object.entries(e)))if(null!=a)if("type"==o){if("null"===a)throw Error("type: null can not be the only possible type for the field.");if(a instanceof Array)continue;t.type=Object.values(eh).includes(a.toUpperCase())?a.toUpperCase():eh.TYPE_UNSPECIFIED}else if(r.includes(o))t[o]=t4(a);else if(n.includes(o)){let e=[];for(let r of a){if("null"==r.type){t.nullable=!0;continue}e.push(t4(r))}t[o]=e}else if(i.includes(o)){let e={};for(let[t,r]of Object.entries(a))e[t]=t4(r);t[o]=e}else{if("additionalProperties"===o)continue;t[o]=a}return t}function t6(e){if("object"==typeof e)return e;if("string"==typeof e)return{voiceConfig:{prebuiltVoiceConfig:{voiceName:e}}};throw Error(`Unsupported speechConfig type: ${typeof e}`)}function t3(e){if("multiSpeakerVoiceConfig"in e)throw Error("multiSpeakerVoiceConfig is not supported in the live API.");return e}function t8(e){if(e.functionDeclarations)for(let t of e.functionDeclarations)t.parameters&&(Object.keys(t.parameters).includes("$schema")?t.parametersJsonSchema||(t.parametersJsonSchema=t.parameters,delete t.parameters):t.parameters=t4(t.parameters)),t.response&&(Object.keys(t.response).includes("$schema")?t.responseJsonSchema||(t.responseJsonSchema=t.response,delete t.response):t.response=t4(t.response));return e}function t5(e){if(null==e)throw Error("tools is required");if(!Array.isArray(e))throw Error("tools is required and must be an array of Tools");let t=[];for(let r of e)t.push(r);return t}function t9(e,t){if("string"!=typeof t)throw Error("name must be a string");return function(e,t,r,n=1){let i=!t.startsWith(`${r}/`)&&t.split("/").length===n;if(e.isVertexAI())if(t.startsWith("projects/"))return t;else if(t.startsWith("locations/"))return`projects/${e.getProject()}/${t}`;else if(t.startsWith(`${r}/`))return`projects/${e.getProject()}/locations/${e.getLocation()}/${t}`;else if(i)return`projects/${e.getProject()}/locations/${e.getLocation()}/${r}/${t}`;else return t;return i?`${r}/${t}`:t}(e,t,"cachedContents")}function t7(e){switch(e){case"STATE_UNSPECIFIED":return"JOB_STATE_UNSPECIFIED";case"CREATING":return"JOB_STATE_RUNNING";case"ACTIVE":return"JOB_STATE_SUCCEEDED";case"FAILED":return"JOB_STATE_FAILED";default:return e}}function re(e){return null!=e&&"object"==typeof e&&"video"in e}function rt(e){return null!=e&&"object"==typeof e&&"uri"in e}function rr(e){var t;let r;if(null!=e&&"object"==typeof e&&"name"in e&&(r=e.name),!rt(e)||void 0!==(r=e.uri)){if(!re(e)||void 0!==(r=null==(t=e.video)?void 0:t.uri)){if("string"==typeof e&&(r=e),void 0===r)throw Error("Could not extract file name from the provided input.");if(r.startsWith("https://")){let e=r.split("files/")[1].match(/[a-z0-9]+/);if(null===e)throw Error(`Could not extract file name from URI ${r}`);r=e[0]}else r.startsWith("files/")&&(r=r.split("files/")[1]);return r}}}function rn(e,t){return e.isVertexAI()?t?"publishers/google/models":"models":t?"models":"tunedModels"}function ri(e){for(let n of["models","tunedModels","publisherModels"]){var t,r;if(t=e,r=n,null!==t&&"object"==typeof t&&r in t)return e[n]}return[]}function rs(e,t){let r;if("string"==typeof t)if(e.isVertexAI())if(t.startsWith("gs://"))r={format:"jsonl",gcsUri:[t]};else if(t.startsWith("bq://"))r={format:"bigquery",bigqueryUri:t};else throw Error(`Unsupported string source for Vertex AI: ${t}`);else if(t.startsWith("files/"))r={fileName:t};else throw Error(`Unsupported string source for Gemini API: ${t}`);else if(Array.isArray(t)){if(e.isVertexAI())throw Error("InlinedRequest[] is not supported in Vertex AI.");r={inlinedRequests:t}}else r=t;let n=[r.gcsUri,r.bigqueryUri].filter(Boolean).length,i=[r.inlinedRequests,r.fileName].filter(Boolean).length;if(e.isVertexAI()){if(i>0||1!==n)throw Error("Exactly one of `gcsUri` or `bigqueryUri` must be set for Vertex AI.")}else if(n>0||1!==i)throw Error("Exactly one of `inlinedRequests`, `fileName`, must be set for Gemini API.");return r}function ro(e){if("object"!=typeof e||null===e)return{};let t=e.inlinedResponses;if("object"!=typeof t||null===t)return e;let r=t.inlinedResponses;if(!Array.isArray(r)||0===r.length)return e;let n=!1;for(let e of r){if("object"!=typeof e||null===e)continue;let t=e.response;if("object"==typeof t&&null!==t&&void 0!==t.embedding){n=!0;break}}return n&&(e.inlinedEmbedContentResponses=e.inlinedResponses,delete e.inlinedResponses),e}function ra(e,t){if(!e.isVertexAI()){if(/batches\/[^/]+$/.test(t))return t.split("/").pop();throw Error(`Invalid batch job name: ${t}.`)}if(/^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/.test(t))return t.split("/").pop();if(/^\d+$/.test(t))return t;throw Error(`Invalid batch job name: ${t}.`)}function rl(e){if("BATCH_STATE_UNSPECIFIED"===e)return"JOB_STATE_UNSPECIFIED";if("BATCH_STATE_PENDING"===e)return"JOB_STATE_PENDING";if("BATCH_STATE_RUNNING"===e)return"JOB_STATE_RUNNING";if("BATCH_STATE_SUCCEEDED"===e)return"JOB_STATE_SUCCEEDED";if("BATCH_STATE_FAILED"===e)return"JOB_STATE_FAILED";else if("BATCH_STATE_CANCELLED"===e)return"JOB_STATE_CANCELLED";else if("BATCH_STATE_EXPIRED"===e)return"JOB_STATE_EXPIRED";else return e}function ru(e){let t={},r=th(e,["name"]);null!=r&&td(t,["name"],r);let n=th(e,["metadata","displayName"]);null!=n&&td(t,["displayName"],n);let i=th(e,["metadata","state"]);null!=i&&td(t,["state"],rl(i));let s=th(e,["metadata","createTime"]);null!=s&&td(t,["createTime"],s);let o=th(e,["metadata","endTime"]);null!=o&&td(t,["endTime"],o);let a=th(e,["metadata","updateTime"]);null!=a&&td(t,["updateTime"],a);let l=th(e,["metadata","model"]);null!=l&&td(t,["model"],l);let u=th(e,["metadata","output"]);return null!=u&&td(t,["dest"],function(e){let t={},r=th(e,["responsesFile"]);null!=r&&td(t,["fileName"],r);let n=th(e,["inlinedResponses","inlinedResponses"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["response"]))&&td(r,["response"],function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["content"]);null!=r&&td(t,["content"],r);let n=th(e,["citationMetadata"]);null!=n&&td(t,["citationMetadata"],function(e){let t={},r=th(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["citations"],e)}return t}(n));let i=th(e,["tokenCount"]);null!=i&&td(t,["tokenCount"],i);let s=th(e,["finishReason"]);null!=s&&td(t,["finishReason"],s);let o=th(e,["avgLogprobs"]);null!=o&&td(t,["avgLogprobs"],o);let a=th(e,["groundingMetadata"]);null!=a&&td(t,["groundingMetadata"],a);let l=th(e,["index"]);null!=l&&td(t,["index"],l);let u=th(e,["logprobsResult"]);null!=u&&td(t,["logprobsResult"],u);let c=th(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["safetyRatings"],e)}let d=th(e,["urlContextMetadata"]);return null!=d&&td(t,["urlContextMetadata"],d),t})(e))),td(t,["candidates"],e)}let i=th(e,["modelVersion"]);null!=i&&td(t,["modelVersion"],i);let s=th(e,["promptFeedback"]);null!=s&&td(t,["promptFeedback"],s);let o=th(e,["responseId"]);null!=o&&td(t,["responseId"],o);let a=th(e,["usageMetadata"]);return null!=a&&td(t,["usageMetadata"],a),t}(n)),null!=(i=th(t,["error"]))&&td(r,["error"],i),r})),td(t,["inlinedResponses"],e)}let i=th(e,["inlinedEmbedContentResponses","inlinedResponses"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["inlinedEmbedContentResponses"],e)}return t}(ro(u))),t}function rc(e){var t,r;let n,i,s,o,a,l,u,c,d={},h=th(e,["name"]);null!=h&&td(d,["name"],h);let p=th(e,["displayName"]);null!=p&&td(d,["displayName"],p);let f=th(e,["state"]);null!=f&&td(d,["state"],rl(f));let m=th(e,["error"]);null!=m&&td(d,["error"],m);let g=th(e,["createTime"]);null!=g&&td(d,["createTime"],g);let y=th(e,["startTime"]);null!=y&&td(d,["startTime"],y);let _=th(e,["endTime"]);null!=_&&td(d,["endTime"],_);let E=th(e,["updateTime"]);null!=E&&td(d,["updateTime"],E);let v=th(e,["model"]);null!=v&&td(d,["model"],v);let b=th(e,["inputConfig"]);null!=b&&td(d,["src"],(n={},null!=(i=th(r=b,["instancesFormat"]))&&td(n,["format"],i),null!=(s=th(r,["gcsSource","uris"]))&&td(n,["gcsUri"],s),null!=(o=th(r,["bigquerySource","inputUri"]))&&td(n,["bigqueryUri"],o),n));let w=th(e,["outputConfig"]);null!=w&&td(d,["dest"],(t=ro(w),a={},null!=(l=th(t,["predictionsFormat"]))&&td(a,["format"],l),null!=(u=th(t,["gcsDestination","outputUriPrefix"]))&&td(a,["gcsUri"],u),null!=(c=th(t,["bigqueryDestination","outputUri"]))&&td(a,["bigqueryUri"],c),a));let A=th(e,["completionStats"]);return null!=A&&td(d,["completionStats"],A),d}function rd(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}function rh(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["src"]);null!=i&&td(r,["batch","inputConfig"],function(e,t){let r={};if(void 0!==th(t,["format"]))throw Error("format parameter is not supported in Gemini API.");if(void 0!==th(t,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==th(t,["bigqueryUri"]))throw Error("bigqueryUri parameter is not supported in Gemini API.");let n=th(t,["fileName"]);null!=n&&td(r,["fileName"],n);let i=th(t,["inlinedRequests"]);if(null!=i){let t=i;Array.isArray(t)&&(t=t.map(t=>(function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["request","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rd(e))),td(r,["request","contents"],e)}let s=th(t,["metadata"]);null!=s&&td(r,["metadata"],s);let o=th(t,["config"]);return null!=o&&td(r,["request","generationConfig"],function(e,t,r){var n;let i,s,o,a={},l=th(t,["systemInstruction"]);void 0!==r&&null!=l&&td(r,["systemInstruction"],rd(t0(l)));let u=th(t,["temperature"]);null!=u&&td(a,["temperature"],u);let c=th(t,["topP"]);null!=c&&td(a,["topP"],c);let d=th(t,["topK"]);null!=d&&td(a,["topK"],d);let h=th(t,["candidateCount"]);null!=h&&td(a,["candidateCount"],h);let p=th(t,["maxOutputTokens"]);null!=p&&td(a,["maxOutputTokens"],p);let f=th(t,["stopSequences"]);null!=f&&td(a,["stopSequences"],f);let m=th(t,["responseLogprobs"]);null!=m&&td(a,["responseLogprobs"],m);let g=th(t,["logprobs"]);null!=g&&td(a,["logprobs"],g);let y=th(t,["presencePenalty"]);null!=y&&td(a,["presencePenalty"],y);let _=th(t,["frequencyPenalty"]);null!=_&&td(a,["frequencyPenalty"],_);let E=th(t,["seed"]);null!=E&&td(a,["seed"],E);let v=th(t,["responseMimeType"]);null!=v&&td(a,["responseMimeType"],v);let b=th(t,["responseSchema"]);null!=b&&td(a,["responseSchema"],t4(b));let w=th(t,["responseJsonSchema"]);if(null!=w&&td(a,["responseJsonSchema"],w),void 0!==th(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==th(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let A=th(t,["safetySettings"]);if(void 0!==r&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["category"]);if(null!=r&&td(t,["category"],r),void 0!==th(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=th(e,["threshold"]);return null!=n&&td(t,["threshold"],n),t})(e))),td(r,["safetySettings"],e)}let S=th(t,["tools"]);if(void 0!==r&&null!=S){let e=t5(S);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t8(e)))),td(r,["tools"],e)}let T=th(t,["toolConfig"]);if(void 0!==r&&null!=T&&td(r,["toolConfig"],(i={},null!=(s=th(n=T,["functionCallingConfig"]))&&td(i,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),null!=(o=th(n,["retrievalConfig"]))&&td(i,["retrievalConfig"],o),i)),void 0!==th(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=th(t,["cachedContent"]);void 0!==r&&null!=O&&td(r,["cachedContent"],t9(e,O));let I=th(t,["responseModalities"]);null!=I&&td(a,["responseModalities"],I);let C=th(t,["mediaResolution"]);null!=C&&td(a,["mediaResolution"],C);let R=th(t,["speechConfig"]);if(null!=R&&td(a,["speechConfig"],t6(R)),void 0!==th(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let x=th(t,["thinkingConfig"]);null!=x&&td(a,["thinkingConfig"],x);let k=th(t,["imageConfig"]);null!=k&&td(a,["imageConfig"],function(e){let t={},r=th(e,["aspectRatio"]);null!=r&&td(t,["aspectRatio"],r);let n=th(e,["imageSize"]);if(null!=n&&td(t,["imageSize"],n),void 0!==th(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}(k));let N=th(t,["enableEnhancedCivicAnswers"]);return null!=N&&td(a,["enableEnhancedCivicAnswers"],N),a}(e,o,th(r,["request"],{}))),r})(e,t))),td(r,["requests","requests"],t)}return r}(e,rs(e,i)));let s=th(t,["config"]);return null!=s&&function(e,t){let r=th(e,["displayName"]);if(void 0!==t&&null!=r&&td(t,["batch","displayName"],r),void 0!==th(e,["dest"]))throw Error("dest parameter is not supported in Gemini API.")}(s,r),r}(el=tt||(tt={})).PAGED_ITEM_BATCH_JOBS="batchJobs",el.PAGED_ITEM_MODELS="models",el.PAGED_ITEM_TUNING_JOBS="tuningJobs",el.PAGED_ITEM_FILES="files",el.PAGED_ITEM_CACHED_CONTENTS="cachedContents",el.PAGED_ITEM_FILE_SEARCH_STORES="fileSearchStores",el.PAGED_ITEM_DOCUMENTS="documents";class rp{constructor(e,t,r,n){this.pageInternal=[],this.paramsInternal={},this.requestInternal=t,this.init(e,r,n)}init(e,t,r){var n,i;this.nameInternal=e,this.pageInternal=t[this.nameInternal]||[],this.sdkHttpResponseInternal=null==t?void 0:t.sdkHttpResponse,this.idxInternal=0;let s={config:{}};(s=r&&0!==Object.keys(r).length?"object"==typeof r?Object.assign({},r):r:{config:{}}).config&&(s.config.pageToken=t.nextPageToken),this.paramsInternal=s,this.pageInternalSize=null!=(i=null==(n=s.config)?void 0:n.pageSize)?i:this.pageInternal.length}initNextPage(e){this.init(this.nameInternal,e,this.paramsInternal)}get page(){return this.pageInternal}get name(){return this.nameInternal}get pageSize(){return this.pageInternalSize}get sdkHttpResponse(){return this.sdkHttpResponseInternal}get params(){return this.paramsInternal}get pageLength(){return this.pageInternal.length}getItem(e){return this.pageInternal[e]}[Symbol.asyncIterator](){return{next:async()=>{if(this.idxInternal>=this.pageLength)if(!this.hasNextPage())return{value:void 0,done:!0};else await this.nextPage();let e=this.getItem(this.idxInternal);return this.idxInternal+=1,{value:e,done:!1}},return:async()=>({value:void 0,done:!0})}}async nextPage(){if(!this.hasNextPage())throw Error("No more pages to fetch.");let e=await this.requestInternal(this.params);return this.initNextPage(e),this.page}hasNextPage(){var e;return(null==(e=this.params.config)?void 0:e.pageToken)!==void 0}}class rf extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_BATCH_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.create=async e=>(this.apiClient.isVertexAI()&&(e.config=this.formatDestination(e.src,e.config)),this.createInternal(e)),this.createEmbeddings=async e=>{if(console.warn("batches.createEmbeddings() is experimental and may change without notice."),this.apiClient.isVertexAI())throw Error("Vertex AI does not support batches.createEmbeddings.");return this.createEmbeddingsInternal(e)}}createInlinedGenerateContentRequest(e){let t=rh(this.apiClient,e),r=tc("{model}:batchGenerateContent",t._url),n=t.batch.inputConfig.requests,i=n.requests,s=[];for(let e of i){let t=Object.assign({},e);if(t.systemInstruction){let e=t.systemInstruction;delete t.systemInstruction;let r=t.request;r.systemInstruction=e,t.request=r}s.push(t)}return n.requests=s,delete t.config,delete t._url,delete t._query,{path:r,body:t}}getGcsUri(e){return"string"==typeof e?e.startsWith("gs://")?e:void 0:!Array.isArray(e)&&e.gcsUri&&e.gcsUri.length>0?e.gcsUri[0]:void 0}getBigqueryUri(e){return"string"==typeof e?e.startsWith("bq://")?e:void 0:Array.isArray(e)?void 0:e.bigqueryUri}formatDestination(e,t){let r=t?Object.assign({},t):{},n=Date.now().toString();if(r.displayName||(r.displayName=`genaiBatchJob_${n}`),void 0===r.dest){let t=this.getGcsUri(e),i=this.getBigqueryUri(e);if(t)t.endsWith(".jsonl")?r.dest=`${t.slice(0,-6)}/dest`:r.dest=`${t}_dest_${n}`;else if(i)r.dest=`${i}_dest_${n}`;else throw Error("Unsupported source for Vertex AI: No GCS or BigQuery URI found.")}return r}async createInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let n,i,l,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["model"],tB(s,i)),null!=(l=th(e,["src"]))&&td(n,["inputConfig"],function(e){let t={},r=th(e,["format"]);null!=r&&td(t,["instancesFormat"],r);let n=th(e,["gcsUri"]);null!=n&&td(t,["gcsSource","uris"],n);let i=th(e,["bigqueryUri"]);if(null!=i&&td(t,["bigquerySource","inputUri"],i),void 0!==th(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedRequests"]))throw Error("inlinedRequests parameter is not supported in Vertex AI.");return t}(rs(s,l))),null!=(u=th(e,["config"]))&&(c=th(u,["displayName"]),void 0!==n&&null!=c&&td(n,["displayName"],c),d=th(u,["dest"]),void 0!==n&&null!=d&&td(n,["outputConfig"],function(e){let t={},r=th(e,["format"]);null!=r&&td(t,["predictionsFormat"],r);let n=th(e,["gcsUri"]);null!=n&&td(t,["gcsDestination","outputUriPrefix"],n);let i=th(e,["bigqueryUri"]);if(null!=i&&td(t,["bigqueryDestination","outputUri"],i),void 0!==th(e,["fileName"]))throw Error("fileName parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedResponses"]))throw Error("inlinedResponses parameter is not supported in Vertex AI.");if(void 0!==th(e,["inlinedEmbedContentResponses"]))throw Error("inlinedEmbedContentResponses parameter is not supported in Vertex AI.");return t}(function(e){if("string"!=typeof e)return e;if(e.startsWith("gs://"))return{format:"jsonl",gcsUri:e};if(e.startsWith("bq://"))return{format:"bigquery",bigqueryUri:e};throw Error(`Unsupported destination: ${e}`)}(d)))),n);return o=tc("batchPredictionJobs",h._url),a=h._query,delete h._url,delete h._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(h),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rc(e))}{let t=rh(this.apiClient,e);return o=tc("{model}:batchGenerateContent",t._url),a=t._query,delete t._url,delete t._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async createEmbeddingsInternal(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g=(n=this.apiClient,d={},null!=(h=th(e,["model"]))&&td(d,["_url","model"],tB(n,h)),null!=(p=th(e,["src"]))&&td(d,["batch","inputConfig"],(i=n,l={},null!=(u=th(s=p,["fileName"]))&&td(l,["file_name"],u),null!=(c=th(s,["inlinedRequests"]))&&td(l,["requests"],function(e,t){let r={},n=th(t,["contents"]);if(null!=n){let t=t1(e,n);Array.isArray(t)&&(t=t.map(e=>e)),td(r,["requests[]","request","content"],t)}let i=th(t,["config"]);return null!=i&&(td(r,["_self"],function(e,t){let r=th(e,["taskType"]);void 0!==t&&null!=r&&td(t,["requests[]","taskType"],r);let n=th(e,["title"]);void 0!==t&&null!=n&&td(t,["requests[]","title"],n);let i=th(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&td(t,["requests[]","outputDimensionality"],i),void 0!==th(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.");return{}}(i,r)),!function(e,t){for(let[r,n]of Object.entries(t)){let t=r.split("."),i=n.split("."),s=new Set,o=-1;for(let e=0;e<t.length;e++)if("*"===t[e]){o=e;break}if(-1!==o&&i.length>o)for(let e=o;e<i.length;e++){let t=i[e];"*"===t||t.endsWith("[]")||t.endsWith("[0]")||s.add(t)}!function e(t,r,n,i,s){if(i>=r.length||"object"!=typeof t||null===t)return;let o=r[i];if(o.endsWith("[]")){let a=o.slice(0,-2);if(a in t&&Array.isArray(t[a]))for(let o of t[a])e(o,r,n,i+1,s)}else if("*"===o){if("object"==typeof t&&null!==t&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!e.startsWith("_")&&!s.has(e)),r={};for(let n of e)r[n]=t[n];for(let[e,s]of Object.entries(r)){let r=[];for(let t of n.slice(i))"*"===t?r.push(e):r.push(t);td(t,r,s)}for(let r of e)delete t[r]}}else o in t&&e(t[o],r,n,i+1,s)}(e,t,i,0,s)}}(r,{"requests[].*":"requests[].request.*"})),r}(i,c)),l)),null!=(f=th(e,["config"]))&&(m=th(f,["displayName"]),void 0!==d&&null!=m&&td(d,["batch","displayName"],m)),d);return o=tc("{model}:asyncBatchEmbedContent",g._url),a=g._query,delete g._url,delete g._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(g),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);return a=tc("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rc(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);return a=tc("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>ru(e))}}async cancel(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);a=tc("batchPredictionJobs/{name}:cancel",o._url),l=o._query,delete o._url,delete o._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}else{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);a=tc("batches/{name}:cancel",s._url),l=s._query,delete s._url,delete s._query,await this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal})}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l),u=th(i,["filter"]),void 0!==n&&null!=u&&td(n,["_query","filter"],u)),n);return s=tc("batchPredictionJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["batchPredictionJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>rc(e))),td(t,["batchJobs"],e)}return t}(e),r=new tF;return Object.assign(r,t),r})}{let t,r,a=(t={},null!=(r=th(e,["config"]))&&function(e,t){let r=th(e,["pageSize"]);void 0!==t&&null!=r&&td(t,["_query","pageSize"],r);let n=th(e,["pageToken"]);if(void 0!==t&&null!=n&&td(t,["_query","pageToken"],n),void 0!==th(e,["filter"]))throw Error("filter parameter is not supported in Gemini API.")}(r,t),t);return s=tc("batches",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["operations"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ru(e))),td(t,["batchJobs"],e)}return t}(e),r=new tF;return Object.assign(r,t),r})}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],ra(s,i)),n);return a=tc("batchPredictionJobs/{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),t})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],ra(o,r)),t);return a=tc("batches/{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),t})}}}function rm(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}class rg extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_CACHED_CONTENTS,e=>this.listInternal(e),await this.listInternal(e),e)}async create(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["model"],tH(s,i)),null!=(o=th(e,["config"]))&&function(e,t){let r=th(e,["ttl"]);void 0!==t&&null!=r&&td(t,["ttl"],r);let n=th(e,["expireTime"]);void 0!==t&&null!=n&&td(t,["expireTime"],n);let i=th(e,["displayName"]);void 0!==t&&null!=i&&td(t,["displayName"],i);let s=th(e,["contents"]);if(void 0!==t&&null!=s){let e=t2(s);Array.isArray(e)&&(e=e.map(e=>e)),td(t,["contents"],e)}let o=th(e,["systemInstruction"]);void 0!==t&&null!=o&&td(t,["systemInstruction"],t0(o));let a=th(e,["tools"]);if(void 0!==t&&null!=a){let e=a;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t})(e))),td(t,["tools"],e)}let l=th(e,["toolConfig"]);void 0!==t&&null!=l&&td(t,["toolConfig"],l);let u=th(e,["kmsKeyName"]);void 0!==t&&null!=u&&td(t,["encryption_spec","kmsKeyName"],u)}(o,n),n);return a=tc("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["model"],tH(o,r)),null!=(s=th(e,["config"]))&&function(e,t){var r;let n,i,s,o=th(e,["ttl"]);void 0!==t&&null!=o&&td(t,["ttl"],o);let a=th(e,["expireTime"]);void 0!==t&&null!=a&&td(t,["expireTime"],a);let l=th(e,["displayName"]);void 0!==t&&null!=l&&td(t,["displayName"],l);let u=th(e,["contents"]);if(void 0!==t&&null!=u){let e=t2(u);Array.isArray(e)&&(e=e.map(e=>rm(e))),td(t,["contents"],e)}let c=th(e,["systemInstruction"]);void 0!==t&&null!=c&&td(t,["systemInstruction"],rm(t0(c)));let d=th(e,["tools"]);if(void 0!==t&&null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(e))),td(t,["tools"],e)}let h=th(e,["toolConfig"]);if(void 0!==t&&null!=h&&td(t,["toolConfig"],(n={},null!=(i=th(r=h,["functionCallingConfig"]))&&td(n,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(i)),null!=(s=th(r,["retrievalConfig"]))&&td(n,["retrievalConfig"],s),n)),void 0!==th(e,["kmsKeyName"]))throw Error("kmsKeyName parameter is not supported in Gemini API.")}(s,t),t);return a=tc("cachedContents",u._url),l=u._query,delete u._url,delete u._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tx;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tx;return Object.assign(i,n),i})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d=(s=this.apiClient,n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],t9(s,i)),null!=(o=th(e,["config"]))&&(u=th(o,["ttl"]),void 0!==n&&null!=u&&td(n,["ttl"],u),c=th(o,["expireTime"]),void 0!==n&&null!=c&&td(n,["expireTime"],c)),n);return a=tc("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}{let t,r,s,u,c,d=(o=this.apiClient,t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],t9(o,r)),null!=(s=th(e,["config"]))&&(u=th(s,["ttl"]),void 0!==t&&null!=u&&td(t,["ttl"],u),c=th(s,["expireTime"]),void 0!==t&&null!=c&&td(t,["expireTime"],c)),t);return a=tc("{name}",d._url),l=d._query,delete d._url,delete d._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(d),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>e)}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l)),n);return s=tc("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cachedContents"],e)}return t}(e),r=new tk;return Object.assign(r,t),r})}{let t,r,a,l,u=(t={},null!=(r=th(e,["config"]))&&(a=th(r,["pageSize"]),void 0!==t&&null!=a&&td(t,["_query","pageSize"],a),l=th(r,["pageToken"]),void 0!==t&&null!=l&&td(t,["_query","pageToken"],l)),t);return s=tc("cachedContents",u._url),o=u._query,delete u._url,delete u._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["cachedContents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cachedContents"],e)}return t}(e),r=new tk;return Object.assign(r,t),r})}}}function ry(e,t){var r={};for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&0>t.indexOf(n)&&(r[n]=e[n]);if(null!=e&&"function"==typeof Object.getOwnPropertySymbols)for(var i=0,n=Object.getOwnPropertySymbols(e);i<n.length;i++)0>t.indexOf(n[i])&&Object.prototype.propertyIsEnumerable.call(e,n[i])&&(r[n[i]]=e[n[i]]);return r}function r_(e){return this instanceof r_?(this.v=e,this):new r_(e)}function rE(e,t,r){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var n,i=r.apply(e,t||[]),s=[];return n=Object.create(("function"==typeof AsyncIterator?AsyncIterator:Object).prototype),o("next"),o("throw"),o("return",function(e){return function(t){return Promise.resolve(t).then(e,u)}}),n[Symbol.asyncIterator]=function(){return this},n;function o(e,t){i[e]&&(n[e]=function(t){return new Promise(function(r,n){s.push([e,t,r,n])>1||a(e,t)})},t&&(n[e]=t(n[e])))}function a(e,t){try{var r;(r=i[e](t)).value instanceof r_?Promise.resolve(r.value.v).then(l,u):c(s[0][2],r)}catch(e){c(s[0][3],e)}}function l(e){a("next",e)}function u(e){a("throw",e)}function c(e,t){e(t),s.shift(),s.length&&a(s[0][0],s[0][1])}}function rv(e){if(!Symbol.asyncIterator)throw TypeError("Symbol.asyncIterator is not defined.");var t,r=e[Symbol.asyncIterator];return r?r.call(e):(e=function(e){var t="function"==typeof Symbol&&Symbol.iterator,r=t&&e[t],n=0;if(r)return r.call(e);if(e&&"number"==typeof e.length)return{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}};throw TypeError(t?"Object is not iterable.":"Symbol.iterator is not defined.")}(e),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(r){t[r]=e[r]&&function(t){return new Promise(function(n,i){var s,o,a;s=n,o=i,a=(t=e[r](t)).done,Promise.resolve(t.value).then(function(e){s({value:e,done:a})},o)})}}}function rb(e){if(void 0===e.parts||0===e.parts.length)return!1;for(let t of e.parts)if(void 0===t||0===Object.keys(t).length)return!1;return!0}function rw(e){if(void 0===e||0===e.length)return[];let t=[],r=e.length,n=0;for(;n<r;)if("user"===e[n].role)t.push(e[n]),n++;else{let i=[],s=!0;for(;n<r&&"model"===e[n].role;)i.push(e[n]),s&&!rb(e[n])&&(s=!1),n++;s?t.push(...i):t.pop()}return t}"function"==typeof SuppressedError&&SuppressedError;class rA{constructor(e,t){this.modelsModule=e,this.apiClient=t}create(e){return new rS(this.apiClient,this.modelsModule,e.model,e.config,structuredClone(e.history))}}class rS{constructor(e,t,r,n={},i=[]){this.apiClient=e,this.modelsModule=t,this.model=r,this.config=n,this.history=i,this.sendPromise=Promise.resolve(),function(e){if(0!==e.length){for(let t of e)if("user"!==t.role&&"model"!==t.role)throw Error(`Role must be user or model, but got ${t.role}.`)}}(i)}async sendMessage(e){var t;await this.sendPromise;let r=t0(e.message),n=this.modelsModule.generateContent({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});return this.sendPromise=(async()=>{var e,t,i;let s=await n,o=null==(t=null==(e=s.candidates)?void 0:e[0])?void 0:t.content,a=s.automaticFunctionCallingHistory,l=this.getHistory(!0).length,u=[];null!=a&&(u=null!=(i=a.slice(l))?i:[]),this.recordHistory(r,o?[o]:[],u)})(),await this.sendPromise.catch(()=>{this.sendPromise=Promise.resolve()}),n}async sendMessageStream(e){var t;await this.sendPromise;let r=t0(e.message),n=this.modelsModule.generateContentStream({model:this.model,contents:this.getHistory(!0).concat(r),config:null!=(t=e.config)?t:this.config});this.sendPromise=n.then(()=>void 0).catch(()=>void 0);let i=await n;return this.processStreamResponse(i,r)}getHistory(e=!1){return structuredClone(e?rw(this.history):this.history)}processStreamResponse(e,t){return rE(this,arguments,function*(){let r=[];try{for(var n,i,s,o,a,l,u,c=!0,d=rv(e);!(n=(u=yield r_(d.next())).done);c=!0){if(o=u.value,c=!1,function(e){var t;if(void 0==e.candidates||0===e.candidates.length)return!1;let r=null==(t=e.candidates[0])?void 0:t.content;return void 0!==r&&rb(r)}(o)){let e=null==(l=null==(a=o.candidates)?void 0:a[0])?void 0:l.content;void 0!==e&&r.push(e)}yield yield r_(o)}}catch(e){i={error:e}}finally{try{!c&&!n&&(s=d.return)&&(yield r_(s.call(d)))}finally{if(i)throw i.error}}this.recordHistory(t,r)})}recordHistory(e,t,r){let n=[];t.length>0&&t.every(e=>void 0!==e.role)?n=t:n.push({role:"model",parts:[]}),r&&r.length>0?this.history.push(...rw(r)):this.history.push(e),this.history.push(...n)}}class rT extends Error{constructor(e){super(e.message),this.name="ApiError",this.status=e.status,Object.setPrototypeOf(this,rT.prototype)}}class rO extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_FILES,e=>this.listInternal(e),await this.listInternal(e),e)}async upload(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files. You can share files through a GCS bucket.");return this.apiClient.uploadFile(e.file,e.config).then(e=>e)}async download(e){await this.apiClient.downloadFile(e)}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["pageSize"]),void 0!==s&&null!=a&&td(s,["_query","pageSize"],a),l=th(o,["pageToken"]),void 0!==s&&null!=l&&td(s,["_query","pageToken"],l)),s);return n=tc("files",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["files"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["files"],e)}return t}(e),r=new tM;return Object.assign(r,t),r})}}async createInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["file"]))&&td(s,["file"],o),s);return n=tc("upload/v1beta/files",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tj;return Object.assign(i,n),i})}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","file"],rr(o)),s);return n=tc("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","file"],rr(o)),s);return n=tc("files/{file}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tL;return Object.assign(i,n),i})}}}function rI(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}function rC(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}function rR(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rC(e))),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&td(r,["generationConfig"],function(e,t,r){var n;let i,s,o,a={},l=th(t,["systemInstruction"]);void 0!==r&&null!=l&&td(r,["systemInstruction"],rC(t0(l)));let u=th(t,["temperature"]);null!=u&&td(a,["temperature"],u);let c=th(t,["topP"]);null!=c&&td(a,["topP"],c);let d=th(t,["topK"]);null!=d&&td(a,["topK"],d);let h=th(t,["candidateCount"]);null!=h&&td(a,["candidateCount"],h);let p=th(t,["maxOutputTokens"]);null!=p&&td(a,["maxOutputTokens"],p);let f=th(t,["stopSequences"]);null!=f&&td(a,["stopSequences"],f);let m=th(t,["responseLogprobs"]);null!=m&&td(a,["responseLogprobs"],m);let g=th(t,["logprobs"]);null!=g&&td(a,["logprobs"],g);let y=th(t,["presencePenalty"]);null!=y&&td(a,["presencePenalty"],y);let _=th(t,["frequencyPenalty"]);null!=_&&td(a,["frequencyPenalty"],_);let E=th(t,["seed"]);null!=E&&td(a,["seed"],E);let v=th(t,["responseMimeType"]);null!=v&&td(a,["responseMimeType"],v);let b=th(t,["responseSchema"]);null!=b&&td(a,["responseSchema"],t4(b));let w=th(t,["responseJsonSchema"]);if(null!=w&&td(a,["responseJsonSchema"],w),void 0!==th(t,["routingConfig"]))throw Error("routingConfig parameter is not supported in Gemini API.");if(void 0!==th(t,["modelSelectionConfig"]))throw Error("modelSelectionConfig parameter is not supported in Gemini API.");let A=th(t,["safetySettings"]);if(void 0!==r&&null!=A){let e=A;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["category"]);if(null!=r&&td(t,["category"],r),void 0!==th(e,["method"]))throw Error("method parameter is not supported in Gemini API.");let n=th(e,["threshold"]);return null!=n&&td(t,["threshold"],n),t})(e))),td(r,["safetySettings"],e)}let S=th(t,["tools"]);if(void 0!==r&&null!=S){let e=t5(S);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t8(e)))),td(r,["tools"],e)}let T=th(t,["toolConfig"]);if(void 0!==r&&null!=T&&td(r,["toolConfig"],(i={},null!=(s=th(n=T,["functionCallingConfig"]))&&td(i,["functionCallingConfig"],function(e){let t={},r=th(e,["mode"]);null!=r&&td(t,["mode"],r);let n=th(e,["allowedFunctionNames"]);if(null!=n&&td(t,["allowedFunctionNames"],n),void 0!==th(e,["streamFunctionCallArguments"]))throw Error("streamFunctionCallArguments parameter is not supported in Gemini API.");return t}(s)),null!=(o=th(n,["retrievalConfig"]))&&td(i,["retrievalConfig"],o),i)),void 0!==th(t,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let O=th(t,["cachedContent"]);void 0!==r&&null!=O&&td(r,["cachedContent"],t9(e,O));let I=th(t,["responseModalities"]);null!=I&&td(a,["responseModalities"],I);let C=th(t,["mediaResolution"]);null!=C&&td(a,["mediaResolution"],C);let R=th(t,["speechConfig"]);if(null!=R&&td(a,["speechConfig"],t6(R)),void 0!==th(t,["audioTimestamp"]))throw Error("audioTimestamp parameter is not supported in Gemini API.");let x=th(t,["thinkingConfig"]);null!=x&&td(a,["thinkingConfig"],x);let k=th(t,["imageConfig"]);null!=k&&td(a,["imageConfig"],function(e){let t={},r=th(e,["aspectRatio"]);null!=r&&td(t,["aspectRatio"],r);let n=th(e,["imageSize"]);if(null!=n&&td(t,["imageSize"],n),void 0!==th(e,["outputMimeType"]))throw Error("outputMimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["outputCompressionQuality"]))throw Error("outputCompressionQuality parameter is not supported in Gemini API.");return t}(k));let N=th(t,["enableEnhancedCivicAnswers"]);return null!=N&&td(a,["enableEnhancedCivicAnswers"],N),a}(e,s,r)),r}function rx(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&td(r,["generationConfig"],function(e,t,r){var n;let i,s,o,a,l,u={},c=th(t,["systemInstruction"]);void 0!==r&&null!=c&&td(r,["systemInstruction"],t0(c));let d=th(t,["temperature"]);null!=d&&td(u,["temperature"],d);let h=th(t,["topP"]);null!=h&&td(u,["topP"],h);let p=th(t,["topK"]);null!=p&&td(u,["topK"],p);let f=th(t,["candidateCount"]);null!=f&&td(u,["candidateCount"],f);let m=th(t,["maxOutputTokens"]);null!=m&&td(u,["maxOutputTokens"],m);let g=th(t,["stopSequences"]);null!=g&&td(u,["stopSequences"],g);let y=th(t,["responseLogprobs"]);null!=y&&td(u,["responseLogprobs"],y);let _=th(t,["logprobs"]);null!=_&&td(u,["logprobs"],_);let E=th(t,["presencePenalty"]);null!=E&&td(u,["presencePenalty"],E);let v=th(t,["frequencyPenalty"]);null!=v&&td(u,["frequencyPenalty"],v);let b=th(t,["seed"]);null!=b&&td(u,["seed"],b);let w=th(t,["responseMimeType"]);null!=w&&td(u,["responseMimeType"],w);let A=th(t,["responseSchema"]);null!=A&&td(u,["responseSchema"],t4(A));let S=th(t,["responseJsonSchema"]);null!=S&&td(u,["responseJsonSchema"],S);let T=th(t,["routingConfig"]);null!=T&&td(u,["routingConfig"],T);let O=th(t,["modelSelectionConfig"]);null!=O&&td(u,["modelConfig"],O);let I=th(t,["safetySettings"]);if(void 0!==r&&null!=I){let e=I;Array.isArray(e)&&(e=e.map(e=>e)),td(r,["safetySettings"],e)}let C=th(t,["tools"]);if(void 0!==r&&null!=C){let e=t5(C);Array.isArray(e)&&(e=e.map(e=>rq(t8(e)))),td(r,["tools"],e)}let R=th(t,["toolConfig"]);void 0!==r&&null!=R&&td(r,["toolConfig"],R);let x=th(t,["labels"]);void 0!==r&&null!=x&&td(r,["labels"],x);let k=th(t,["cachedContent"]);void 0!==r&&null!=k&&td(r,["cachedContent"],t9(e,k));let N=th(t,["responseModalities"]);null!=N&&td(u,["responseModalities"],N);let P=th(t,["mediaResolution"]);null!=P&&td(u,["mediaResolution"],P);let U=th(t,["speechConfig"]);null!=U&&td(u,["speechConfig"],t6(U));let D=th(t,["audioTimestamp"]);null!=D&&td(u,["audioTimestamp"],D);let M=th(t,["thinkingConfig"]);null!=M&&td(u,["thinkingConfig"],M);let j=th(t,["imageConfig"]);if(null!=j&&td(u,["imageConfig"],(i={},null!=(s=th(n=j,["aspectRatio"]))&&td(i,["aspectRatio"],s),null!=(o=th(n,["imageSize"]))&&td(i,["imageSize"],o),null!=(a=th(n,["outputMimeType"]))&&td(i,["imageOutputOptions","mimeType"],a),null!=(l=th(n,["outputCompressionQuality"]))&&td(i,["imageOutputOptions","compressionQuality"],l),i)),void 0!==th(t,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return u}(e,s,r)),r}function rk(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["content"]);null!=r&&td(t,["content"],r);let n=th(e,["citationMetadata"]);null!=n&&td(t,["citationMetadata"],function(e){let t={},r=th(e,["citationSources"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["citations"],e)}return t}(n));let i=th(e,["tokenCount"]);null!=i&&td(t,["tokenCount"],i);let s=th(e,["finishReason"]);null!=s&&td(t,["finishReason"],s);let o=th(e,["avgLogprobs"]);null!=o&&td(t,["avgLogprobs"],o);let a=th(e,["groundingMetadata"]);null!=a&&td(t,["groundingMetadata"],a);let l=th(e,["index"]);null!=l&&td(t,["index"],l);let u=th(e,["logprobsResult"]);null!=u&&td(t,["logprobsResult"],u);let c=th(e,["safetyRatings"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["safetyRatings"],e)}let d=th(e,["urlContextMetadata"]);return null!=d&&td(t,["urlContextMetadata"],d),t})(e))),td(t,["candidates"],e)}let i=th(e,["modelVersion"]);null!=i&&td(t,["modelVersion"],i);let s=th(e,["promptFeedback"]);null!=s&&td(t,["promptFeedback"],s);let o=th(e,["responseId"]);null!=o&&td(t,["responseId"],o);let a=th(e,["usageMetadata"]);return null!=a&&td(t,["usageMetadata"],a),t}function rN(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["candidates"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["candidates"],e)}let i=th(e,["createTime"]);null!=i&&td(t,["createTime"],i);let s=th(e,["modelVersion"]);null!=s&&td(t,["modelVersion"],s);let o=th(e,["promptFeedback"]);null!=o&&td(t,["promptFeedback"],o);let a=th(e,["responseId"]);null!=a&&td(t,["responseId"],a);let l=th(e,["usageMetadata"]);return null!=l&&td(t,["usageMetadata"],l),t}function rP(e){let t={},r=th(e,["_self"]);null!=r&&td(t,["image"],rU(r));let n=th(e,["raiFilteredReason"]);null!=n&&td(t,["raiFilteredReason"],n);let i=th(e,["_self"]);null!=i&&td(t,["safetyAttributes"],rG(i));let s=th(e,["prompt"]);return null!=s&&td(t,["enhancedPrompt"],s),t}function rU(e){let t={},r=th(e,["gcsUri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["bytesBase64Encoded"]);null!=n&&td(t,["imageBytes"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rD(e){let t={};if(void 0!==th(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");let r=th(e,["imageBytes"]);null!=r&&td(t,["bytesBase64Encoded"],tp(r));let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}function rM(e){let t={},r=th(e,["gcsUri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["imageBytes"]);null!=n&&td(t,["bytesBase64Encoded"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rj(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["displayName"]);null!=l&&td(o,["displayName"],l);let u=th(e,["description"]);null!=u&&td(o,["description"],u);let c=th(e,["version"]);null!=c&&td(o,["version"],c);let d=th(e,["_self"]);null!=d&&td(o,["tunedModelInfo"],(r={},null!=(n=th(t=d,["baseModel"]))&&td(r,["baseModel"],n),null!=(i=th(t,["createTime"]))&&td(r,["createTime"],i),null!=(s=th(t,["updateTime"]))&&td(r,["updateTime"],s),r));let h=th(e,["inputTokenLimit"]);null!=h&&td(o,["inputTokenLimit"],h);let p=th(e,["outputTokenLimit"]);null!=p&&td(o,["outputTokenLimit"],p);let f=th(e,["supportedGenerationMethods"]);null!=f&&td(o,["supportedActions"],f);let m=th(e,["temperature"]);null!=m&&td(o,["temperature"],m);let g=th(e,["maxTemperature"]);null!=g&&td(o,["maxTemperature"],g);let y=th(e,["topP"]);null!=y&&td(o,["topP"],y);let _=th(e,["topK"]);null!=_&&td(o,["topK"],_);let E=th(e,["thinking"]);return null!=E&&td(o,["thinking"],E),o}function rL(e){var t;let r,n,i,s,o={},a=th(e,["name"]);null!=a&&td(o,["name"],a);let l=th(e,["displayName"]);null!=l&&td(o,["displayName"],l);let u=th(e,["description"]);null!=u&&td(o,["description"],u);let c=th(e,["versionId"]);null!=c&&td(o,["version"],c);let d=th(e,["deployedModels"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>{let t,r,n;return t={},null!=(r=th(e,["endpoint"]))&&td(t,["name"],r),null!=(n=th(e,["deployedModelId"]))&&td(t,["deployedModelId"],n),t})),td(o,["endpoints"],e)}let h=th(e,["labels"]);null!=h&&td(o,["labels"],h);let p=th(e,["_self"]);null!=p&&td(o,["tunedModelInfo"],(r={},null!=(n=th(t=p,["labels","google-vertex-llm-tuning-base-model-id"]))&&td(r,["baseModel"],n),null!=(i=th(t,["createTime"]))&&td(r,["createTime"],i),null!=(s=th(t,["updateTime"]))&&td(r,["updateTime"],s),r));let f=th(e,["defaultCheckpointId"]);null!=f&&td(o,["defaultCheckpointId"],f);let m=th(e,["checkpoints"]);if(null!=m){let e=m;Array.isArray(e)&&(e=e.map(e=>e)),td(o,["checkpoints"],e)}return o}function rF(e){let t={},r=th(e,["safetyAttributes","categories"]);null!=r&&td(t,["categories"],r);let n=th(e,["safetyAttributes","scores"]);null!=n&&td(t,["scores"],n);let i=th(e,["contentType"]);return null!=i&&td(t,["contentType"],i),t}function rG(e){let t={},r=th(e,["safetyAttributes","categories"]);null!=r&&td(t,["categories"],r);let n=th(e,["safetyAttributes","scores"]);null!=n&&td(t,["scores"],n);let i=th(e,["contentType"]);return null!=i&&td(t,["contentType"],i),t}function rq(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t}function r$(e){let t={},r=th(e,["uri"]);null!=r&&td(t,["uri"],r);let n=th(e,["videoBytes"]);null!=n&&td(t,["encodedVideo"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["encoding"],i),t}function rB(e){let t={},r=th(e,["uri"]);null!=r&&td(t,["gcsUri"],r);let n=th(e,["videoBytes"]);null!=n&&td(t,["bytesBase64Encoded"],tp(n));let i=th(e,["mimeType"]);return null!=i&&td(t,["mimeType"],i),t}function rH(e,t){let r=th(e,["mimeType"]);void 0!==t&&null!=r&&td(t,["mimeType"],r);let n=th(e,["displayName"]);void 0!==t&&null!=n&&td(t,["displayName"],n);let i=th(e,["customMetadata"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["customMetadata"],e)}let s=th(e,["chunkingConfig"]);return void 0!==t&&null!=s&&td(t,["chunkingConfig"],s),{}}let rV="x-goog-api-client";class rJ{constructor(e){var t,r;this.clientOptions=Object.assign(Object.assign({},e),{project:e.project,location:e.location,apiKey:e.apiKey,vertexai:e.vertexai});const n={};this.clientOptions.vertexai?(n.apiVersion=null!=(t=this.clientOptions.apiVersion)?t:"v1beta1",n.baseUrl=this.baseUrlFromProjectLocation(),this.normalizeAuthParameters()):(n.apiVersion=null!=(r=this.clientOptions.apiVersion)?r:"v1beta",n.baseUrl="https://generativelanguage.googleapis.com/"),n.headers=this.getDefaultHeaders(),this.clientOptions.httpOptions=n,e.httpOptions&&(this.clientOptions.httpOptions=this.patchHttpOptions(n,e.httpOptions))}baseUrlFromProjectLocation(){return this.clientOptions.project&&this.clientOptions.location&&"global"!==this.clientOptions.location?`https://${this.clientOptions.location}-aiplatform.googleapis.com/`:"https://aiplatform.googleapis.com/"}normalizeAuthParameters(){if(this.clientOptions.project&&this.clientOptions.location){this.clientOptions.apiKey=void 0;return}this.clientOptions.project=void 0,this.clientOptions.location=void 0}isVertexAI(){var e;return null!=(e=this.clientOptions.vertexai)&&e}getProject(){return this.clientOptions.project}getLocation(){return this.clientOptions.location}async getAuthHeaders(){let e=new Headers;return await this.clientOptions.auth.addAuthHeaders(e),e}getApiVersion(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.apiVersion)return this.clientOptions.httpOptions.apiVersion;throw Error("API version is not set.")}getBaseUrl(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.baseUrl)return this.clientOptions.httpOptions.baseUrl;throw Error("Base URL is not set.")}getRequestUrl(){return this.getRequestUrlInternal(this.clientOptions.httpOptions)}getHeaders(){if(this.clientOptions.httpOptions&&void 0!==this.clientOptions.httpOptions.headers)return this.clientOptions.httpOptions.headers;throw Error("Headers are not set.")}getRequestUrlInternal(e){if(!e||void 0===e.baseUrl||void 0===e.apiVersion)throw Error("HTTP options are not correctly set.");let t=[e.baseUrl.endsWith("/")?e.baseUrl.slice(0,-1):e.baseUrl];return e.apiVersion&&""!==e.apiVersion&&t.push(e.apiVersion),t.join("/")}getBaseResourcePath(){return`projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`}getApiKey(){return this.clientOptions.apiKey}getWebsocketBaseUrl(){let e=new URL(this.getBaseUrl());return e.protocol="http:"==e.protocol?"ws":"wss",e.toString()}setBaseUrl(e){if(this.clientOptions.httpOptions)this.clientOptions.httpOptions.baseUrl=e;else throw Error("HTTP options are not correctly set.")}constructUrl(e,t,r){let n=[this.getRequestUrlInternal(t)];return r&&n.push(this.getBaseResourcePath()),""!==e&&n.push(e),new URL(`${n.join("/")}`)}shouldPrependVertexProjectPath(e){return!(this.clientOptions.apiKey||!this.clientOptions.vertexai||e.path.startsWith("projects/")||"GET"===e.httpMethod&&e.path.startsWith("publishers/google/models"))}async request(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e),n=this.constructUrl(e.path,t,r);if(e.queryParams)for(let[t,r]of Object.entries(e.queryParams))n.searchParams.append(t,String(r));let i={};if("GET"===e.httpMethod){if(e.body&&"{}"!==e.body)throw Error("Request body should be empty for GET request, but got non empty request body")}else i.body=e.body;return i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.unaryApiCall(n,i,e.httpMethod)}patchHttpOptions(e,t){let r=JSON.parse(JSON.stringify(e));for(let[e,n]of Object.entries(t))"object"==typeof n?r[e]=Object.assign(Object.assign({},r[e]),n):void 0!==n&&(r[e]=n);return r}async requestStream(e){let t=this.clientOptions.httpOptions;e.httpOptions&&(t=this.patchHttpOptions(this.clientOptions.httpOptions,e.httpOptions));let r=this.shouldPrependVertexProjectPath(e),n=this.constructUrl(e.path,t,r);n.searchParams.has("alt")&&"sse"===n.searchParams.get("alt")||n.searchParams.set("alt","sse");let i={};return i.body=e.body,i=await this.includeExtraHttpOptionsToRequestInit(i,t,n.toString(),e.abortSignal),this.streamApiCall(n,i,e.httpMethod)}async includeExtraHttpOptionsToRequestInit(e,t,r,n){if(t&&t.timeout||n){let r=new AbortController,i=r.signal;if(t.timeout&&(null==t?void 0:t.timeout)>0){let e=setTimeout(()=>r.abort(),t.timeout);e&&"function"==typeof e.unref&&e.unref()}n&&n.addEventListener("abort",()=>{r.abort()}),e.signal=i}return t&&null!==t.extraBody&&function(e,t){if(!t||0===Object.keys(t).length)return;if(e.body instanceof Blob)return console.warn("includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.");let r={};if("string"==typeof e.body&&e.body.length>0)try{let t=JSON.parse(e.body);if("object"!=typeof t||null===t||Array.isArray(t))return void console.warn("includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.");r=t}catch(e){console.warn("includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.");return}e.body=JSON.stringify(function e(t,r){let n=Object.assign({},t);for(let t in r)if(Object.prototype.hasOwnProperty.call(r,t)){let i=r[t],s=n[t];i&&"object"==typeof i&&!Array.isArray(i)&&s&&"object"==typeof s&&!Array.isArray(s)?n[t]=e(s,i):(s&&i&&typeof s!=typeof i&&console.warn(`includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${t}". Original type: ${typeof s}, New type: ${typeof i}. Overwriting.`),n[t]=i)}return n}(r,t))}(e,t.extraBody),e.headers=await this.getHeadersInternal(t,r),e}async unaryApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await rW(e),new tm(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}async streamApiCall(e,t,r){return this.apiCall(e.toString(),Object.assign(Object.assign({},t),{method:r})).then(async e=>(await rW(e),this.processStreamResponse(e))).catch(e=>{if(e instanceof Error)throw e;throw Error(JSON.stringify(e))})}processStreamResponse(e){return rE(this,arguments,function*(){var t;let r=null==(t=null==e?void 0:e.body)?void 0:t.getReader(),n=new TextDecoder("utf-8");if(!r)throw Error("Response body is empty");try{let t="",i="data:",s=["\n\n","\r\r","\r\n\r\n"];for(;;){let{done:o,value:a}=yield r_(r.read());if(o){if(t.trim().length>0)throw Error("Incomplete JSON segment at the end");break}let l=n.decode(a,{stream:!0});try{let e=JSON.parse(l);if("error"in e){let t=JSON.parse(JSON.stringify(e.error)),r=t.status,n=t.code,i=`got status: ${r}. ${JSON.stringify(e)}`;if(n>=400&&n<600)throw new rT({message:i,status:n})}}catch(e){if("ApiError"===e.name)throw e}t+=l;let u=-1,c=0;for(;;){for(let e of(u=-1,c=0,s)){let r=t.indexOf(e);-1!==r&&(-1===u||r<u)&&(u=r,c=e.length)}if(-1===u)break;let r=t.substring(0,u);t=t.substring(u+c);let n=r.trim();if(n.startsWith(i)){let t=n.substring(i.length).trim();try{let r=new Response(t,{headers:null==e?void 0:e.headers,status:null==e?void 0:e.status,statusText:null==e?void 0:e.statusText});yield yield r_(new tm(r))}catch(e){throw Error(`exception parsing stream chunk ${t}. ${e}`)}}}}}finally{r.releaseLock()}})}async apiCall(e,t){return fetch(e,t).catch(e=>{throw Error(`exception ${e} sending request`)})}getDefaultHeaders(){let e={},t="google-genai-sdk/1.34.0 "+this.clientOptions.userAgentExtra;return e["User-Agent"]=t,e[rV]=t,e["Content-Type"]="application/json",e}async getHeadersInternal(e,t){let r=new Headers;if(e&&e.headers){for(let[t,n]of Object.entries(e.headers))r.append(t,n);e.timeout&&e.timeout>0&&r.append("X-Server-Timeout",String(Math.ceil(e.timeout/1e3)))}return await this.clientOptions.auth.addAuthHeaders(r,t),r}getFileName(e){var t;let r="";return"string"==typeof e&&(r=null!=(t=(r=e.replace(/[/\\]+$/,"")).split(/[/\\]/).pop())?t:""),r}async uploadFile(e,t){var r;let n={};null!=t&&(n.mimeType=t.mimeType,n.name=t.name,n.displayName=t.displayName),n.name&&!n.name.startsWith("files/")&&(n.name=`files/${n.name}`);let i=this.clientOptions.uploader,s=await i.stat(e);n.sizeBytes=String(s.size);let o=null!=(r=null==t?void 0:t.mimeType)?r:s.type;if(void 0===o||""===o)throw Error("Can not determine mimeType. Please provide mimeType in the config.");n.mimeType=o;let a={file:n},l=this.getFileName(e),u=tc("upload/v1beta/files",a._url),c=await this.fetchUploadUrl(u,n.sizeBytes,n.mimeType,l,a,null==t?void 0:t.httpOptions);return i.upload(e,c,this)}async uploadFileToFileSearchStore(e,t,r){var n;let i=this.clientOptions.uploader,s=await i.stat(t),o=String(s.size),a=null!=(n=null==r?void 0:r.mimeType)?n:s.type;if(void 0===a||""===a)throw Error("Can not determine mimeType. Please provide mimeType in the config.");let l=`upload/v1beta/${e}:uploadToFileSearchStore`,u=this.getFileName(t),c={};null!=r&&rH(r,c);let d=await this.fetchUploadUrl(l,o,a,u,c,null==r?void 0:r.httpOptions);return i.uploadToFileSearchStore(t,d,this)}async downloadFile(e){let t=this.clientOptions.downloader;await t.download(e,this)}async fetchUploadUrl(e,t,r,n,i,s){var o;let a={};a=s||{apiVersion:"",headers:Object.assign({"Content-Type":"application/json","X-Goog-Upload-Protocol":"resumable","X-Goog-Upload-Command":"start","X-Goog-Upload-Header-Content-Length":`${t}`,"X-Goog-Upload-Header-Content-Type":`${r}`},n?{"X-Goog-Upload-File-Name":n}:{})};let l=await this.request({path:e,body:JSON.stringify(i),httpMethod:"POST",httpOptions:a});if(!l||!(null==l?void 0:l.headers))throw Error("Server did not return an HttpResponse or the returned HttpResponse did not have headers.");let u=null==(o=null==l?void 0:l.headers)?void 0:o["x-goog-upload-url"];if(void 0===u)throw Error("Failed to get upload url. Server did not return the x-google-upload-url in the headers");return u}}async function rW(e){var t;if(void 0===e)throw Error("response is undefined");if(!e.ok){let r=e.status,n=JSON.stringify((null==(t=e.headers.get("content-type"))?void 0:t.includes("application/json"))?await e.json():{error:{message:await e.text(),code:e.status,status:e.statusText}});if(r>=400&&r<600)throw new rT({message:n,status:r});throw Error(n)}}function rK(e){for(let r of e){var t;if(null!==(t=r)&&"object"==typeof t&&t instanceof rY||"object"==typeof r&&"inputSchema"in r)return!0}return!1}function rz(e){var t;let r=null!=(t=e[rV])?t:"";e[rV]=(r+" mcp_used/unknown").trimStart()}class rY{constructor(e=[],t){this.mcpTools=[],this.functionNameToMcpClient={},this.mcpClients=e,this.config=t}static create(e,t){return new rY(e,t)}async initialize(){var e,t,r,n;if(this.mcpTools.length>0)return;let i={},s=[];for(let u of this.mcpClients)try{for(var o,a=!0,l=(t=void 0,rv(function(e){return rE(this,arguments,function*(e,t=100){let r,n=0;for(;n<t;){let t=yield r_(e.listTools({cursor:r}));for(let e of t.tools)yield yield r_(e),n++;if(!t.nextCursor)break;r=t.nextCursor}})}(u)));!(e=(o=await l.next()).done);a=!0){n=o.value,a=!1,s.push(n);let e=n.name;if(i[e])throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);i[e]=u}}catch(e){t={error:e}}finally{try{!a&&!e&&(r=l.return)&&await r.call(l)}finally{if(t)throw t.error}}this.mcpTools=s,this.functionNameToMcpClient=i}async tool(){return await this.initialize(),function(e,t={}){let r=[],n=new Set;for(let i of e){let e=i.name;if(n.has(e))throw Error(`Duplicate function name ${e} found in MCP tools. Please ensure function names are unique.`);n.add(e);let s=function(e,t={}){let r={name:e.name,description:e.description,parametersJsonSchema:e.inputSchema};return e.outputSchema&&(r.responseJsonSchema=e.outputSchema),t.behavior&&(r.behavior=t.behavior),{functionDeclarations:[r]}}(i,t);s.functionDeclarations&&r.push(...s.functionDeclarations)}return{functionDeclarations:r}}(this.mcpTools,this.config)}async callTool(e){await this.initialize();let t=[];for(let r of e)if(r.name in this.functionNameToMcpClient){let e,n=this.functionNameToMcpClient[r.name];this.config.timeout&&(e={timeout:this.config.timeout});let i=await n.callTool({name:r.name,arguments:r.args},void 0,e);t.push({functionResponse:{name:r.name,response:i.isError?{error:i}:i}})}return t}}async function rX(e,t,r){let n=new tq;Object.assign(n,r.data instanceof Blob?JSON.parse(await r.data.text()):JSON.parse(r.data)),t(n)}class rQ{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r}async connect(e){var t,r;let n;if(this.apiClient.isVertexAI())throw Error("Live music is not supported for Vertex AI.");console.warn("Live music generation is experimental and may change in future versions.");let i=this.apiClient.getWebsocketBaseUrl(),s=this.apiClient.getApiVersion(),o=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(this.apiClient.getDefaultHeaders()),a=this.apiClient.getApiKey(),l=`${i}/ws/google.ai.generativelanguage.${s}.GenerativeService.BidiGenerateMusic?key=${a}`,u=()=>{},c=new Promise(e=>{u=e}),d=e.callbacks,h=this.apiClient,p={onopen:function(){u({})},onmessage:e=>{rX(h,d.onmessage,e)},onerror:null!=(t=null==d?void 0:d.onerror)?t:function(e){},onclose:null!=(r=null==d?void 0:d.onclose)?r:function(e){}},f=this.webSocketFactory.create(l,(n={},o.forEach((e,t)=>{n[t]=e}),n),p);f.connect(),await c;let m=tB(this.apiClient,e.model);return f.send(JSON.stringify({setup:{model:m}})),new rZ(f,this.apiClient)}}class rZ{constructor(e,t){this.conn=e,this.apiClient=t}async setWeightedPrompts(e){if(!e.weightedPrompts||0===Object.keys(e.weightedPrompts).length)throw Error("Weighted prompts must be set and contain at least one entry.");let t=function(e){let t={},r=th(e,["weightedPrompts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["weightedPrompts"],e)}return t}(e);this.conn.send(JSON.stringify({clientContent:t}))}async setMusicGenerationConfig(e){let t,r;e.musicGenerationConfig||(e.musicGenerationConfig={});let n=(t={},null!=(r=th(e,["musicGenerationConfig"]))&&td(t,["musicGenerationConfig"],r),t);this.conn.send(JSON.stringify(n))}sendPlaybackControl(e){this.conn.send(JSON.stringify({playbackControl:e}))}play(){this.sendPlaybackControl(te.PLAY)}pause(){this.sendPlaybackControl(te.PAUSE)}stop(){this.sendPlaybackControl(te.STOP)}resetContext(){this.sendPlaybackControl(te.RESET_CONTEXT)}close(){this.conn.close()}}async function r0(e,t,r){let n=new tG,i=JSON.parse(r.data instanceof Blob?await r.data.text():r.data instanceof ArrayBuffer?new TextDecoder().decode(r.data):r.data);if(e.isVertexAI()){let e,t,r,s,o,a,l,u,c;Object.assign(n,(e={},null!=(t=th(i,["setupComplete"]))&&td(e,["setupComplete"],t),null!=(r=th(i,["serverContent"]))&&td(e,["serverContent"],r),null!=(s=th(i,["toolCall"]))&&td(e,["toolCall"],s),null!=(o=th(i,["toolCallCancellation"]))&&td(e,["toolCallCancellation"],o),null!=(a=th(i,["usageMetadata"]))&&td(e,["usageMetadata"],function(e){let t={},r=th(e,["promptTokenCount"]);null!=r&&td(t,["promptTokenCount"],r);let n=th(e,["cachedContentTokenCount"]);null!=n&&td(t,["cachedContentTokenCount"],n);let i=th(e,["candidatesTokenCount"]);null!=i&&td(t,["responseTokenCount"],i);let s=th(e,["toolUsePromptTokenCount"]);null!=s&&td(t,["toolUsePromptTokenCount"],s);let o=th(e,["thoughtsTokenCount"]);null!=o&&td(t,["thoughtsTokenCount"],o);let a=th(e,["totalTokenCount"]);null!=a&&td(t,["totalTokenCount"],a);let l=th(e,["promptTokensDetails"]);if(null!=l){let e=l;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["promptTokensDetails"],e)}let u=th(e,["cacheTokensDetails"]);if(null!=u){let e=u;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["cacheTokensDetails"],e)}let c=th(e,["candidatesTokensDetails"]);if(null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["responseTokensDetails"],e)}let d=th(e,["toolUsePromptTokensDetails"]);if(null!=d){let e=d;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["toolUsePromptTokensDetails"],e)}let h=th(e,["trafficType"]);return null!=h&&td(t,["trafficType"],h),t}(a)),null!=(l=th(i,["goAway"]))&&td(e,["goAway"],l),null!=(u=th(i,["sessionResumptionUpdate"]))&&td(e,["sessionResumptionUpdate"],u),null!=(c=th(i,["voiceActivityDetectionSignal"]))&&td(e,["voiceActivityDetectionSignal"],c),e))}else Object.assign(n,i);t(n)}class r1{constructor(e,t,r){this.apiClient=e,this.auth=t,this.webSocketFactory=r,this.music=new rQ(this.apiClient,this.auth,this.webSocketFactory)}async connect(e){var t,r,n,i,s,o,a,l;let u,c;if(e.config&&e.config.httpOptions)throw Error("The Live module does not support httpOptions at request-level in LiveConnectConfig yet. Please use the client-level httpOptions configuration instead.");let d=this.apiClient.getWebsocketBaseUrl(),h=this.apiClient.getApiVersion(),p=this.apiClient.getHeaders();e.config&&e.config.tools&&rK(e.config.tools)&&rz(p);let f=function(e){let t=new Headers;for(let[r,n]of Object.entries(e))t.append(r,n);return t}(p);if(this.apiClient.isVertexAI())u=`${d}/ws/google.cloud.aiplatform.${h}.LlmBidiService/BidiGenerateContent`,await this.auth.addAuthHeaders(f,u);else{let e=this.apiClient.getApiKey(),t="BidiGenerateContent",r="key";(null==e?void 0:e.startsWith("auth_tokens/"))&&(console.warn("Warning: Ephemeral token support is experimental and may change in future versions."),"v1alpha"!==h&&console.warn("Warning: The SDK's ephemeral token support is in v1alpha only. Please use const ai = new GoogleGenAI({apiKey: token.name, httpOptions: { apiVersion: 'v1alpha' }}); before session connection."),t="BidiGenerateContentConstrained",r="access_token"),u=`${d}/ws/google.ai.generativelanguage.${h}.GenerativeService.${t}?${r}=${e}`}let m=()=>{},g=new Promise(e=>{m=e}),y=e.callbacks,_=this.apiClient,E={onopen:function(){var e;null==(e=null==y?void 0:y.onopen)||e.call(y),m({})},onmessage:e=>{r0(_,y.onmessage,e)},onerror:null!=(t=null==y?void 0:y.onerror)?t:function(e){},onclose:null!=(r=null==y?void 0:y.onclose)?r:function(e){}},v=this.webSocketFactory.create(u,(c={},f.forEach((e,t)=>{c[t]=e}),c),E);v.connect(),await g;let b=tB(this.apiClient,e.model);if(this.apiClient.isVertexAI()&&b.startsWith("publishers/")){let e=this.apiClient.getProject(),t=this.apiClient.getLocation();b=`projects/${e}/locations/${t}/`+b}let w={};this.apiClient.isVertexAI()&&(null==(n=e.config)?void 0:n.responseModalities)===void 0&&(void 0===e.config?e.config={responseModalities:[eC.AUDIO]}:e.config.responseModalities=[eC.AUDIO]),(null==(i=e.config)?void 0:i.generationConfig)&&console.warn("Setting `LiveConnectConfig.generation_config` is deprecated, please set the fields on `LiveConnectConfig` directly. This will become an error in a future version (not before Q3 2025).");let A=null!=(o=null==(s=e.config)?void 0:s.tools)?o:[],S=[];for(let e of A)this.isCallableTool(e)?S.push(await e.tool()):S.push(e);S.length>0&&(e.config.tools=S);let T={model:b,config:e.config,callbacks:e.callbacks};if(this.apiClient.isVertexAI()){let e,t,r;a=this.apiClient,e={},null!=(t=th(T,["model"]))&&td(e,["setup","model"],tB(a,t)),null!=(r=th(T,["config"]))&&td(e,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],function(e){let t={},r=th(e,["modelSelectionConfig"]);null!=r&&td(t,["modelConfig"],r);let n=th(e,["responseJsonSchema"]);null!=n&&td(t,["responseJsonSchema"],n);let i=th(e,["audioTimestamp"]);null!=i&&td(t,["audioTimestamp"],i);let s=th(e,["candidateCount"]);null!=s&&td(t,["candidateCount"],s);let o=th(e,["enableAffectiveDialog"]);null!=o&&td(t,["enableAffectiveDialog"],o);let a=th(e,["frequencyPenalty"]);null!=a&&td(t,["frequencyPenalty"],a);let l=th(e,["logprobs"]);null!=l&&td(t,["logprobs"],l);let u=th(e,["maxOutputTokens"]);null!=u&&td(t,["maxOutputTokens"],u);let c=th(e,["mediaResolution"]);null!=c&&td(t,["mediaResolution"],c);let d=th(e,["presencePenalty"]);null!=d&&td(t,["presencePenalty"],d);let h=th(e,["responseLogprobs"]);null!=h&&td(t,["responseLogprobs"],h);let p=th(e,["responseMimeType"]);null!=p&&td(t,["responseMimeType"],p);let f=th(e,["responseModalities"]);null!=f&&td(t,["responseModalities"],f);let m=th(e,["responseSchema"]);null!=m&&td(t,["responseSchema"],m);let g=th(e,["routingConfig"]);null!=g&&td(t,["routingConfig"],g);let y=th(e,["seed"]);null!=y&&td(t,["seed"],y);let _=th(e,["speechConfig"]);null!=_&&td(t,["speechConfig"],_);let E=th(e,["stopSequences"]);null!=E&&td(t,["stopSequences"],E);let v=th(e,["temperature"]);null!=v&&td(t,["temperature"],v);let b=th(e,["thinkingConfig"]);null!=b&&td(t,["thinkingConfig"],b);let w=th(e,["topK"]);null!=w&&td(t,["topK"],w);let A=th(e,["topP"]);if(null!=A&&td(t,["topP"],A),void 0!==th(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}(r));let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],t0(p));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t5(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={};if(void 0!==th(e,["behavior"]))throw Error("behavior parameter is not supported in Vertex AI.");let r=th(e,["description"]);null!=r&&td(t,["description"],r);let n=th(e,["name"]);null!=n&&td(t,["name"],n);let i=th(e,["parameters"]);null!=i&&td(t,["parameters"],i);let s=th(e,["parametersJsonSchema"]);null!=s&&td(t,["parametersJsonSchema"],s);let o=th(e,["response"]);null!=o&&td(t,["response"],o);let a=th(e,["responseJsonSchema"]);return null!=a&&td(t,["responseJsonSchema"],a),t})(e))),td(t,["functionDeclarations"],e)}let n=th(e,["retrieval"]);null!=n&&td(t,["retrieval"],n);let i=th(e,["googleSearchRetrieval"]);null!=i&&td(t,["googleSearchRetrieval"],i);let s=th(e,["computerUse"]);if(null!=s&&td(t,["computerUse"],s),void 0!==th(e,["fileSearch"]))throw Error("fileSearch parameter is not supported in Vertex AI.");let o=th(e,["codeExecution"]);null!=o&&td(t,["codeExecution"],o);let a=th(e,["enterpriseWebSearch"]);null!=a&&td(t,["enterpriseWebSearch"],a);let l=th(e,["googleMaps"]);null!=l&&td(t,["googleMaps"],l);let u=th(e,["googleSearch"]);null!=u&&td(t,["googleSearch"],u);let c=th(e,["urlContext"]);return null!=c&&td(t,["urlContext"],c),t})(t8(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],m);let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);void 0!==t&&null!=v&&td(t,["setup","proactivity"],v);let b=th(e,["explicitVadSignal"]);return void 0!==t&&null!=b&&td(t,["setup","explicitVadSignal"],b),{}}(r,e)),w=e}else{let e,t,r;l=this.apiClient,e={},null!=(t=th(T,["model"]))&&td(e,["setup","model"],tB(l,t)),null!=(r=th(T,["config"]))&&td(e,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],r);let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],function(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],rI(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}(t0(p)));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t5(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t8(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],function(e){let t={},r=th(e,["handle"]);if(null!=r&&td(t,["handle"],r),void 0!==th(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);if(void 0!==t&&null!=v&&td(t,["setup","proactivity"],v),void 0!==th(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(r,e)),w=e}return delete w.config,v.send(JSON.stringify(w)),new r4(v,this.apiClient)}isCallableTool(e){return"callTool"in e&&"function"==typeof e.callTool}}let r2={turnComplete:!0};class r4{constructor(e,t){this.conn=e,this.apiClient=t}tLiveClientContent(e,t){if(null!==t.turns&&void 0!==t.turns){let r=[];try{r=t2(t.turns),e.isVertexAI()||(r=r.map(e=>rC(e)))}catch(e){throw Error(`Failed to parse client content "turns", type: '${typeof t.turns}'`)}return{clientContent:{turns:r,turnComplete:t.turnComplete}}}return{clientContent:{turnComplete:t.turnComplete}}}tLiveClienttToolResponse(e,t){let r=[];if(null==t.functionResponses||0===(r=Array.isArray(t.functionResponses)?t.functionResponses:[t.functionResponses]).length)throw Error("functionResponses is required.");for(let t of r){if("object"!=typeof t||null===t||!("name"in t)||!("response"in t))throw Error(`Could not parse function response, type '${typeof t}'.`);if(!e.isVertexAI()&&!("id"in t))throw Error("FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.")}return{toolResponse:{functionResponses:r}}}sendClientContent(e){e=Object.assign(Object.assign({},r2),e);let t=this.tLiveClientContent(this.apiClient,e);this.conn.send(JSON.stringify(t))}sendRealtimeInput(e){let t={};t=this.apiClient.isVertexAI()?{realtimeInput:function(e){let t={},r=th(e,["media"]);if(null!=r){let e=tV(r);Array.isArray(e)&&(e=e.map(e=>e)),td(t,["mediaChunks"],e)}let n=th(e,["audio"]);null!=n&&td(t,["audio"],tK(n));let i=th(e,["audioStreamEnd"]);null!=i&&td(t,["audioStreamEnd"],i);let s=th(e,["video"]);null!=s&&td(t,["video"],tW(s));let o=th(e,["text"]);null!=o&&td(t,["text"],o);let a=th(e,["activityStart"]);null!=a&&td(t,["activityStart"],a);let l=th(e,["activityEnd"]);return null!=l&&td(t,["activityEnd"],l),t}(e)}:{realtimeInput:function(e){let t={},r=th(e,["media"]);if(null!=r){let e=tV(r);Array.isArray(e)&&(e=e.map(e=>rI(e))),td(t,["mediaChunks"],e)}let n=th(e,["audio"]);null!=n&&td(t,["audio"],rI(tK(n)));let i=th(e,["audioStreamEnd"]);null!=i&&td(t,["audioStreamEnd"],i);let s=th(e,["video"]);null!=s&&td(t,["video"],rI(tW(s)));let o=th(e,["text"]);null!=o&&td(t,["text"],o);let a=th(e,["activityStart"]);null!=a&&td(t,["activityStart"],a);let l=th(e,["activityEnd"]);return null!=l&&td(t,["activityEnd"],l),t}(e)},this.conn.send(JSON.stringify(t))}sendToolResponse(e){if(null==e.functionResponses)throw Error("Tool response parameters are required.");let t=this.tLiveClienttToolResponse(this.apiClient,e);this.conn.send(JSON.stringify(t))}close(){this.conn.close()}}function r6(e){var t,r,n;if(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.disable)return!0;let i=!1;for(let t of null!=(r=null==e?void 0:e.tools)?r:[])if(r3(t)){i=!0;break}if(!i)return!0;let s=null==(n=null==e?void 0:e.automaticFunctionCalling)?void 0:n.maximumRemoteCalls;return(!(!s||!(s<0)&&Number.isInteger(s))||0==s)&&(console.warn("Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:",s),!0)}function r3(e){return"callTool"in e&&"function"==typeof e.callTool}function r8(e){var t;let r=[];return(null==(t=null==e?void 0:e.config)?void 0:t.tools)&&e.config.tools.forEach((e,t)=>{r3(e)||e.functionDeclarations&&e.functionDeclarations.length>0&&r.push(t)}),r}function r5(e){var t;return!(null==(t=null==e?void 0:e.automaticFunctionCalling)?void 0:t.ignoreCallHistory)}class r9 extends tu{constructor(e){super(),this.apiClient=e,this.generateContent=async e=>{var t,r,n,i,s,o,a,l;let u,c,d=await this.processParamsMaybeAddMcpUsage(e);if(this.maybeMoveToResponseJsonSchem(e),!(null!=(l=null==(a=null==(o=e.config)?void 0:o.tools)?void 0:a.some(e=>r3(e)))&&l)||r6(e.config))return await this.generateContentInternal(d);let h=r8(e);if(h.length>0){let e=h.map(e=>`tools[${e}]`).join(", ");throw Error(`Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations is not yet supported. Incompatible tools found at ${e}.`)}let p=t2(d.contents),f=null!=(n=null==(r=null==(t=d.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,m=0;for(;m<f&&(u=await this.generateContentInternal(d)).functionCalls&&0!==u.functionCalls.length;){let t=u.candidates[0].content,r=[];for(let t of null!=(s=null==(i=e.config)?void 0:i.tools)?s:[])if(r3(t)){let e=await t.callTool(u.functionCalls);r.push(...e)}m++,c={role:"user",parts:r},d.contents=t2(d.contents),d.contents.push(t),d.contents.push(c),r5(d.config)&&(p.push(t),p.push(c))}return r5(d.config)&&(u.automaticFunctionCallingHistory=p),u},this.generateContentStream=async e=>{var t,r,n,i,s;if(this.maybeMoveToResponseJsonSchem(e),r6(e.config)){let t=await this.processParamsMaybeAddMcpUsage(e);return await this.generateContentStreamInternal(t)}let o=r8(e);if(o.length>0){let e=o.map(e=>`tools[${e}]`).join(", ");throw Error(`Incompatible tools found at ${e}. Automatic function calling with CallableTools (or MCP objects) and basic FunctionDeclarations" is not yet supported.`)}let a=null==(n=null==(r=null==(t=null==e?void 0:e.config)?void 0:t.toolConfig)?void 0:r.functionCallingConfig)?void 0:n.streamFunctionCallArguments,l=null==(s=null==(i=null==e?void 0:e.config)?void 0:i.automaticFunctionCalling)?void 0:s.disable;if(a&&!l)throw Error("Running in streaming mode with 'streamFunctionCallArguments' enabled, this feature is not compatible with automatic function calling (AFC). Please set 'config.automaticFunctionCalling.disable' to true to disable AFC or leave 'config.toolConfig.functionCallingConfig.streamFunctionCallArguments' to be undefined or set to false to disable streaming function call arguments feature.");return await this.processAfcStream(e)},this.generateImages=async e=>await this.generateImagesInternal(e).then(e=>{var t;let r,n=[];if(null==e?void 0:e.generatedImages)for(let i of e.generatedImages)i&&(null==i?void 0:i.safetyAttributes)&&(null==(t=null==i?void 0:i.safetyAttributes)?void 0:t.contentType)==="Positive Prompt"?r=null==i?void 0:i.safetyAttributes:n.push(i);return r?{generatedImages:n,positivePromptSafetyAttributes:r,sdkHttpResponse:e.sdkHttpResponse}:{generatedImages:n,sdkHttpResponse:e.sdkHttpResponse}}),this.list=async e=>{var t;let r={config:Object.assign(Object.assign({},{queryBase:!0}),null==e?void 0:e.config)};if(this.apiClient.isVertexAI()&&!r.config.queryBase)if(null==(t=r.config)?void 0:t.filter)throw Error("Filtering tuned models list for Vertex AI is not currently supported");else r.config.filter="labels.tune-type:*";return new rp(tt.PAGED_ITEM_MODELS,e=>this.listInternal(e),await this.listInternal(r),r)},this.editImage=async e=>{let t={model:e.model,prompt:e.prompt,referenceImages:[],config:e.config};return e.referenceImages&&e.referenceImages&&(t.referenceImages=e.referenceImages.map(e=>e.toReferenceImageAPI())),await this.editImageInternal(t)},this.upscaleImage=async e=>{let t={numberOfImages:1,mode:"upscale"};e.config&&(t=Object.assign(Object.assign({},t),e.config));let r={model:e.model,image:e.image,upscaleFactor:e.upscaleFactor,config:t};return await this.upscaleImageInternal(r)},this.generateVideos=async e=>{var t,r,n,i,s,o;if((e.prompt||e.image||e.video)&&e.source)throw Error("Source and prompt/image/video are mutually exclusive. Please only use source.");return!this.apiClient.isVertexAI()&&((null==(t=e.video)?void 0:t.uri)&&(null==(r=e.video)?void 0:r.videoBytes)?e.video={uri:e.video.uri,mimeType:e.video.mimeType}:(null==(i=null==(n=e.source)?void 0:n.video)?void 0:i.uri)&&(null==(o=null==(s=e.source)?void 0:s.video)?void 0:o.videoBytes)&&(e.source.video={uri:e.source.video.uri,mimeType:e.source.video.mimeType})),await this.generateVideosInternal(e)}}maybeMoveToResponseJsonSchem(e){e.config&&e.config.responseSchema&&!e.config.responseJsonSchema&&Object.keys(e.config.responseSchema).includes("$schema")&&(e.config.responseJsonSchema=e.config.responseSchema,delete e.config.responseSchema)}async processParamsMaybeAddMcpUsage(e){var t,r,n;let i=null==(t=e.config)?void 0:t.tools;if(!i)return e;let s=await Promise.all(i.map(async e=>r3(e)?await e.tool():e)),o={model:e.model,contents:e.contents,config:Object.assign(Object.assign({},e.config),{tools:s})};if(o.config.tools=s,e.config&&e.config.tools&&rK(e.config.tools)){let t=Object.assign({},null!=(n=null==(r=e.config.httpOptions)?void 0:r.headers)?n:{});0===Object.keys(t).length&&(t=this.apiClient.getDefaultHeaders()),rz(t),o.config.httpOptions=Object.assign(Object.assign({},e.config.httpOptions),{headers:t})}return o}async initAfcToolsMap(e){var t,r,n;let i=new Map;for(let s of null!=(r=null==(t=e.config)?void 0:t.tools)?r:[])if(r3(s))for(let e of null!=(n=(await s.tool()).functionDeclarations)?n:[]){if(!e.name)throw Error("Function declaration name is required.");if(i.has(e.name))throw Error(`Duplicate tool declaration name: ${e.name}`);i.set(e.name,s)}return i}async processAfcStream(e){var t,r,n;let i=null!=(n=null==(r=null==(t=e.config)?void 0:t.automaticFunctionCalling)?void 0:r.maximumRemoteCalls)?n:10,s=!1,o=0;return function(e,t,r){return rE(this,arguments,function*(){for(;o<i;){s&&(o++,s=!1);let m=yield r_(e.processParamsMaybeAddMcpUsage(r)),g=yield r_(e.generateContentStreamInternal(m)),y=[],_=[];try{for(var n,a,l,u,c,d,h,p=!0,f=(a=void 0,rv(g));!(n=(h=yield r_(f.next())).done);p=!0)if(u=h.value,p=!1,yield yield r_(u),u.candidates&&(null==(c=u.candidates[0])?void 0:c.content)){for(let e of(_.push(u.candidates[0].content),null!=(d=u.candidates[0].content.parts)?d:[]))if(o<i&&e.functionCall){if(!e.functionCall.name)throw Error("Function call name was not returned by the model.");if(t.has(e.functionCall.name)){let r=yield r_(t.get(e.functionCall.name).callTool([e.functionCall]));y.push(...r)}else throw Error(`Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${t.keys()}, mising tool: ${e.functionCall.name}`)}}}catch(e){a={error:e}}finally{try{!p&&!n&&(l=f.return)&&(yield r_(l.call(f)))}finally{if(a)throw a.error}}if(y.length>0){s=!0;let e=new tg;e.candidates=[{content:{role:"user",parts:y}}],yield yield r_(e);let t=[];t.push(..._),t.push({role:"user",parts:y});let n=t2(r.contents).concat(t);r.contents=n}else break}})}(this,await this.initAfcToolsMap(e),e)}async generateContentInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rx(this.apiClient,e);return s=tc("{model}:generateContent",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rN(e),r=new tg;return Object.assign(r,t),r})}{let t=rR(this.apiClient,e);return s=tc("{model}:generateContent",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=rk(e),r=new tg;return Object.assign(r,t),r})}}async generateContentStreamInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=rx(this.apiClient,e);return s=tc("{model}:streamGenerateContent?alt=sse",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(function(e){return rE(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=rv(e);!(t=(s=yield r_(a.next())).done);o=!0){i=s.value,o=!1;let e=rN((yield r_(i.json())));e.sdkHttpResponse={headers:i.headers};let t=new tg;Object.assign(t,e),yield yield r_(t)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield r_(n.call(a)))}finally{if(r)throw r.error}}})})}{let t=rR(this.apiClient,e);return s=tc("{model}:streamGenerateContent?alt=sse",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.requestStream({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(function(e){return rE(this,arguments,function*(){var t,r,n,i;try{for(var s,o=!0,a=rv(e);!(t=(s=yield r_(a.next())).done);o=!0){i=s.value,o=!1;let e=rk((yield r_(i.json())));e.sdkHttpResponse={headers:i.headers};let t=new tg;Object.assign(t,e),yield yield r_(t)}}catch(e){r={error:e}}finally{try{!o&&!t&&(n=a.return)&&(yield r_(n.call(a)))}finally{if(r)throw r.error}}})})}}async embedContent(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=function(e,t){let r,n,i,s,o,a={},l=th(t,["model"]);null!=l&&td(a,["_url","model"],tB(e,l));let u=th(t,["contents"]);if(null!=u){let t=t1(e,u);Array.isArray(t)&&(t=t.map(e=>e)),td(a,["instances[]","content"],t)}let c=th(t,["config"]);return null!=c&&(r=th(c,["taskType"]),void 0!==a&&null!=r&&td(a,["instances[]","task_type"],r),n=th(c,["title"]),void 0!==a&&null!=n&&td(a,["instances[]","title"],n),i=th(c,["outputDimensionality"]),void 0!==a&&null!=i&&td(a,["parameters","outputDimensionality"],i),s=th(c,["mimeType"]),void 0!==a&&null!=s&&td(a,["instances[]","mimeType"],s),o=th(c,["autoTruncate"]),void 0!==a&&null!=o&&td(a,["parameters","autoTruncate"],o)),a}(this.apiClient,e);return s=tc("{model}:predict",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions[]","embeddings"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["values"]))&&td(r,["values"],n),null!=(i=th(e,["statistics"]))&&td(r,["statistics"],(s={},null!=(o=th(t=i,["truncated"]))&&td(s,["truncated"],o),null!=(a=th(t,["token_count"]))&&td(s,["tokenCount"],a),s)),r})),td(t,["embeddings"],e)}let i=th(e,["metadata"]);return null!=i&&td(t,["metadata"],i),t}(e),r=new ty;return Object.assign(r,t),r})}{let t=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let t=t1(e,i);Array.isArray(t)&&(t=t.map(e=>e)),td(r,["requests[]","content"],t)}let s=th(t,["config"]);null!=s&&function(e,t){let r=th(e,["taskType"]);void 0!==t&&null!=r&&td(t,["requests[]","taskType"],r);let n=th(e,["title"]);void 0!==t&&null!=n&&td(t,["requests[]","title"],n);let i=th(e,["outputDimensionality"]);if(void 0!==t&&null!=i&&td(t,["requests[]","outputDimensionality"],i),void 0!==th(e,["mimeType"]))throw Error("mimeType parameter is not supported in Gemini API.");if(void 0!==th(e,["autoTruncate"]))throw Error("autoTruncate parameter is not supported in Gemini API.")}(s,r);let o=th(t,["model"]);return void 0!==o&&td(r,["requests[]","model"],tB(e,o)),r}(this.apiClient,e);return s=tc("{model}:batchEmbedContents",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["embeddings"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["embeddings"],e)}let i=th(e,["metadata"]);return null!=i&&td(t,["metadata"],i),t}(e),r=new ty;return Object.assign(r,t),r})}}async generateImagesInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A,S,T,O,I=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","model"],tB(s,i)),null!=(o=th(e,["prompt"]))&&td(n,["instances[0]","prompt"],o),null!=(u=th(e,["config"]))&&(c=th(u,["outputGcsUri"]),void 0!==n&&null!=c&&td(n,["parameters","storageUri"],c),d=th(u,["negativePrompt"]),void 0!==n&&null!=d&&td(n,["parameters","negativePrompt"],d),h=th(u,["numberOfImages"]),void 0!==n&&null!=h&&td(n,["parameters","sampleCount"],h),p=th(u,["aspectRatio"]),void 0!==n&&null!=p&&td(n,["parameters","aspectRatio"],p),f=th(u,["guidanceScale"]),void 0!==n&&null!=f&&td(n,["parameters","guidanceScale"],f),m=th(u,["seed"]),void 0!==n&&null!=m&&td(n,["parameters","seed"],m),g=th(u,["safetyFilterLevel"]),void 0!==n&&null!=g&&td(n,["parameters","safetySetting"],g),y=th(u,["personGeneration"]),void 0!==n&&null!=y&&td(n,["parameters","personGeneration"],y),_=th(u,["includeSafetyAttributes"]),void 0!==n&&null!=_&&td(n,["parameters","includeSafetyAttributes"],_),E=th(u,["includeRaiReason"]),void 0!==n&&null!=E&&td(n,["parameters","includeRaiReason"],E),v=th(u,["language"]),void 0!==n&&null!=v&&td(n,["parameters","language"],v),b=th(u,["outputMimeType"]),void 0!==n&&null!=b&&td(n,["parameters","outputOptions","mimeType"],b),w=th(u,["outputCompressionQuality"]),void 0!==n&&null!=w&&td(n,["parameters","outputOptions","compressionQuality"],w),A=th(u,["addWatermark"]),void 0!==n&&null!=A&&td(n,["parameters","addWatermark"],A),S=th(u,["labels"]),void 0!==n&&null!=S&&td(n,["labels"],S),T=th(u,["imageSize"]),void 0!==n&&null!=T&&td(n,["parameters","sampleImageSize"],T),O=th(u,["enhancePrompt"]),void 0!==n&&null!=O&&td(n,["parameters","enhancePrompt"],O)),n);return a=tc("{model}:predict",I._url),l=I._query,delete I._url,delete I._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(I),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}let i=th(e,["positivePromptSafetyAttributes"]);return null!=i&&td(t,["positivePromptSafetyAttributes"],rG(i)),t}(e),r=new t_;return Object.assign(r,t),r})}{let t,r,s,u,c=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","model"],tB(o,r)),null!=(s=th(e,["prompt"]))&&td(t,["instances[0]","prompt"],s),null!=(u=th(e,["config"]))&&function(e,t){if(void 0!==th(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["negativePrompt"]))throw Error("negativePrompt parameter is not supported in Gemini API.");let r=th(e,["numberOfImages"]);void 0!==t&&null!=r&&td(t,["parameters","sampleCount"],r);let n=th(e,["aspectRatio"]);void 0!==t&&null!=n&&td(t,["parameters","aspectRatio"],n);let i=th(e,["guidanceScale"]);if(void 0!==t&&null!=i&&td(t,["parameters","guidanceScale"],i),void 0!==th(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let s=th(e,["safetyFilterLevel"]);void 0!==t&&null!=s&&td(t,["parameters","safetySetting"],s);let o=th(e,["personGeneration"]);void 0!==t&&null!=o&&td(t,["parameters","personGeneration"],o);let a=th(e,["includeSafetyAttributes"]);void 0!==t&&null!=a&&td(t,["parameters","includeSafetyAttributes"],a);let l=th(e,["includeRaiReason"]);void 0!==t&&null!=l&&td(t,["parameters","includeRaiReason"],l);let u=th(e,["language"]);void 0!==t&&null!=u&&td(t,["parameters","language"],u);let c=th(e,["outputMimeType"]);void 0!==t&&null!=c&&td(t,["parameters","outputOptions","mimeType"],c);let d=th(e,["outputCompressionQuality"]);if(void 0!==t&&null!=d&&td(t,["parameters","outputOptions","compressionQuality"],d),void 0!==th(e,["addWatermark"]))throw Error("addWatermark parameter is not supported in Gemini API.");if(void 0!==th(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");let h=th(e,["imageSize"]);if(void 0!==t&&null!=h&&td(t,["parameters","sampleImageSize"],h),void 0!==th(e,["enhancePrompt"]))throw Error("enhancePrompt parameter is not supported in Gemini API.")}(u,t),t);return a=tc("{model}:predict",c._url),l=c._query,delete c._url,delete c._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>{var t,r;let n,i,s,o,a,l,u;return n={},null!=(i=th(t=e,["_self"]))&&td(n,["image"],(s={},null!=(o=th(r=i,["bytesBase64Encoded"]))&&td(s,["imageBytes"],tp(o)),null!=(a=th(r,["mimeType"]))&&td(s,["mimeType"],a),s)),null!=(l=th(t,["raiFilteredReason"]))&&td(n,["raiFilteredReason"],l),null!=(u=th(t,["_self"]))&&td(n,["safetyAttributes"],rF(u)),n})),td(t,["generatedImages"],e)}let i=th(e,["positivePromptSafetyAttributes"]);return null!=i&&td(t,["positivePromptSafetyAttributes"],rF(i)),t}(e),r=new t_;return Object.assign(r,t),r})}}async editImageInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r,n,i,s,o,a,l,u,c,d,h,p,f,m,g,y,_,E={},v=th(t,["model"]);null!=v&&td(E,["_url","model"],tB(e,v));let b=th(t,["prompt"]);null!=b&&td(E,["instances[0]","prompt"],b);let w=th(t,["referenceImages"]);if(null!=w){let e=w;Array.isArray(e)&&(e=e.map(e=>(function(e){let t,r,n,i,s,o,a,l={},u=th(e,["referenceImage"]);null!=u&&td(l,["referenceImage"],rM(u));let c=th(e,["referenceId"]);null!=c&&td(l,["referenceId"],c);let d=th(e,["referenceType"]);null!=d&&td(l,["referenceType"],d);let h=th(e,["maskImageConfig"]);null!=h&&td(l,["maskImageConfig"],(t={},null!=(r=th(h,["maskMode"]))&&td(t,["maskMode"],r),null!=(n=th(h,["segmentationClasses"]))&&td(t,["maskClasses"],n),null!=(i=th(h,["maskDilation"]))&&td(t,["dilation"],i),t));let p=th(e,["controlImageConfig"]);null!=p&&td(l,["controlImageConfig"],(s={},null!=(o=th(p,["controlType"]))&&td(s,["controlType"],o),null!=(a=th(p,["enableControlImageComputation"]))&&td(s,["computeControl"],a),s));let f=th(e,["styleImageConfig"]);null!=f&&td(l,["styleImageConfig"],f);let m=th(e,["subjectImageConfig"]);return null!=m&&td(l,["subjectImageConfig"],m),l})(e))),td(E,["instances[0]","referenceImages"],e)}let A=th(t,["config"]);return null!=A&&(r=th(A,["outputGcsUri"]),void 0!==E&&null!=r&&td(E,["parameters","storageUri"],r),n=th(A,["negativePrompt"]),void 0!==E&&null!=n&&td(E,["parameters","negativePrompt"],n),i=th(A,["numberOfImages"]),void 0!==E&&null!=i&&td(E,["parameters","sampleCount"],i),s=th(A,["aspectRatio"]),void 0!==E&&null!=s&&td(E,["parameters","aspectRatio"],s),o=th(A,["guidanceScale"]),void 0!==E&&null!=o&&td(E,["parameters","guidanceScale"],o),a=th(A,["seed"]),void 0!==E&&null!=a&&td(E,["parameters","seed"],a),l=th(A,["safetyFilterLevel"]),void 0!==E&&null!=l&&td(E,["parameters","safetySetting"],l),u=th(A,["personGeneration"]),void 0!==E&&null!=u&&td(E,["parameters","personGeneration"],u),c=th(A,["includeSafetyAttributes"]),void 0!==E&&null!=c&&td(E,["parameters","includeSafetyAttributes"],c),d=th(A,["includeRaiReason"]),void 0!==E&&null!=d&&td(E,["parameters","includeRaiReason"],d),h=th(A,["language"]),void 0!==E&&null!=h&&td(E,["parameters","language"],h),p=th(A,["outputMimeType"]),void 0!==E&&null!=p&&td(E,["parameters","outputOptions","mimeType"],p),f=th(A,["outputCompressionQuality"]),void 0!==E&&null!=f&&td(E,["parameters","outputOptions","compressionQuality"],f),m=th(A,["addWatermark"]),void 0!==E&&null!=m&&td(E,["parameters","addWatermark"],m),g=th(A,["labels"]),void 0!==E&&null!=g&&td(E,["labels"],g),y=th(A,["editMode"]),void 0!==E&&null!=y&&td(E,["parameters","editMode"],y),_=th(A,["baseSteps"]),void 0!==E&&null!=_&&td(E,["parameters","editConfig","baseSteps"],_)),E}(this.apiClient,e);return n=tc("{model}:predict",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tE;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async upscaleImageInternal(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b,w=(n=this.apiClient,o={},null!=(a=th(e,["model"]))&&td(o,["_url","model"],tB(n,a)),null!=(l=th(e,["image"]))&&td(o,["instances[0]","image"],rM(l)),null!=(u=th(e,["upscaleFactor"]))&&td(o,["parameters","upscaleConfig","upscaleFactor"],u),null!=(c=th(e,["config"]))&&(d=th(c,["outputGcsUri"]),void 0!==o&&null!=d&&td(o,["parameters","storageUri"],d),h=th(c,["safetyFilterLevel"]),void 0!==o&&null!=h&&td(o,["parameters","safetySetting"],h),p=th(c,["personGeneration"]),void 0!==o&&null!=p&&td(o,["parameters","personGeneration"],p),f=th(c,["includeRaiReason"]),void 0!==o&&null!=f&&td(o,["parameters","includeRaiReason"],f),m=th(c,["outputMimeType"]),void 0!==o&&null!=m&&td(o,["parameters","outputOptions","mimeType"],m),g=th(c,["outputCompressionQuality"]),void 0!==o&&null!=g&&td(o,["parameters","outputOptions","compressionQuality"],g),y=th(c,["enhanceInputImage"]),void 0!==o&&null!=y&&td(o,["parameters","upscaleConfig","enhanceInputImage"],y),_=th(c,["imagePreservationFactor"]),void 0!==o&&null!=_&&td(o,["parameters","upscaleConfig","imagePreservationFactor"],_),E=th(c,["labels"]),void 0!==o&&null!=E&&td(o,["labels"],E),v=th(c,["numberOfImages"]),void 0!==o&&null!=v&&td(o,["parameters","sampleCount"],v),b=th(c,["mode"]),void 0!==o&&null!=b&&td(o,["parameters","mode"],b)),o);return i=tc("{model}:predict",w._url),s=w._query,delete w._url,delete w._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(w),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["predictions"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tv;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async recontextImage(e){var t,r,n;let i="",s={};if(this.apiClient.isVertexAI()){let o,a,l,u,c,d,h,p,f,m,g,y,_,E,v,b=(n=this.apiClient,o={},null!=(a=th(e,["model"]))&&td(o,["_url","model"],tB(n,a)),null!=(l=th(e,["source"]))&&function(e,t){let r=th(e,["prompt"]);void 0!==t&&null!=r&&td(t,["instances[0]","prompt"],r);let n=th(e,["personImage"]);void 0!==t&&null!=n&&td(t,["instances[0]","personImage","image"],rM(n));let i=th(e,["productImages"]);if(void 0!==t&&null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>{let t,r;return t={},null!=(r=th(e,["productImage"]))&&td(t,["image"],rM(r)),t})),td(t,["instances[0]","productImages"],e)}}(l,o),null!=(u=th(e,["config"]))&&(c=th(u,["numberOfImages"]),void 0!==o&&null!=c&&td(o,["parameters","sampleCount"],c),d=th(u,["baseSteps"]),void 0!==o&&null!=d&&td(o,["parameters","baseSteps"],d),h=th(u,["outputGcsUri"]),void 0!==o&&null!=h&&td(o,["parameters","storageUri"],h),p=th(u,["seed"]),void 0!==o&&null!=p&&td(o,["parameters","seed"],p),f=th(u,["safetyFilterLevel"]),void 0!==o&&null!=f&&td(o,["parameters","safetySetting"],f),m=th(u,["personGeneration"]),void 0!==o&&null!=m&&td(o,["parameters","personGeneration"],m),g=th(u,["addWatermark"]),void 0!==o&&null!=g&&td(o,["parameters","addWatermark"],g),y=th(u,["outputMimeType"]),void 0!==o&&null!=y&&td(o,["parameters","outputOptions","mimeType"],y),_=th(u,["outputCompressionQuality"]),void 0!==o&&null!=_&&td(o,["parameters","outputOptions","compressionQuality"],_),E=th(u,["enhancePrompt"]),void 0!==o&&null!=E&&td(o,["parameters","enhancePrompt"],E),v=th(u,["labels"]),void 0!==o&&null!=v&&td(o,["labels"],v)),o);return i=tc("{model}:predict",b._url),s=b._query,delete b._url,delete b._query,this.apiClient.request({path:i,queryParams:s,body:JSON.stringify(b),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>rP(e))),td(t,["generatedImages"],e)}return t}(e),r=new tb;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async segmentImage(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI()){let l,u,c,d,h,p,f,m,g,y,_,E,v,b,w,A=(n=this.apiClient,p={},null!=(f=th(e,["model"]))&&td(p,["_url","model"],tB(n,f)),null!=(m=th(e,["source"]))&&(i=m,s=p,c=th(i,["prompt"]),void 0!==s&&null!=c&&td(s,["instances[0]","prompt"],c),d=th(i,["image"]),void 0!==s&&null!=d&&td(s,["instances[0]","image"],rM(d)),h=th(i,["scribbleImage"]),void 0!==s&&null!=h&&td(s,["instances[0]","scribble"],(l={},null!=(u=th(h,["image"]))&&td(l,["image"],rM(u)),l))),null!=(g=th(e,["config"]))&&(y=th(g,["mode"]),void 0!==p&&null!=y&&td(p,["parameters","mode"],y),_=th(g,["maxPredictions"]),void 0!==p&&null!=_&&td(p,["parameters","maxPredictions"],_),E=th(g,["confidenceThreshold"]),void 0!==p&&null!=E&&td(p,["parameters","confidenceThreshold"],E),v=th(g,["maskDilation"]),void 0!==p&&null!=v&&td(p,["parameters","maskDilation"],v),b=th(g,["binaryColorThreshold"]),void 0!==p&&null!=b&&td(p,["parameters","binaryColorThreshold"],b),w=th(g,["labels"]),void 0!==p&&null!=w&&td(p,["labels"],w)),p);return o=tc("{model}:predict",A._url),a=A._query,delete A._url,delete A._query,this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(A),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["predictions"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["_self"]);null!=r&&td(t,["mask"],rU(r));let n=th(e,["labels"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["labels"],e)}return t})(e))),td(t,["generatedMasks"],e)}return t}(e),r=new tw;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async get(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","name"],tB(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rL(e))}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rj(e))}}async listInternal(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["config"]))&&(o=th(i,["pageSize"]),void 0!==n&&null!=o&&td(n,["_query","pageSize"],o),u=th(i,["pageToken"]),void 0!==n&&null!=u&&td(n,["_query","pageToken"],u),c=th(i,["filter"]),void 0!==n&&null!=c&&td(n,["_query","filter"],c),d=th(i,["queryBase"]),void 0!==n&&null!=d&&td(n,["_url","models_url"],rn(s,d))),n);return a=tc("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["_self"]);if(null!=i){let e=ri(i);Array.isArray(e)&&(e=e.map(e=>rL(e))),td(t,["models"],e)}return t}(e),r=new tA;return Object.assign(r,t),r})}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=th(e,["config"]))&&(s=th(r,["pageSize"]),void 0!==t&&null!=s&&td(t,["_query","pageSize"],s),u=th(r,["pageToken"]),void 0!==t&&null!=u&&td(t,["_query","pageToken"],u),c=th(r,["filter"]),void 0!==t&&null!=c&&td(t,["_query","filter"],c),d=th(r,["queryBase"]),void 0!==t&&null!=d&&td(t,["_url","models_url"],rn(o,d))),t);return a=tc("{models_url}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["_self"]);if(null!=i){let e=ri(i);Array.isArray(e)&&(e=e.map(e=>rj(e))),td(t,["models"],e)}return t}(e),r=new tA;return Object.assign(r,t),r})}}async update(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,d,h=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","model"],tB(s,i)),null!=(o=th(e,["config"]))&&(u=th(o,["displayName"]),void 0!==n&&null!=u&&td(n,["displayName"],u),c=th(o,["description"]),void 0!==n&&null!=c&&td(n,["description"],c),d=th(o,["defaultCheckpointId"]),void 0!==n&&null!=d&&td(n,["defaultCheckpointId"],d)),n);return a=tc("{model}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>rL(e))}{let t,r,s,u,c,d,h=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),null!=(s=th(e,["config"]))&&(u=th(s,["displayName"]),void 0!==t&&null!=u&&td(t,["displayName"],u),c=th(s,["description"]),void 0!==t&&null!=c&&td(t,["description"],c),d=th(s,["defaultCheckpointId"]),void 0!==t&&null!=d&&td(t,["defaultCheckpointId"],d)),t);return a=tc("{name}",h._url),l=h._query,delete h._url,delete h._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(h),httpMethod:"PATCH",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>rj(e))}}async delete(e){var t,r,n,i,s,o;let a="",l={};if(this.apiClient.isVertexAI()){let n,i,o=(s=this.apiClient,n={},null!=(i=th(e,["model"]))&&td(n,["_url","name"],tB(s,i)),n);return a=tc("{name}",o._url),l=o._query,delete o._url,delete o._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(o),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tS;return Object.assign(i,n),i})}{let t,r,s=(o=this.apiClient,t={},null!=(r=th(e,["model"]))&&td(t,["_url","name"],tB(o,r)),t);return a=tc("{name}",s._url),l=s._query,delete s._url,delete s._query,this.apiClient.request({path:a,queryParams:l,body:JSON.stringify(s),httpMethod:"DELETE",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tS;return Object.assign(i,n),i})}}async countTokens(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&function(e,t){let r=th(e,["systemInstruction"]);void 0!==t&&null!=r&&td(t,["systemInstruction"],t0(r));let n=th(e,["tools"]);if(void 0!==t&&null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>rq(e))),td(t,["tools"],e)}let i=th(e,["generationConfig"]);void 0!==t&&null!=i&&td(t,["generationConfig"],function(e){let t={},r=th(e,["modelSelectionConfig"]);null!=r&&td(t,["modelConfig"],r);let n=th(e,["responseJsonSchema"]);null!=n&&td(t,["responseJsonSchema"],n);let i=th(e,["audioTimestamp"]);null!=i&&td(t,["audioTimestamp"],i);let s=th(e,["candidateCount"]);null!=s&&td(t,["candidateCount"],s);let o=th(e,["enableAffectiveDialog"]);null!=o&&td(t,["enableAffectiveDialog"],o);let a=th(e,["frequencyPenalty"]);null!=a&&td(t,["frequencyPenalty"],a);let l=th(e,["logprobs"]);null!=l&&td(t,["logprobs"],l);let u=th(e,["maxOutputTokens"]);null!=u&&td(t,["maxOutputTokens"],u);let c=th(e,["mediaResolution"]);null!=c&&td(t,["mediaResolution"],c);let d=th(e,["presencePenalty"]);null!=d&&td(t,["presencePenalty"],d);let h=th(e,["responseLogprobs"]);null!=h&&td(t,["responseLogprobs"],h);let p=th(e,["responseMimeType"]);null!=p&&td(t,["responseMimeType"],p);let f=th(e,["responseModalities"]);null!=f&&td(t,["responseModalities"],f);let m=th(e,["responseSchema"]);null!=m&&td(t,["responseSchema"],m);let g=th(e,["routingConfig"]);null!=g&&td(t,["routingConfig"],g);let y=th(e,["seed"]);null!=y&&td(t,["seed"],y);let _=th(e,["speechConfig"]);null!=_&&td(t,["speechConfig"],_);let E=th(e,["stopSequences"]);null!=E&&td(t,["stopSequences"],E);let v=th(e,["temperature"]);null!=v&&td(t,["temperature"],v);let b=th(e,["thinkingConfig"]);null!=b&&td(t,["thinkingConfig"],b);let w=th(e,["topK"]);null!=w&&td(t,["topK"],w);let A=th(e,["topP"]);if(null!=A&&td(t,["topP"],A),void 0!==th(e,["enableEnhancedCivicAnswers"]))throw Error("enableEnhancedCivicAnswers parameter is not supported in Vertex AI.");return t}(i))}(s,r),r}(this.apiClient,e);return s=tc("{model}:countTokens",n._url),o=n._query,delete n._url,delete n._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(n),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["totalTokens"]))&&td(t,["totalTokens"],n),t),s=new tT;return Object.assign(s,i),s})}{let t=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>rC(e))),td(r,["contents"],e)}let s=th(t,["config"]);return null!=s&&function(e){if(void 0!==th(e,["systemInstruction"]))throw Error("systemInstruction parameter is not supported in Gemini API.");if(void 0!==th(e,["tools"]))throw Error("tools parameter is not supported in Gemini API.");if(void 0!==th(e,["generationConfig"]))throw Error("generationConfig parameter is not supported in Gemini API.")}(s),r}(this.apiClient,e);return s=tc("{model}:countTokens",t._url),o=t._query,delete t._url,delete t._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(t),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["totalTokens"]))&&td(t,["totalTokens"],n),null!=(i=th(e,["cachedContentTokenCount"]))&&td(t,["cachedContentTokenCount"],i),t),o=new tT;return Object.assign(o,s),o})}}async computeTokens(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s=function(e,t){let r={},n=th(t,["model"]);null!=n&&td(r,["_url","model"],tB(e,n));let i=th(t,["contents"]);if(null!=i){let e=t2(i);Array.isArray(e)&&(e=e.map(e=>e)),td(r,["contents"],e)}return r}(this.apiClient,e);return n=tc("{model}:computeTokens",s._url),i=s._query,delete s._url,delete s._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(s),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["tokensInfo"]);if(null!=n){let e=n;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["tokensInfo"],e)}return t}(e),r=new tO;return Object.assign(r,t),r})}throw Error("This method is only supported by the Vertex AI.")}async generateVideosInternal(e){var t,r,n,i,s,o,a,l,u,c;let d="",h={};if(this.apiClient.isVertexAI()){let n,i,o,u,c,p,f,m,g,y,_=(s=this.apiClient,u={},null!=(c=th(e,["model"]))&&td(u,["_url","model"],tB(s,c)),null!=(p=th(e,["prompt"]))&&td(u,["instances[0]","prompt"],p),null!=(f=th(e,["image"]))&&td(u,["instances[0]","image"],rM(f)),null!=(m=th(e,["video"]))&&td(u,["instances[0]","video"],rB(m)),null!=(g=th(e,["source"]))&&(a=g,l=u,n=th(a,["prompt"]),void 0!==l&&null!=n&&td(l,["instances[0]","prompt"],n),i=th(a,["image"]),void 0!==l&&null!=i&&td(l,["instances[0]","image"],rM(i)),o=th(a,["video"]),void 0!==l&&null!=o&&td(l,["instances[0]","video"],rB(o))),null!=(y=th(e,["config"]))&&function(e,t){var r;let n,i,s,o=th(e,["numberOfVideos"]);void 0!==t&&null!=o&&td(t,["parameters","sampleCount"],o);let a=th(e,["outputGcsUri"]);void 0!==t&&null!=a&&td(t,["parameters","storageUri"],a);let l=th(e,["fps"]);void 0!==t&&null!=l&&td(t,["parameters","fps"],l);let u=th(e,["durationSeconds"]);void 0!==t&&null!=u&&td(t,["parameters","durationSeconds"],u);let c=th(e,["seed"]);void 0!==t&&null!=c&&td(t,["parameters","seed"],c);let d=th(e,["aspectRatio"]);void 0!==t&&null!=d&&td(t,["parameters","aspectRatio"],d);let h=th(e,["resolution"]);void 0!==t&&null!=h&&td(t,["parameters","resolution"],h);let p=th(e,["personGeneration"]);void 0!==t&&null!=p&&td(t,["parameters","personGeneration"],p);let f=th(e,["pubsubTopic"]);void 0!==t&&null!=f&&td(t,["parameters","pubsubTopic"],f);let m=th(e,["negativePrompt"]);void 0!==t&&null!=m&&td(t,["parameters","negativePrompt"],m);let g=th(e,["enhancePrompt"]);void 0!==t&&null!=g&&td(t,["parameters","enhancePrompt"],g);let y=th(e,["generateAudio"]);void 0!==t&&null!=y&&td(t,["parameters","generateAudio"],y);let _=th(e,["lastFrame"]);void 0!==t&&null!=_&&td(t,["instances[0]","lastFrame"],rM(_));let E=th(e,["referenceImages"]);if(void 0!==t&&null!=E){let e=E;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["image"]))&&td(r,["image"],rM(n)),null!=(i=th(t,["referenceType"]))&&td(r,["referenceType"],i),r})),td(t,["instances[0]","referenceImages"],e)}let v=th(e,["mask"]);void 0!==t&&null!=v&&td(t,["instances[0]","mask"],(n={},null!=(i=th(r=v,["image"]))&&td(n,["_self"],rM(i)),null!=(s=th(r,["maskMode"]))&&td(n,["maskMode"],s),n));let b=th(e,["compressionQuality"]);void 0!==t&&null!=b&&td(t,["parameters","compressionQuality"],b)}(y,u),u);return d=tc("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=th(e,["name"]))&&td(t,["name"],r),null!=(n=th(e,["metadata"]))&&td(t,["metadata"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),null!=(o=th(e,["response"]))&&td(t,["response"],function(e){let t={},r=th(e,["videos"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["_self"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["gcsUri"]))&&td(i,["uri"],s),null!=(o=th(t,["bytesBase64Encoded"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["mimeType"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tI;return Object.assign(l,a),l})}{let t,r,s,a,l,p,f,m,g,y,_=(o=this.apiClient,a={},null!=(l=th(e,["model"]))&&td(a,["_url","model"],tB(o,l)),null!=(p=th(e,["prompt"]))&&td(a,["instances[0]","prompt"],p),null!=(f=th(e,["image"]))&&td(a,["instances[0]","image"],rD(f)),null!=(m=th(e,["video"]))&&td(a,["instances[0]","video"],r$(m)),null!=(g=th(e,["source"]))&&(u=g,c=a,t=th(u,["prompt"]),void 0!==c&&null!=t&&td(c,["instances[0]","prompt"],t),r=th(u,["image"]),void 0!==c&&null!=r&&td(c,["instances[0]","image"],rD(r)),s=th(u,["video"]),void 0!==c&&null!=s&&td(c,["instances[0]","video"],r$(s))),null!=(y=th(e,["config"]))&&function(e,t){let r=th(e,["numberOfVideos"]);if(void 0!==t&&null!=r&&td(t,["parameters","sampleCount"],r),void 0!==th(e,["outputGcsUri"]))throw Error("outputGcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["fps"]))throw Error("fps parameter is not supported in Gemini API.");let n=th(e,["durationSeconds"]);if(void 0!==t&&null!=n&&td(t,["parameters","durationSeconds"],n),void 0!==th(e,["seed"]))throw Error("seed parameter is not supported in Gemini API.");let i=th(e,["aspectRatio"]);void 0!==t&&null!=i&&td(t,["parameters","aspectRatio"],i);let s=th(e,["resolution"]);void 0!==t&&null!=s&&td(t,["parameters","resolution"],s);let o=th(e,["personGeneration"]);if(void 0!==t&&null!=o&&td(t,["parameters","personGeneration"],o),void 0!==th(e,["pubsubTopic"]))throw Error("pubsubTopic parameter is not supported in Gemini API.");let a=th(e,["negativePrompt"]);void 0!==t&&null!=a&&td(t,["parameters","negativePrompt"],a);let l=th(e,["enhancePrompt"]);if(void 0!==t&&null!=l&&td(t,["parameters","enhancePrompt"],l),void 0!==th(e,["generateAudio"]))throw Error("generateAudio parameter is not supported in Gemini API.");let u=th(e,["lastFrame"]);void 0!==t&&null!=u&&td(t,["instances[0]","lastFrame"],rD(u));let c=th(e,["referenceImages"]);if(void 0!==t&&null!=c){let e=c;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i;return r={},null!=(n=th(t=e,["image"]))&&td(r,["image"],rD(n)),null!=(i=th(t,["referenceType"]))&&td(r,["referenceType"],i),r})),td(t,["instances[0]","referenceImages"],e)}if(void 0!==th(e,["mask"]))throw Error("mask parameter is not supported in Gemini API.");if(void 0!==th(e,["compressionQuality"]))throw Error("compressionQuality parameter is not supported in Gemini API.")}(y,a),a);return d=tc("{model}:predictLongRunning",_._url),h=_._query,delete _._url,delete _._query,this.apiClient.request({path:d,queryParams:h,body:JSON.stringify(_),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n,i,s,o,a=(t={},null!=(r=th(e,["name"]))&&td(t,["name"],r),null!=(n=th(e,["metadata"]))&&td(t,["metadata"],n),null!=(i=th(e,["done"]))&&td(t,["done"],i),null!=(s=th(e,["error"]))&&td(t,["error"],s),null!=(o=th(e,["response","generateVideoResponse"]))&&td(t,["response"],function(e){let t={},r=th(e,["generatedSamples"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a;return r={},null!=(n=th(e,["video"]))&&td(r,["video"],(i={},null!=(s=th(t=n,["uri"]))&&td(i,["uri"],s),null!=(o=th(t,["encodedVideo"]))&&td(i,["videoBytes"],tp(o)),null!=(a=th(t,["encoding"]))&&td(i,["mimeType"],a),i)),r})),td(t,["generatedVideos"],e)}let n=th(e,["raiMediaFilteredCount"]);null!=n&&td(t,["raiMediaFilteredCount"],n);let i=th(e,["raiMediaFilteredReasons"]);return null!=i&&td(t,["raiMediaFilteredReasons"],i),t}(o)),t),l=new tI;return Object.assign(l,a),l})}}}class r7 extends tu{constructor(e){super(),this.apiClient=e}async getVideosOperation(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async get(e){let t=e.operation,r=e.config;if(void 0===t.name||""===t.name)throw Error("Operation name is required.");if(this.apiClient.isVertexAI()){let e,n=t.name.split("/operations/")[0];r&&"httpOptions"in r&&(e=r.httpOptions);let i=await this.fetchPredictVideosOperationInternal({operationName:t.name,resourceName:n,config:{httpOptions:e}});return t._fromAPIResponse({apiResponse:i,_isVertexAI:!0})}{let e=await this.getVideosOperationInternal({operationName:t.name,config:r});return t._fromAPIResponse({apiResponse:e,_isVertexAI:!1})}}async getVideosOperationInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["operationName"]))&&td(n,["_url","operationName"],i),n);return s=tc("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}{let t,r,a=(t={},null!=(r=th(e,["operationName"]))&&td(t,["_url","operationName"],r),t);return s=tc("{operationName}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json())}}async fetchPredictVideosOperationInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l=(s={},null!=(o=th(e,["operationName"]))&&td(s,["operationName"],o),null!=(a=th(e,["resourceName"]))&&td(s,["_url","resourceName"],a),s);return n=tc("{resourceName}:fetchPredictOperation",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json())}throw Error("This method is only supported by the Vertex AI.")}}class ne extends tu{constructor(e){super(),this.apiClient=e}async create(e){var t,r,n,i,s;let o="",a={};if(this.apiClient.isVertexAI())throw Error("The client.tokens.create method is only supported by the Gemini Developer API.");{let l,u,c,d,h,p,f,m,g,y,_=(n=this.apiClient,d={},null!=(h=th(e,["config"]))&&td(d,["config"],(p=th(h,["expireTime"]),void 0!==d&&null!=p&&td(d,["expireTime"],p),f=th(h,["newSessionExpireTime"]),void 0!==d&&null!=f&&td(d,["newSessionExpireTime"],f),m=th(h,["uses"]),void 0!==d&&null!=m&&td(d,["uses"],m),g=th(h,["liveConnectConstraints"]),void 0!==d&&null!=g&&td(d,["bidiGenerateContentSetup"],(i=n,l={},null!=(u=th(s=g,["model"]))&&td(l,["setup","model"],tB(i,u)),null!=(c=th(s,["config"]))&&td(l,["config"],function(e,t){let r=th(e,["generationConfig"]);void 0!==t&&null!=r&&td(t,["setup","generationConfig"],r);let n=th(e,["responseModalities"]);void 0!==t&&null!=n&&td(t,["setup","generationConfig","responseModalities"],n);let i=th(e,["temperature"]);void 0!==t&&null!=i&&td(t,["setup","generationConfig","temperature"],i);let s=th(e,["topP"]);void 0!==t&&null!=s&&td(t,["setup","generationConfig","topP"],s);let o=th(e,["topK"]);void 0!==t&&null!=o&&td(t,["setup","generationConfig","topK"],o);let a=th(e,["maxOutputTokens"]);void 0!==t&&null!=a&&td(t,["setup","generationConfig","maxOutputTokens"],a);let l=th(e,["mediaResolution"]);void 0!==t&&null!=l&&td(t,["setup","generationConfig","mediaResolution"],l);let u=th(e,["seed"]);void 0!==t&&null!=u&&td(t,["setup","generationConfig","seed"],u);let c=th(e,["speechConfig"]);void 0!==t&&null!=c&&td(t,["setup","generationConfig","speechConfig"],t3(c));let d=th(e,["thinkingConfig"]);void 0!==t&&null!=d&&td(t,["setup","generationConfig","thinkingConfig"],d);let h=th(e,["enableAffectiveDialog"]);void 0!==t&&null!=h&&td(t,["setup","generationConfig","enableAffectiveDialog"],h);let p=th(e,["systemInstruction"]);void 0!==t&&null!=p&&td(t,["setup","systemInstruction"],function(e){let t={},r=th(e,["parts"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h,p;return r={},null!=(n=th(t=e,["mediaResolution"]))&&td(r,["mediaResolution"],n),null!=(i=th(t,["codeExecutionResult"]))&&td(r,["codeExecutionResult"],i),null!=(s=th(t,["executableCode"]))&&td(r,["executableCode"],s),null!=(o=th(t,["fileData"]))&&td(r,["fileData"],function(e){let t={};if(void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let r=th(e,["fileUri"]);null!=r&&td(t,["fileUri"],r);let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(o)),null!=(a=th(t,["functionCall"]))&&td(r,["functionCall"],function(e){let t={},r=th(e,["id"]);null!=r&&td(t,["id"],r);let n=th(e,["args"]);null!=n&&td(t,["args"],n);let i=th(e,["name"]);if(null!=i&&td(t,["name"],i),void 0!==th(e,["partialArgs"]))throw Error("partialArgs parameter is not supported in Gemini API.");if(void 0!==th(e,["willContinue"]))throw Error("willContinue parameter is not supported in Gemini API.");return t}(a)),null!=(l=th(t,["functionResponse"]))&&td(r,["functionResponse"],l),null!=(u=th(t,["inlineData"]))&&td(r,["inlineData"],function(e){let t={},r=th(e,["data"]);if(null!=r&&td(t,["data"],r),void 0!==th(e,["displayName"]))throw Error("displayName parameter is not supported in Gemini API.");let n=th(e,["mimeType"]);return null!=n&&td(t,["mimeType"],n),t}(u)),null!=(c=th(t,["text"]))&&td(r,["text"],c),null!=(d=th(t,["thought"]))&&td(r,["thought"],d),null!=(h=th(t,["thoughtSignature"]))&&td(r,["thoughtSignature"],h),null!=(p=th(t,["videoMetadata"]))&&td(r,["videoMetadata"],p),r})),td(t,["parts"],e)}let n=th(e,["role"]);return null!=n&&td(t,["role"],n),t}(t0(p)));let f=th(e,["tools"]);if(void 0!==t&&null!=f){let e=t5(f);Array.isArray(e)&&(e=e.map(e=>(function(e){let t={},r=th(e,["functionDeclarations"]);if(null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["functionDeclarations"],e)}if(void 0!==th(e,["retrieval"]))throw Error("retrieval parameter is not supported in Gemini API.");let n=th(e,["googleSearchRetrieval"]);null!=n&&td(t,["googleSearchRetrieval"],n);let i=th(e,["computerUse"]);null!=i&&td(t,["computerUse"],i);let s=th(e,["fileSearch"]);null!=s&&td(t,["fileSearch"],s);let o=th(e,["codeExecution"]);if(null!=o&&td(t,["codeExecution"],o),void 0!==th(e,["enterpriseWebSearch"]))throw Error("enterpriseWebSearch parameter is not supported in Gemini API.");let a=th(e,["googleMaps"]);null!=a&&td(t,["googleMaps"],function(e){let t={};if(void 0!==th(e,["authConfig"]))throw Error("authConfig parameter is not supported in Gemini API.");let r=th(e,["enableWidget"]);return null!=r&&td(t,["enableWidget"],r),t}(a));let l=th(e,["googleSearch"]);null!=l&&td(t,["googleSearch"],function(e){let t={};if(void 0!==th(e,["excludeDomains"]))throw Error("excludeDomains parameter is not supported in Gemini API.");if(void 0!==th(e,["blockingConfidence"]))throw Error("blockingConfidence parameter is not supported in Gemini API.");let r=th(e,["timeRangeFilter"]);return null!=r&&td(t,["timeRangeFilter"],r),t}(l));let u=th(e,["urlContext"]);return null!=u&&td(t,["urlContext"],u),t})(t8(e)))),td(t,["setup","tools"],e)}let m=th(e,["sessionResumption"]);void 0!==t&&null!=m&&td(t,["setup","sessionResumption"],function(e){let t={},r=th(e,["handle"]);if(null!=r&&td(t,["handle"],r),void 0!==th(e,["transparent"]))throw Error("transparent parameter is not supported in Gemini API.");return t}(m));let g=th(e,["inputAudioTranscription"]);void 0!==t&&null!=g&&td(t,["setup","inputAudioTranscription"],g);let y=th(e,["outputAudioTranscription"]);void 0!==t&&null!=y&&td(t,["setup","outputAudioTranscription"],y);let _=th(e,["realtimeInputConfig"]);void 0!==t&&null!=_&&td(t,["setup","realtimeInputConfig"],_);let E=th(e,["contextWindowCompression"]);void 0!==t&&null!=E&&td(t,["setup","contextWindowCompression"],E);let v=th(e,["proactivity"]);if(void 0!==t&&null!=v&&td(t,["setup","proactivity"],v),void 0!==th(e,["explicitVadSignal"]))throw Error("explicitVadSignal parameter is not supported in Gemini API.");return{}}(c,l)),l)),y=th(h,["lockAdditionalFields"]),void 0!==d&&null!=y&&td(d,["fieldMask"],y),{})),d);o=tc("auth_tokens",_._url),a=_._query,delete _.config,delete _._url,delete _._query;let E=function(e,t){let r=null,n=e.bidiGenerateContentSetup;if("object"==typeof n&&null!==n&&"setup"in n){let t=n.setup;"object"==typeof t&&null!==t?(e.bidiGenerateContentSetup=t,r=t):delete e.bidiGenerateContentSetup}else void 0!==n&&delete e.bidiGenerateContentSetup;let i=e.fieldMask;if(r){let n=function(e){let t=[];for(let r in e)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if("object"==typeof n&&null!=n&&Object.keys(n).length>0){let e=Object.keys(n).map(e=>`${r}.${e}`);t.push(...e)}else t.push(r)}return t.join(",")}(r);if(Array.isArray(null==t?void 0:t.lockAdditionalFields)&&(null==t?void 0:t.lockAdditionalFields.length)===0)n?e.fieldMask=n:delete e.fieldMask;else if((null==t?void 0:t.lockAdditionalFields)&&t.lockAdditionalFields.length>0&&null!==i&&Array.isArray(i)&&i.length>0){let t=["temperature","topK","topP","maxOutputTokens","responseModalities","seed","speechConfig"],r=[];i.length>0&&(r=i.map(e=>t.includes(e)?`generationConfig.${e}`:e));let s=[];n&&s.push(n),r.length>0&&s.push(...r),s.length>0?e.fieldMask=s.join(","):delete e.fieldMask}else delete e.fieldMask}else null!==i&&Array.isArray(i)&&i.length>0?e.fieldMask=i.join(","):delete e.fieldMask;return e}(_,e.config);return this.apiClient.request({path:o,queryParams:a,body:JSON.stringify(E),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}}class nt extends tu{constructor(e){super(),this.apiClient=e,this.list=async e=>new rp(tt.PAGED_ITEM_DOCUMENTS,t=>this.listInternal({parent:e.parent,config:t.config}),await this.listInternal(e),e)}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),s);return n=tc("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),null!=(a=th(e,["config"]))&&(l=th(a,["force"]),void 0!==s&&null!=l&&td(s,["_query","force"],l)),s);n=tc("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=th(e,["parent"]))&&td(s,["_url","parent"],o),null!=(a=th(e,["config"]))&&(l=th(a,["pageSize"]),void 0!==s&&null!=l&&td(s,["_query","pageSize"],l),u=th(a,["pageToken"]),void 0!==s&&null!=u&&td(s,["_query","pageToken"],u)),s);return n=tc("{parent}/documents",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["documents"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["documents"],e)}return t}(e),r=new tN;return Object.assign(r,t),r})}}}class nr extends tu{constructor(e,t=new nt(e)){super(),this.apiClient=e,this.documents=t,this.list=async(e={})=>new rp(tt.PAGED_ITEM_FILE_SEARCH_STORES,e=>this.listInternal(e),await this.listInternal(e),e)}async uploadToFileSearchStore(e){if(this.apiClient.isVertexAI())throw Error("Vertex AI does not support uploading files to a file search store.");return this.apiClient.uploadFileToFileSearchStore(e.fileSearchStoreName,e.file,e.config)}async create(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["displayName"]),void 0!==s&&null!=a&&td(s,["displayName"],a)),s);return n=tc("fileSearchStores",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async get(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),s);return n=tc("{name}",a._url),i=a._query,delete a._url,delete a._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>e)}}async delete(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["name"]))&&td(s,["_url","name"],o),null!=(a=th(e,["config"]))&&(l=th(a,["force"]),void 0!==s&&null!=l&&td(s,["_query","force"],l)),s);n=tc("{name}",u._url),i=u._query,delete u._url,delete u._query,await this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"DELETE",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal})}}async listInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["config"]))&&(a=th(o,["pageSize"]),void 0!==s&&null!=a&&td(s,["_query","pageSize"],a),l=th(o,["pageToken"]),void 0!==s&&null!=l&&td(s,["_query","pageToken"],l)),s);return n=tc("fileSearchStores",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["fileSearchStores"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["fileSearchStores"],e)}return t}(e),r=new tP;return Object.assign(r,t),r})}}async uploadToFileSearchStoreInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l=(s={},null!=(o=th(e,["fileSearchStoreName"]))&&td(s,["_url","file_search_store_name"],o),null!=(a=th(e,["config"]))&&rH(a,s),s);return n=tc("upload/v1beta/{file_search_store_name}:uploadToFileSearchStore",l._url),i=l._query,delete l._url,delete l._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(l),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tU;return Object.assign(i,n),i})}}async importFile(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u=(s={},null!=(o=th(e,["fileSearchStoreName"]))&&td(s,["_url","file_search_store_name"],o),null!=(a=th(e,["fileName"]))&&td(s,["fileName"],a),null!=(l=th(e,["config"]))&&function(e,t){let r=th(e,["customMetadata"]);if(void 0!==t&&null!=r){let e=r;Array.isArray(e)&&(e=e.map(e=>e)),td(t,["customMetadata"],e)}let n=th(e,["chunkingConfig"]);void 0!==t&&null!=n&&td(t,["chunkingConfig"],n)}(l,s),s);return n=tc("{file_search_store_name}:importFile",u._url),i=u._query,delete u._url,delete u._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(u),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json()).then(e=>{var t;let r,n,i,s,o,a,l,u,c,d,h=(o={},null!=(a=th(e,["name"]))&&td(o,["name"],a),null!=(l=th(e,["metadata"]))&&td(o,["metadata"],l),null!=(u=th(e,["done"]))&&td(o,["done"],u),null!=(c=th(e,["error"]))&&td(o,["error"],c),null!=(d=th(e,["response"]))&&td(o,["response"],(r={},null!=(n=th(t=d,["sdkHttpResponse"]))&&td(r,["sdkHttpResponse"],n),null!=(i=th(t,["parent"]))&&td(r,["parent"],i),null!=(s=th(t,["documentName"]))&&td(r,["documentName"],s),r)),o),p=new tD;return Object.assign(p,h),p})}}}let nn=function(){let{crypto:e}=globalThis;if(null==e?void 0:e.randomUUID)return nn=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),r=e?()=>e.getRandomValues(t)[0]:()=>255*Math.random()&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,e=>(e^r()&15>>e/4).toString(16))};function ni(e){return"object"==typeof e&&null!==e&&("name"in e&&"AbortError"===e.name||"message"in e&&String(e.message).includes("FetchRequestCanceledException"))}let ns=e=>{if(e instanceof Error)return e;if("object"==typeof e&&null!==e){try{if("[object Error]"===Object.prototype.toString.call(e)){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch(e){}try{return Error(JSON.stringify(e))}catch(e){}}return Error(e)};class no extends Error{}class na extends no{constructor(e,t,r,n){super(`${na.makeMessage(e,t,r)}`),this.status=e,this.headers=n,this.error=t}static makeMessage(e,t,r){let n=(null==t?void 0:t.message)?"string"==typeof t.message?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&n?`${e} ${n}`:e?`${e} status code (no body)`:n||"(no status code or body)"}static generate(e,t,r,n){return e&&n?400===e?new nd(e,t,r,n):401===e?new nh(e,t,r,n):403===e?new np(e,t,r,n):404===e?new nf(e,t,r,n):409===e?new nm(e,t,r,n):422===e?new ng(e,t,r,n):429===e?new ny(e,t,r,n):e>=500?new n_(e,t,r,n):new na(e,t,r,n):new nu({message:r,cause:ns(t)})}}class nl extends na{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class nu extends na{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class nc extends nu{constructor({message:e}={}){super({message:null!=e?e:"Request timed out."})}}class nd extends na{}class nh extends na{}class np extends na{}class nf extends na{}class nm extends na{}class ng extends na{}class ny extends na{}class n_ extends na{}let nE=/^[a-z][a-z0-9+.-]*:/i,nv=e=>(nv=Array.isArray)(e),nb=nv,nw="0.0.1",nA=e=>"x32"===e?"x32":"x86_64"===e||"x64"===e?"x64":"arm"===e?"arm":"aarch64"===e||"arm64"===e?"arm64":e?`other:${e}`:"unknown",nS=e=>(e=e.toLowerCase()).includes("ios")?"iOS":"android"===e?"Android":"darwin"===e?"MacOS":"win32"===e?"Windows":"freebsd"===e?"FreeBSD":"openbsd"===e?"OpenBSD":"linux"===e?"Linux":e?`Other:${e}`:"Unknown";function nT(...e){let t=globalThis.ReadableStream;if(void 0===t)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function nO(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return(null==e?void 0:e.done)&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function nI(e){var t,r;if(null===e||"object"!=typeof e)return;if(e[Symbol.asyncIterator])return void await (null==(r=(t=e[Symbol.asyncIterator]()).return)?void 0:r.call(t));let n=e.getReader(),i=n.cancel();n.releaseLock(),await i}let nC=({headers:e,body:t})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(t)}),nR=()=>{var e;if("u"<typeof File){let{process:t}=globalThis;throw Error("`File` is not defined as a global, which is required for file uploads."+("string"==typeof(null==(e=null==t?void 0:t.versions)?void 0:e.node)&&20>parseInt(t.versions.node.split("."))?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function nx(e,t,r){return nR(),new File(e,null!=t?t:"unknown_file",r)}let nk=e=>null!=e&&"object"==typeof e&&"number"==typeof e.size&&"string"==typeof e.type&&"function"==typeof e.text&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer;async function nN(e,t,r){var n;let i,s;if(nR(),null!=(i=e=await e)&&"object"==typeof i&&"string"==typeof i.name&&"number"==typeof i.lastModified&&nk(i))return e instanceof File?e:nx([await e.arrayBuffer()],e.name);if(null!=(s=e)&&"object"==typeof s&&"string"==typeof s.url&&"function"==typeof s.blob){let n=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),nx(await nP(n),t,r)}let o=await nP(e);if(t||(t=("object"==typeof(n=e)&&null!==n&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0),!(null==r?void 0:r.type)){let e=o.find(e=>"object"==typeof e&&"type"in e&&e.type);"string"==typeof e&&(r=Object.assign(Object.assign({},r),{type:e}))}return nx(o,t,r)}async function nP(e){let t=[];if("string"==typeof e||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(nk(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(null!=e&&"object"==typeof e&&"function"==typeof e[Symbol.asyncIterator])try{for(var r,n,i,s,o,a,l=!0,u=rv(e);!(r=(a=await u.next()).done);l=!0)s=a.value,l=!1,t.push(...await nP(s))}catch(e){n={error:e}}finally{try{!l&&!r&&(i=u.return)&&await i.call(u)}finally{if(n)throw n.error}}else{let t=null==(o=null==e?void 0:e.constructor)?void 0:o.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:""}${function(e){if("object"!=typeof e||null===e)return"";let t=Object.getOwnPropertyNames(e);return`; props: [${t.map(e=>`"${e}"`).join(", ")}]`}(e)}`)}return t}class nU{constructor(e){this._client=e}}function nD(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}nU._key=[];let nM=Object.freeze(Object.create(null)),nj=((e=nD)=>function(t,...r){let n;if(1===t.length)return t[0];let i=!1,s=[],o=t.reduce((t,n,o)=>{var a,l,u;/[?#]/.test(n)&&(i=!0);let c=r[o],d=(i?encodeURIComponent:e)(""+c);return o!==r.length&&(null==c||"object"==typeof c&&c.toString===(null==(u=Object.getPrototypeOf(null!=(l=Object.getPrototypeOf(null!=(a=c.hasOwnProperty)?a:nM))?l:nM))?void 0:u.toString))&&(d=c+"",s.push({start:t.length+n.length,length:d.length,error:`Value of type ${Object.prototype.toString.call(c).slice(8,-1)} is not a valid path parameter`})),t+n+(o===r.length?"":d)},""),a=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;for(;null!==(n=l.exec(a));)s.push({start:n.index,length:n[0].length,error:`Value "${n[0]}" can't be safely passed as a path parameter`});if(s.sort((e,t)=>e.start-t.start),s.length>0){let e=0,t=s.reduce((t,r)=>{let n=" ".repeat(r.start-e),i="^".repeat(r.length);return e=r.start+r.length,t+n+i},"");throw new no(`Path parameters result in path with invalid segments:
|
|
25
25
|
${s.map(e=>e.error).join("\n")}
|
|
26
26
|
${o}
|
|
27
|
-
${t}`)}return o})(nD);class nL extends nU{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=ry(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new no("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new no("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(nj`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(nj`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(nj`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:s=this._client.apiVersion}=i,o=ry(i,["api_version"]);return this._client.get(nj`/${s}/interactions/${e}`,Object.assign(Object.assign({query:o},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}nL._key=Object.freeze(["interactions"]);class nF extends nL{}function nG(e){let t;return(null!=r?r:r=(t=new globalThis.TextEncoder).encode.bind(t))(e)}function nq(e){let t;return(null!=n?n:n=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class n${constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?nG(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);let n=[];for(;null!=(t=function(e,t){for(let r=null!=t?t:0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(this.buffer,this.carriageReturnIndex));){if(t.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=t.index;continue}if(null!=this.carriageReturnIndex&&(t.index!==this.carriageReturnIndex+1||t.carriage)){n.push(nq(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}let e=null!==this.carriageReturnIndex?t.preceding-1:t.preceding,r=nq(this.buffer.subarray(0,e));n.push(r),this.buffer=this.buffer.subarray(t.index),this.carriageReturnIndex=null}return n}flush(){return this.buffer.length?this.decode("\n"):[]}}n$.NEWLINE_CHARS=new Set(["\n","\r"]),n$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let nB={off:0,error:200,warn:300,info:400,debug:500},nH=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(nB,e))return e;nz(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nB))}`)}};function nV(){}function nJ(e,t,r){return!t||nB[e]>nB[r]?nV:t[e].bind(t)}let nW={error:nV,warn:nV,info:nV,debug:nV},nK=new WeakMap;function nz(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return nW;let i=nK.get(r);if(i&&i[0]===n)return i[1];let s={error:nJ("error",r,n),warn:nJ("warn",r,n),info:nJ("info",r,n),debug:nJ("debug",r,n)};return nK.set(r,[n,s]),s}let nY=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class nX{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?nz(r):console;return new nX(function(){return rE(this,arguments,function*(){var r,s,o,a;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=rv(function(e,t){return rE(this,arguments,function*(){var r,n,i,s;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new no("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new no("Attempted to iterate over a response with no body")}let o=new nQ,a=new n$,l=nO(e.body);try{for(var u,c=!0,d=rv(function(e){return rE(this,arguments,function*(){var t,r,n,i;let s=new Uint8Array;try{for(var o,a=!0,l=rv(e);!(t=(o=yield r_(l.next())).done);a=!0){let e;if(i=o.value,a=!1,null==i)continue;let t=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?nG(i):i,r=new Uint8Array(s.length+t.length);for(r.set(s),r.set(t,s.length),s=r;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(s));)yield yield r_(s.slice(0,e)),s=s.slice(e)}}catch(e){r={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield r_(n.call(l)))}finally{if(r)throw r.error}}s.length>0&&(yield yield r_(s))})}(l));!(r=(u=yield r_(d.next())).done);c=!0)for(let e of(s=u.value,c=!1,a.decode(s))){let t=o.decode(e);t&&(yield yield r_(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield r_(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=o.decode(e);t&&(yield yield r_(t))}})}(e,t));!(r=(u=yield r_(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield r_(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){s={error:e}}finally{try{!c&&!r&&(o=d.return)&&(yield r_(o.call(d)))}finally{if(s)throw s.error}}l=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new nX(function(){return rE(this,arguments,function*(){var r,i,s,o;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=rv(function(){return rE(this,arguments,function*(){var t,r,n,i;let s=new n$,o=nO(e);try{for(var a,l=!0,u=rv(o);!(t=(a=yield r_(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,s.decode(i)))yield yield r_(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield r_(n.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush())yield yield r_(e)})}());!(r=(l=yield r_(c.next())).done);u=!0)o=l.value,u=!1,!a&&o&&(yield yield r_(JSON.parse(o)))}catch(e){i={error:e}}finally{try{!u&&!r&&(s=c.return)&&(yield r_(s.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new nX(()=>n(e),this.controller,this.client),new nX(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nT({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=nG(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class nQ{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function nZ(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{var n;if(t.options.stream)return(nz(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):nX.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),s=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();return(null==s?void 0:s.includes("application/json"))||(null==s?void 0:s.endsWith("+json"))?await r.json():await r.text()})();return nz(e).debug(`[${n}] response parsed`,nY({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}class n0 extends Promise{constructor(e,t,r=nZ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new n0(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let n1=Symbol("brand.privateNullableHeaders"),n2=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(n1 in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nb(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nb(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[n1]:!0,values:t,nulls:r}},n4=e=>{var t,r,n,i,s,o;return void 0!==globalThis.process?null!=(n=null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())?n:void 0:void 0!==globalThis.Deno?null==(o=null==(s=null==(i=globalThis.Deno.env)?void 0:i.get)?void 0:s.call(i,e))?void 0:o.trim():void 0};class n6{constructor(e){var t,r,n,i,s,o,a,{baseURL:l=n4("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=n4("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;const d=Object.assign(Object.assign({apiKey:u,apiVersion:c},ry(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:n6.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;const h="warn";this.logLevel=h,this.logLevel=null!=(s=null!=(i=nH(d.logLevel,"ClientOptions.logLevel",this))?i:nH(n4("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?s:h,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(o=d.maxRetries)?o:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nC,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let t=n2([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return n2([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return n2([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new no(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${nw}`}defaultIdempotencyKey(){return`stainless-node-retry-${nn()}`}makeStatusError(e,t,r,n){return na.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nE.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(s)&&(t=Object.assign(Object.assign({},s),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new n0(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,s;let o=await e,a=null!=(n=o.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(o);let{req:l,url:u,timeout:c}=await this.buildRequest(o,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:o});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,p=Date.now();if(nz(this).debug(`[${d}] sending request`,nY({retryOfRequestLogID:r,method:o.method,url:u,options:o,headers:l.headers})),null==(i=o.signal)?void 0:i.aborted)throw new nl;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(ns),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(s=o.signal)?void 0:s.aborted)throw new nl;let n=ni(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),this.retryRequest(o,t,null!=r?r:d);if(nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),n)throw new nc;throw new nu({cause:m})}let y=`[${d}${h}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-p}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nI(m.body),nz(this).info(`${y} - ${e}`),nz(this).debug(`[${d}] response error (${e})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),this.retryRequest(o,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";nz(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>ns(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=s?void 0:i;throw nz(this).debug(`[${d}] response error (${n})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-p})),this.makeStatusError(m.status,s,a,m.headers)}return nz(this).info(y),nz(this).debug(`[${d}] response start`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),{response:m,options:o,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:p}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:s,method:o}=i,a=ry(i,["signal","method"]);s&&s.addEventListener("abort",()=>n.abort());let l=setTimeout(()=>n.abort(),r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,c=Object.assign(Object.assign(Object.assign({signal:n.signal},u?{duplex:"half"}:{}),{method:"GET"}),a);o&&(c.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let s,o,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(s=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!s){let e=parseFloat(l);s=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){let r=null!=(i=e.maxRetries)?i:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (o=s,new Promise(e=>setTimeout(e,o))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let s=Object.assign({},e),{method:o,path:a,query:l,defaultBaseURL:u}=s,c=this.buildURL(a,l,u);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new no(`${e} must be an integer`);if(t<0)throw new no(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=null!=(r=s.timeout)?r:this.timeout;let{bodyHeaders:d,body:h}=this.buildBody({options:s}),p=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:p},s.signal&&{signal:s.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!=(n=this.fetchOptions)?n:{}),null!=(i=s.fetchOptions)?i:{}),url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=await this.authHeaders(e),a=n2([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),null!=t?t:t=(()=>{var e,t,r,n,i;let s="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(Deno.build.os),"X-Stainless-Arch":nA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:null!=(t=null==(e=Deno.version)?void 0:e.deno)?t:"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(null!=(r=globalThis.process.platform)?r:"unknown"),"X-Stainless-Arch":nA(null!=(n=globalThis.process.arch)?n:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":null!=(i=globalThis.process.version)?i:"unknown"};let o=function(){if("u"<typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${n}.${i}`}}}return null}();return o?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${o.browser}`,"X-Stainless-Runtime-Version":o.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),this._options.defaultHeaders,n,e.headers,o]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){let r;if(!e)return{bodyHeaders:void 0,body:void 0};let n=n2([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"!=typeof e||!(Symbol.asyncIterator in e)&&(!(Symbol.iterator in e)||!("next"in e)||"function"!=typeof e.next))return this.encoder({body:e,headers:n});return{bodyHeaders:void 0,body:(r=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nT({start(){},async pull(e){let{done:t,value:n}=await r.next();t?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=r.return)?void 0:e.call(r))}}))}}}n6.DEFAULT_TIMEOUT=6e4;class n3 extends n6{constructor(){super(...arguments),this.interactions=new nF(this)}}n3.GeminiNextGenAPIClient=n3,n3.GeminiNextGenAPIClientError=no,n3.APIError=na,n3.APIConnectionError=nu,n3.APIConnectionTimeoutError=nc,n3.APIUserAbortError=nl,n3.NotFoundError=nf,n3.ConflictError=nm,n3.RateLimitError=ny,n3.BadRequestError=nd,n3.AuthenticationError=nh,n3.InternalServerError=n_,n3.PermissionDeniedError=np,n3.UnprocessableEntityError=ng,n3.toFile=nN,n3.Interactions=nF;let n8="x-goog-api-key",n5="https://www.googleapis.com/auth/cloud-platform";class n9{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}const t=function(e){let t;if(!e)return{scopes:[n5]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==n5||Array.isArray(t.scopes)&&0>t.scopes.indexOf(n5))throw Error(`Invalid auth scopes. Scopes must include: ${n5}`)}else t.scopes=[n5];return t}(e.googleAuthOptions);this.googleAuth=new tr.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(n8)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(n8,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class n7{async download(e,t){if(e.downloadPath){let r=await ie(e,t);if(r instanceof tm){let t=(0,tn.createWriteStream)(e.downloadPath);ts.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,to.finished)(t)}else try{await (0,ti.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function ie(e,t){var r,n,i;let s=rr(e.file);if(void 0!==s)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(re(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rt(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class it{create(e,t,r){return new ir(e,t,r)}}class ir{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new ta.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ii(e,t){let r,n,i,s={},o=th(e,["sdkHttpResponse"]);null!=o&&td(s,["sdkHttpResponse"],o);let a=th(e,["name"]);null!=a&&td(s,["name"],a);let l=th(e,["state"]);null!=l&&td(s,["state"],t7(l));let u=th(e,["createTime"]);null!=u&&td(s,["createTime"],u);let c=th(e,["tuningTask","startTime"]);null!=c&&td(s,["startTime"],c);let d=th(e,["tuningTask","completeTime"]);null!=d&&td(s,["endTime"],d);let h=th(e,["updateTime"]);null!=h&&td(s,["updateTime"],h);let p=th(e,["description"]);null!=p&&td(s,["description"],p);let f=th(e,["baseModel"]);null!=f&&td(s,["baseModel"],f);let m=th(e,["_self"]);return null!=m&&td(s,["tunedModel"],(r={},null!=(n=th(m,["name"]))&&td(r,["model"],n),null!=(i=th(m,["name"]))&&td(r,["endpoint"],i),r)),s}function is(e,t){let r={},n=th(e,["sdkHttpResponse"]);null!=n&&td(r,["sdkHttpResponse"],n);let i=th(e,["name"]);null!=i&&td(r,["name"],i);let s=th(e,["state"]);null!=s&&td(r,["state"],t7(s));let o=th(e,["createTime"]);null!=o&&td(r,["createTime"],o);let a=th(e,["startTime"]);null!=a&&td(r,["startTime"],a);let l=th(e,["endTime"]);null!=l&&td(r,["endTime"],l);let u=th(e,["updateTime"]);null!=u&&td(r,["updateTime"],u);let c=th(e,["error"]);null!=c&&td(r,["error"],c);let d=th(e,["description"]);null!=d&&td(r,["description"],d);let h=th(e,["baseModel"]);null!=h&&td(r,["baseModel"],h);let p=th(e,["tunedModel"]);null!=p&&td(r,["tunedModel"],p);let f=th(e,["preTunedModel"]);null!=f&&td(r,["preTunedModel"],f);let m=th(e,["supervisedTuningSpec"]);null!=m&&td(r,["supervisedTuningSpec"],m);let g=th(e,["preferenceOptimizationSpec"]);null!=g&&td(r,["preferenceOptimizationSpec"],g);let y=th(e,["tuningDataStats"]);null!=y&&td(r,["tuningDataStats"],y);let _=th(e,["encryptionSpec"]);null!=_&&td(r,["encryptionSpec"],_);let E=th(e,["partnerModelTuningSpec"]);null!=E&&td(r,["partnerModelTuningSpec"],E);let v=th(e,["customBaseModel"]);null!=v&&td(r,["customBaseModel"],v);let b=th(e,["experiment"]);null!=b&&td(r,["experiment"],b);let w=th(e,["labels"]);null!=w&&td(r,["labels"],w);let A=th(e,["outputUri"]);null!=A&&td(r,["outputUri"],A);let S=th(e,["pipelineJob"]);null!=S&&td(r,["pipelineJob"],S);let T=th(e,["serviceAccount"]);null!=T&&td(r,["serviceAccount"],T);let O=th(e,["tunedModelDisplayName"]);null!=O&&td(r,["tunedModelDisplayName"],O);let I=th(e,["veoTuningSpec"]);return null!=I&&td(r,["veoTuningSpec"],I),r}function io(e,t){let r={},n=th(e,["gcsUri"]);null!=n&&td(r,["validationDatasetUri"],n);let i=th(e,["vertexDatasetResource"]);return null!=i&&td(r,["validationDatasetUri"],i),r}class ia extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eN.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ii(e))}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l),u=th(i,["filter"]),void 0!==n&&null!=u&&td(n,["_query","filter"],u)),n);return s=tc("tuningJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>is(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}{let t,r,a,l,u,c=(t={},null!=(r=th(e,["config"]))&&(a=th(r,["pageSize"]),void 0!==t&&null!=a&&td(t,["_query","pageSize"],a),l=th(r,["pageToken"]),void 0!==t&&null!=l&&td(t,["_query","pageToken"],l),u=th(r,["filter"]),void 0!==t&&null!=u&&td(t,["_query","filter"],u)),t);return s=tc("tunedModels",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tunedModels"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ii(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}}async cancel(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}let i=th(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}if(void 0!==th(e,["examples"]))throw Error("examples parameter is not supported in Vertex AI.")}(l,s,e),null!=(u=th(e,["config"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec"],io(r))}else if("PREFERENCE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec"],io(r))}let i=th(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&td(t,["tunedModelDisplayName"],i);let s=th(e,["description"]);void 0!==t&&null!=s&&td(t,["description"],s);let o=th(r,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}let a=th(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}let l=th(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}let u=th(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}if(void 0!==th(e,["batchSize"]))throw Error("batchSize parameter is not supported in Vertex AI.");if(void 0!==th(e,["learningRate"]))throw Error("learningRate parameter is not supported in Vertex AI.");let c=th(e,["labels"]);void 0!==t&&null!=c&&td(t,["labels"],c);let d=th(e,["beta"]);void 0!==t&&null!=d&&td(t,["preferenceOptimizationSpec","hyperParameters","beta"],d)}(u,s,e),s);return n=tc("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}throw Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e){if(void 0!==th(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let t=th(e,["examples"]);if(null!=t){let e=t;Array.isArray(e)&&(e=e.map(e=>e)),td({},["examples","examples"],e)}}(l),null!=(u=th(e,["config"]))&&function(e,t){if(void 0!==th(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let r=th(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=r&&td(t,["displayName"],r),void 0!==th(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let n=th(e,["epochCount"]);void 0!==t&&null!=n&&td(t,["tuningTask","hyperparameters","epochCount"],n);let i=th(e,["learningRateMultiplier"]);if(null!=i&&td({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==th(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==th(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==th(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");let s=th(e,["batchSize"]);void 0!==t&&null!=s&&td(t,["tuningTask","hyperparameters","batchSize"],s);let o=th(e,["learningRate"]);if(void 0!==t&&null!=o&&td(t,["tuningTask","hyperparameters","learningRate"],o),void 0!==th(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==th(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.")}(u,s),s);return n=tc("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),t})}}}let il="x-goog-upload-status";async function iu(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async function ic(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async function id(e,t,r){var n,i;let s=0,o=0,a=new tm(new Response),l="upload";for(s=e.size;o<s;){let u=Math.min(8388608,s-o),c=e.slice(o,o+u);o+u>=s&&(l+=", finalize");let d=0,h=1e3;for(;d<3&&(null==(n=null==(a=await r.request({path:"",body:c,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(o),"Content-Length":String(u)}}}))?void 0:a.headers)||!n[il]);)d++,await ip(h),h*=2;if(o+=u,(null==(i=null==a?void 0:a.headers)?void 0:i[il])!=="active")break;if(s<=o)throw Error("All content has been uploaded, but the upload status is not finalized.")}return a}async function ih(e){return{size:e.size,type:e.type}}function ip(e){return new Promise(t=>setTimeout(t,e))}class im{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await ti.stat(e)).size,t.type=this.inferMimeType(e),t):await ih(e)}async upload(e,t,r){return"string"==typeof e?await this.uploadFileFromPath(e,t,r):iu(e,t,r)}async uploadToFileSearchStore(e,t,r){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r):ic(e,t,r)}inferMimeType(e){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async uploadFileToFileSearchStoreFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async uploadFileFromPathInternal(e,t,r){var n,i;let s,o=0,a=0,l=new tm(new Response),u="upload",c=tl.basename(e);try{if(!(s=await ti.open(e,"r")))throw Error("Failed to open file");for(o=(await s.stat()).size;a<o;){let e=Math.min(8388608,o-a);a+e>=o&&(u+=", finalize");let d=new Uint8Array(e),{bytesRead:h}=await s.read(d,0,e,a);if(h!==e)throw Error(`Failed to read ${e} bytes from file at offset ${a}. bytes actually read: ${h}`);let p=new Blob([d]),f=0,m=1e3;for(;f<3&&(null==(n=null==(l=await r.request({path:"",body:p,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":u,"X-Goog-Upload-Offset":String(a),"Content-Length":String(h),"X-Goog-Upload-File-Name":c}}}))?void 0:l.headers)||!n[il]);)f++,await ip(m),m*=2;if(a+=h,(null==(i=null==l?void 0:l.headers)?void 0:i[il])!=="active")break;if(o<=a)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}finally{s&&await s.close()}}}class ig{get interactions(){if(void 0!==this._interactions)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");let e=this.httpOptions;(null==e?void 0:e.extraBody)&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");let t=new n3({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==e?void 0:e.timeout});return this._interactions=t.interactions,this._interactions}constructor(e){var t,r,n,o,a,l;if((e.project||e.location)&&e.apiKey)throw Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=null!=(r=null!=(t=e.vertexai)?t:function(e){var t;return void 0!==(t=iy(e))&&"true"===t.toLowerCase()}("GOOGLE_GENAI_USE_VERTEXAI"))&&r;const u=function(){let e=iy("GOOGLE_API_KEY"),t=iy("GEMINI_API_KEY");return e&&t&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),e||t||void 0}(),c=iy("GOOGLE_CLOUD_PROJECT"),d=iy("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(n=e.apiKey)?n:u,this.project=null!=(o=e.project)?o:c,this.location=null!=(a=e.location)?a:d,e.vertexai&&((null==(l=e.googleAuthOptions)?void 0:l.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(c||d)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&u?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(c||d)&&u&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));const h=function(e,t,r,n){return(null==e?void 0:e.baseUrl)?e.baseUrl:t?null!=s?s:r:null!=i?i:n}(e.httpOptions,e.vertexai,iy("GOOGLE_VERTEX_BASE_URL"),iy("GOOGLE_GEMINI_BASE_URL"));h&&(e.httpOptions?e.httpOptions.baseUrl=h:e.httpOptions={baseUrl:h}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const p=new n9({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new rJ({auth:p,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new im,downloader:new n7}),this.models=new r9(this.apiClient),this.live=new r1(this.apiClient,p,new it),this.batches=new rf(this.apiClient),this.chats=new rA(this.models,this.apiClient),this.caches=new rg(this.apiClient),this.files=new rO(this.apiClient),this.operations=new r7(this.apiClient),this.authTokens=new ne(this.apiClient),this.tunings=new ia(this.apiClient),this.fileSearchStores=new nr(this.apiClient)}}function iy(e){var t,r,n;return null!=(n=null==(r=null==(t=null==process?void 0:process.env)?void 0:t[e])?void 0:r.trim())?n:void 0}var i_=e.i(5898),iE=e.i(61829),iv=e.i(83598),ib=e.i(99617),iw=e.i(98003),iA=e.i(59398),iS=e.i(50377),iT=e.i(93716),iO=e.i(30166),iI=e.i(15851);let iC=(0,iS.createLogger)("ai:gemini");e.s(["GeminiProvider",0,class{ai;modelName;baseUrl;constructor(e){const t=e?.apiKey,r=e?.baseUrl;if(!t)throw Error("AI_AUTH_ERROR: GOOGLE_API_KEY is required for Gemini provider");this.ai=new ig({apiKey:t,httpOptions:r?{baseUrl:r}:void 0}),this.modelName=e?.model||"gemini-2.0-flash",this.baseUrl=r||"https://generativelanguage.googleapis.com",iC.info({provider:"Gemini",model:this.modelName,baseUrl:this.baseUrl,apiKeyPrefix:t.substring(0,8)+"..."},"AI Provider initialized")}async retryOperation(e,t=3){let r;for(let n=1;n<=t;n++)try{return await e()}catch(s){r=s;let e=s instanceof Error?s.message.toLowerCase():String(s);if(!(e.includes("fetch failed")||e.includes("network")||e.includes("connect")||e.includes("503")||e.includes("502")||e.includes("504")||e.includes("overloaded")||e.includes("timeout")||e.includes("etimedout")||e.includes("enotfound")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("unavailable"))||n===t)throw s;let i=1e3*Math.pow(2,n-1);iC.warn({attempt:n,maxRetries:t,error:e,nextRetryDelayMs:i},"Gemini operation failed, retrying..."),await new Promise(e=>setTimeout(e,i))}throw r}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){iC.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),o=this.extractTag(e,"requires_image"),a=this.extractTag(e,"wrong_answer_text")||"",l=this.extractTag(e,"mistake_analysis")||"",u=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw iC.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let c="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(c=i);let d=[];s&&(d=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let h=o?.toLowerCase().trim()==="true",p=(0,iO.normalizeMistakeStatusForSave)(u,a),f={questionText:t,answerText:r,analysis:n,wrongAnswerText:a,mistakeAnalysis:l,mistakeStatus:p,subject:c,knowledgePoints:d,requiresImage:h,difficultyStars:(0,ib.parseDifficultyStars)(this.extractTag(e,"difficulty_stars")),...(0,ib.parseFigure)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},m=(0,ib.safeParseParsedQuestion)(f);return m.success?(iC.debug("Validated successfully via XML tags"),m.data):(iC.warn({validationError:m.error.format()},"Schema validation warning"),f)}async analyzeImage(e,t="image/jpeg",r="zh",n,i,s,o){let a=(0,iw.getAppConfig)(),l=o?{candidateTags:o}:await (0,iA.prefetchSubjectTags)(i,n),u=(0,i_.generateAnalyzePrompt)(r,n,i,{customTemplate:a.prompts?.analyze,...l},s);iC.box("🔍 AI Image Analysis Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,imageSize:`${e.length} bytes`,mimeType:t,model:this.modelName,language:r,grade:n||"all"}),iC.box("📝 Full Prompt",u);try{let r={model:this.modelName,contents:[{text:u},{inlineData:{data:`[...${e.length} bytes base64 data...]`,mimeType:t}}]};iC.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(r,null,2));let n=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:u},{inlineData:{data:e,mimeType:t}}]}));iC.box("📦 Full API Response Metadata",{usageMetadata:n.usageMetadata});let i=n.text||"";if(iC.box("🤖 AI Raw Response",i),!i)throw Error(n.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let s=this.parseResponse(i);return iC.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw iC.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,r="zh",n="medium",i,s){let o=(0,iw.getAppConfig)(),a=(0,i_.generateSimilarQuestionPrompt)(r,e,t,n,{customTemplate:o.prompts?.similar,originalFigureSvg:s},i);iC.box("🎯 Generate Similar Question Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:n,language:r}),iC.box("📝 Full Prompt",a);try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:a})),t=e.text||"";if(iC.box("🤖 AI Raw Response",t),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let r=this.parseResponse(t);return iC.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,iI.normalizeGeneratedQuestion)(r)}catch(e){throw iC.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,o){let{generateReanswerPrompt:a}=await e.A(30249),l=a(r,t,n,{candidateTags:o},s);iC.info({provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),iC.debug({prompt:l},"Full prompt");try{let e;if(i){let t=i.replace(/^data:image\/\w+;base64,/,"");e=[{text:l},{inlineData:{mimeType:"image/jpeg",data:t}}]}else e=l;let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:e})),r=t.text||"";if(iC.debug({rawResponse:r},"AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",o=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),a=this.extractTag(r,"wrong_answer_text")||"",u=this.extractTag(r,"mistake_analysis")||"",c=(0,iO.normalizeMistakeStatusForSave)(this.extractTag(r,"mistake_status"),a);return iC.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:o,wrongAnswerText:a,mistakeAnalysis:u,mistakeStatus:c,subject:(0,ib.normalizeSubject)(this.extractTag(r,"subject")),difficultyStars:(0,ib.parseDifficultyStars)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,r,n){let i=(0,i_.generateGeogebraPrompt)(e,t,r,n);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:i})),t=e.text||"";if(iC.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let s=r.indexOf("{"),o=r.lastIndexOf("}");-1!==s&&-1!==o&&(r=r.substring(s,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,i_.generateMasteryPrompt)(e);iC.info({provider:"Gemini",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),r=e.text||"";if(iC.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseMasteryEvaluation)(r)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,i_.generateTagSuggestPrompt)(e);iC.info({provider:"Gemini",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),n=r.text||"";if(iC.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseTagSuggestion)(n,e.allowedTags)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,r){let n=(0,i_.generateFigurePrompt)(r);iC.info({provider:"Gemini",model:this.modelName,imageSize:e.length},"Figure SVG Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:n},{inlineData:{data:e,mimeType:t}}]})),i=r.text||"";if(iC.debug({rawResponse:i},"Figure SVG AI raw response"),!i)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseFigure)(this.extractTag(i,"has_figure"),this.extractTag(i,"figure_svg"))}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,i_.generateLatexFixPrompt)(e);iC.info({provider:"Gemini",model:this.modelName,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:t},{text:"请修复上述内容中的 LaTeX 语法。"}]})),n=r.text||"";if(iC.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,iv.parseLatexFix)(n,e)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,r,n){let i=(0,i_.generateSvgAnimationPrompt)(e,t,r,n);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"SVG Animation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:i},{text:"请为上述题目制作 SVG 动画讲解。"}]})),t=e.text||"";if(iC.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,iE.sanitizeSvgAnimation)(this.extractTag(t,"svg_animation")||t)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(iC.error({error:e},"Gemini error"),e instanceof Error){if(e.message===iT.AI_OUTPUT_TRUNCATED||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],93963)},92938,e=>{"use strict";e.i(89228);var t=e.i(88045),t=t,r=e.i(5898),n=e.i(61829),i=e.i(83598),s=e.i(98003),o=e.i(99617),a=e.i(59398),l=e.i(50377),u=e.i(93716),c=e.i(30166),d=e.i(15851);let h=(0,l.createLogger)("ai:openai");e.s(["OpenAIProvider",0,class{openai;model;baseURL;apiKey;isLongCat;constructor(e){const r=e?.apiKey,n=e?.baseUrl;if(!r)throw Error("AI_AUTH_ERROR: OPENAI_API_KEY is required for OpenAI provider");this.openai=new t.OpenAI({apiKey:r,baseURL:n||void 0,defaultHeaders:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.model=e?.model||"gpt-4o",this.baseURL=n||"https://api.openai.com/v1",this.apiKey=r,this.isLongCat=this.baseURL.includes("longcat.chat"),h.info({provider:"OpenAI",model:this.model,baseURL:this.baseURL,apiKeyPrefix:r.substring(0,8)+"..."},"AI Provider initialized")}adaptMessagesForLongCat(e){return e.map(e=>{if("string"==typeof e.content)return{...e,content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(e=>"image_url"===e.type?{type:"input_image",input_image:{data:[e.image_url.url],type:"url"}}:e);return{...e,content:t}}return e})}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r);if(-1===i)return null;let s=i+r.length,o=e.lastIndexOf(n);return -1===o&&"analysis"===t?(h.warn({tagName:t},"Tag was verified unclosed, treating as truncated and reading to end"),e.substring(s).trim()):-1===o||s>=o?null:e.substring(s,o).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.normalizeMistakeStatusForSave)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.parseDifficultyStars)(this.extractTag(e,"difficulty_stars")),...(0,o.parseFigure)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.safeParseParsedQuestion)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.getAppConfig)(),p=c?{candidateTags:c}:await (0,a.prefetchSubjectTags)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r,n={model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,[...${e.length} bytes base64 data...]`}}]}],max_tokens:8192};if(h.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(n,null,2)),this.isLongCat){let n=this.adaptMessagesForLongCat([{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}]),i=await fetch(`${this.baseURL}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:n,max_tokens:8192})});if(!i.ok){let e=await i.text();throw h.error({status:i.status,body:e},"LongCat API error"),Error(`${i.status} status code (${e})`)}r=await i.json()}else r=await (0,u.withTruncationRetry)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let i=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",i),!i)throw Error("Empty response from AI");let s=this.parseResponse(i);return h.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.getAppConfig)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
|
|
27
|
+
${t}`)}return o})(nD);class nL extends nU{create(e,t){var r;let{api_version:n=this._client.apiVersion}=e,i=ry(e,["api_version"]);if("model"in i&&"agent_config"in i)throw new no("Invalid request: specified `model` and `agent_config`. If specifying `model`, use `generation_config`.");if("agent"in i&&"generation_config"in i)throw new no("Invalid request: specified `agent` and `generation_config`. If specifying `agent`, use `agent_config`.");return this._client.post(nj`/${n}/interactions`,Object.assign(Object.assign({body:i},t),{stream:null!=(r=e.stream)&&r}))}delete(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.delete(nj`/${n}/interactions/${e}`,r)}cancel(e,t={},r){let{api_version:n=this._client.apiVersion}=null!=t?t:{};return this._client.post(nj`/${n}/interactions/${e}/cancel`,r)}get(e,t={},r){var n;let i=null!=t?t:{},{api_version:s=this._client.apiVersion}=i,o=ry(i,["api_version"]);return this._client.get(nj`/${s}/interactions/${e}`,Object.assign(Object.assign({query:o},r),{stream:null!=(n=null==t?void 0:t.stream)&&n}))}}nL._key=Object.freeze(["interactions"]);class nF extends nL{}function nG(e){let t;return(null!=r?r:r=(t=new globalThis.TextEncoder).encode.bind(t))(e)}function nq(e){let t;return(null!=n?n:n=(t=new globalThis.TextDecoder).decode.bind(t))(e)}class n${constructor(){this.buffer=new Uint8Array,this.carriageReturnIndex=null}decode(e){let t;if(null==e)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):"string"==typeof e?nG(e):e;this.buffer=function(e){let t=0;for(let r of e)t+=r.length;let r=new Uint8Array(t),n=0;for(let t of e)r.set(t,n),n+=t.length;return r}([this.buffer,r]);let n=[];for(;null!=(t=function(e,t){for(let r=null!=t?t:0;r<e.length;r++){if(10===e[r])return{preceding:r,index:r+1,carriage:!1};if(13===e[r])return{preceding:r,index:r+1,carriage:!0}}return null}(this.buffer,this.carriageReturnIndex));){if(t.carriage&&null==this.carriageReturnIndex){this.carriageReturnIndex=t.index;continue}if(null!=this.carriageReturnIndex&&(t.index!==this.carriageReturnIndex+1||t.carriage)){n.push(nq(this.buffer.subarray(0,this.carriageReturnIndex-1))),this.buffer=this.buffer.subarray(this.carriageReturnIndex),this.carriageReturnIndex=null;continue}let e=null!==this.carriageReturnIndex?t.preceding-1:t.preceding,r=nq(this.buffer.subarray(0,e));n.push(r),this.buffer=this.buffer.subarray(t.index),this.carriageReturnIndex=null}return n}flush(){return this.buffer.length?this.decode("\n"):[]}}n$.NEWLINE_CHARS=new Set(["\n","\r"]),n$.NEWLINE_REGEXP=/\r\n|[\n\r]/g;let nB={off:0,error:200,warn:300,info:400,debug:500},nH=(e,t,r)=>{if(e){if(Object.prototype.hasOwnProperty.call(nB,e))return e;nz(r).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(nB))}`)}};function nV(){}function nJ(e,t,r){return!t||nB[e]>nB[r]?nV:t[e].bind(t)}let nW={error:nV,warn:nV,info:nV,debug:nV},nK=new WeakMap;function nz(e){var t;let r=e.logger,n=null!=(t=e.logLevel)?t:"off";if(!r)return nW;let i=nK.get(r);if(i&&i[0]===n)return i[1];let s={error:nJ("error",r,n),warn:nJ("warn",r,n),info:nJ("info",r,n),debug:nJ("debug",r,n)};return nK.set(r,[n,s]),s}let nY=e=>(e.options&&(e.options=Object.assign({},e.options),delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,"x-goog-api-key"===e.toLowerCase()||"authorization"===e.toLowerCase()||"cookie"===e.toLowerCase()||"set-cookie"===e.toLowerCase()?"***":t]))),"retryOfRequestLogID"in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e);class nX{constructor(e,t,r){this.iterator=e,this.controller=t,this.client=r}static fromSSEResponse(e,t,r){let n=!1,i=r?nz(r):console;return new nX(function(){return rE(this,arguments,function*(){var r,s,o,a;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let l=!1;try{try{for(var u,c=!0,d=rv(function(e,t){return rE(this,arguments,function*(){var r,n,i,s;if(!e.body){if(t.abort(),void 0!==globalThis.navigator&&"ReactNative"===globalThis.navigator.product)throw new no("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api");throw new no("Attempted to iterate over a response with no body")}let o=new nQ,a=new n$,l=nO(e.body);try{for(var u,c=!0,d=rv(function(e){return rE(this,arguments,function*(){var t,r,n,i;let s=new Uint8Array;try{for(var o,a=!0,l=rv(e);!(t=(o=yield r_(l.next())).done);a=!0){let e;if(i=o.value,a=!1,null==i)continue;let t=i instanceof ArrayBuffer?new Uint8Array(i):"string"==typeof i?nG(i):i,r=new Uint8Array(s.length+t.length);for(r.set(s),r.set(t,s.length),s=r;-1!==(e=function(e){for(let t=0;t<e.length-1;t++){if(10===e[t]&&10===e[t+1]||13===e[t]&&13===e[t+1])return t+2;if(13===e[t]&&10===e[t+1]&&t+3<e.length&&13===e[t+2]&&10===e[t+3])return t+4}return -1}(s));)yield yield r_(s.slice(0,e)),s=s.slice(e)}}catch(e){r={error:e}}finally{try{!a&&!t&&(n=l.return)&&(yield r_(n.call(l)))}finally{if(r)throw r.error}}s.length>0&&(yield yield r_(s))})}(l));!(r=(u=yield r_(d.next())).done);c=!0)for(let e of(s=u.value,c=!1,a.decode(s))){let t=o.decode(e);t&&(yield yield r_(t))}}catch(e){n={error:e}}finally{try{!c&&!r&&(i=d.return)&&(yield r_(i.call(d)))}finally{if(n)throw n.error}}for(let e of a.flush()){let t=o.decode(e);t&&(yield yield r_(t))}})}(e,t));!(r=(u=yield r_(d.next())).done);c=!0)if(a=u.value,c=!1,!l)if(a.data.startsWith("[DONE]")){l=!0;continue}else try{yield yield r_(JSON.parse(a.data))}catch(e){throw i.error("Could not parse message into JSON:",a.data),i.error("From chunk:",a.raw),e}}catch(e){s={error:e}}finally{try{!c&&!r&&(o=d.return)&&(yield r_(o.call(d)))}finally{if(s)throw s.error}}l=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{l||t.abort()}})},t,r)}static fromReadableStream(e,t,r){let n=!1;return new nX(function(){return rE(this,arguments,function*(){var r,i,s,o;if(n)throw new no("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{try{for(var l,u=!0,c=rv(function(){return rE(this,arguments,function*(){var t,r,n,i;let s=new n$,o=nO(e);try{for(var a,l=!0,u=rv(o);!(t=(a=yield r_(u.next())).done);l=!0)for(let e of(i=a.value,l=!1,s.decode(i)))yield yield r_(e)}catch(e){r={error:e}}finally{try{!l&&!t&&(n=u.return)&&(yield r_(n.call(u)))}finally{if(r)throw r.error}}for(let e of s.flush())yield yield r_(e)})}());!(r=(l=yield r_(c.next())).done);u=!0)o=l.value,u=!1,!a&&o&&(yield yield r_(JSON.parse(o)))}catch(e){i={error:e}}finally{try{!u&&!r&&(s=c.return)&&(yield r_(s.call(c)))}finally{if(i)throw i.error}}a=!0}catch(e){if(ni(e))return yield r_(void 0);throw e}finally{a||t.abort()}})},t,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],t=[],r=this.iterator(),n=n=>({next:()=>{if(0===n.length){let n=r.next();e.push(n),t.push(n)}return n.shift()}});return[new nX(()=>n(e),this.controller,this.client),new nX(()=>n(t),this.controller,this.client)]}toReadableStream(){let e,t=this;return nT({async start(){e=t[Symbol.asyncIterator]()},async pull(t){try{let{value:r,done:n}=await e.next();if(n)return t.close();let i=nG(JSON.stringify(r)+"\n");t.enqueue(i)}catch(e){t.error(e)}},async cancel(){var t;await (null==(t=e.return)?void 0:t.call(e))}})}}class nQ{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){var t;let r;if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let e={event:this.event,data:this.data.join("\n"),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,i,s]=-1!==(r=(t=e).indexOf(":"))?[t.substring(0,r),":",t.substring(r+1)]:[t,"",""];return s.startsWith(" ")&&(s=s.substring(1)),"event"===n?this.event=s:"data"===n&&this.data.push(s),null}}async function nZ(e,t){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=t,o=await (async()=>{var n;if(t.options.stream)return(nz(e).debug("response",r.status,r.url,r.headers,r.body),t.options.__streamClass)?t.options.__streamClass.fromSSEResponse(r,t.controller,e):nX.fromSSEResponse(r,t.controller,e);if(204===r.status)return null;if(t.options.__binaryResponse)return r;let i=r.headers.get("content-type"),s=null==(n=null==i?void 0:i.split(";")[0])?void 0:n.trim();return(null==s?void 0:s.includes("application/json"))||(null==s?void 0:s.endsWith("+json"))?await r.json():await r.text()})();return nz(e).debug(`[${n}] response parsed`,nY({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}class n0 extends Promise{constructor(e,t,r=nZ){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=r,this.client=e}_thenUnwrap(e){return new n0(this.client,this.responsePromise,async(t,r)=>e(await this.parseResponse(t,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(this.client,e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}let n1=Symbol("brand.privateNullableHeaders"),n2=e=>{let t=new Headers,r=new Set;for(let n of e){let e=new Set;for(let[i,s]of function*(e){let t;if(!e)return;if(n1 in e){let{values:t,nulls:r}=e;for(let e of(yield*t.entries(),r))yield[e,null];return}let r=!1;for(let n of(e instanceof Headers?t=e.entries():nb(e)?t=e:(r=!0,t=Object.entries(null!=e?e:{})),t)){let e=n[0];if("string"!=typeof e)throw TypeError("expected header name to be a string");let t=nb(n[1])?n[1]:[n[1]],i=!1;for(let n of t)void 0!==n&&(r&&!i&&(i=!0,yield[e,null]),yield[e,n])}}(n)){let n=i.toLowerCase();e.has(n)||(t.delete(i),e.add(n)),null===s?(t.delete(i),r.add(n)):(t.append(i,s),r.delete(n))}}return{[n1]:!0,values:t,nulls:r}},n4=e=>{var t,r,n,i,s,o;return void 0!==globalThis.process?null!=(n=null==(r=null==(t=globalThis.process.env)?void 0:t[e])?void 0:r.trim())?n:void 0:void 0!==globalThis.Deno?null==(o=null==(s=null==(i=globalThis.Deno.env)?void 0:i.get)?void 0:s.call(i,e))?void 0:o.trim():void 0};class n6{constructor(e){var t,r,n,i,s,o,a,{baseURL:l=n4("GEMINI_NEXT_GEN_API_BASE_URL"),apiKey:u=null!=(t=n4("GEMINI_API_KEY"))?t:null,apiVersion:c="v1beta"}=e;const d=Object.assign(Object.assign({apiKey:u,apiVersion:c},ry(e,["baseURL","apiKey","apiVersion"])),{baseURL:l||"https://generativelanguage.googleapis.com"});this.baseURL=d.baseURL,this.timeout=null!=(r=d.timeout)?r:n6.DEFAULT_TIMEOUT,this.logger=null!=(n=d.logger)?n:console;const h="warn";this.logLevel=h,this.logLevel=null!=(s=null!=(i=nH(d.logLevel,"ClientOptions.logLevel",this))?i:nH(n4("GEMINI_NEXT_GEN_API_LOG"),"process.env['GEMINI_NEXT_GEN_API_LOG']",this))?s:h,this.fetchOptions=d.fetchOptions,this.maxRetries=null!=(o=d.maxRetries)?o:2,this.fetch=null!=(a=d.fetch)?a:function(){if("u">typeof fetch)return fetch;throw Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new GeminiNextGenAPIClient({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}(),this.encoder=nC,this._options=d,this.apiKey=u,this.apiVersion=c,this.clientAdapter=d.clientAdapter}withOptions(e){return new this.constructor(Object.assign(Object.assign(Object.assign({},this._options),{baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,apiVersion:this.apiVersion}),e))}baseURLOverridden(){return"https://generativelanguage.googleapis.com"!==this.baseURL}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){if(!(e.has("authorization")||e.has("x-goog-api-key")||this.apiKey&&e.get("x-goog-api-key"))&&!t.has("x-goog-api-key"))throw Error('Could not resolve authentication method. Expected the apiKey to be set. Or for the "x-goog-api-key" headers to be explicitly omitted')}async authHeaders(e){let t=n2([e.headers]);if(!(t.values.has("authorization")||t.values.has("x-goog-api-key"))){if(this.apiKey)return n2([{"x-goog-api-key":this.apiKey}]);if(this.clientAdapter.isVertexAI())return n2([await this.clientAdapter.getAuthHeaders()])}}stringifyQuery(e){return Object.entries(e).filter(([e,t])=>void 0!==t).map(([e,t])=>{if("string"==typeof t||"number"==typeof t||"boolean"==typeof t)return`${encodeURIComponent(e)}=${encodeURIComponent(t)}`;if(null===t)return`${encodeURIComponent(e)}=`;throw new no(`Cannot stringify type ${typeof t}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${nw}`}defaultIdempotencyKey(){return`stainless-node-retry-${nn()}`}makeStatusError(e,t,r,n){return na.generate(e,t,r,n)}buildURL(e,t,r){let n=!this.baseURLOverridden()&&r||this.baseURL,i=new URL(nE.test(e)?e:n+(n.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return!function(e){if(!e)return!0;for(let t in e)return!1;return!0}(s)&&(t=Object.assign(Object.assign({},s),t)),"object"==typeof t&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){if(this.clientAdapter&&this.clientAdapter.isVertexAI()&&!e.path.startsWith(`/${this.apiVersion}/projects/`)){let t=e.path.slice(this.apiVersion.length+1);e.path=`/${this.apiVersion}/projects/${this.clientAdapter.getProject()}/locations/${this.clientAdapter.getLocation()}${t}`}}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(r=>Object.assign({method:e,path:t},r)))}request(e,t=null){return new n0(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){var n,i,s;let o=await e,a=null!=(n=o.maxRetries)?n:this.maxRetries;null==t&&(t=a),await this.prepareOptions(o);let{req:l,url:u,timeout:c}=await this.buildRequest(o,{retryCount:a-t});await this.prepareRequest(l,{url:u,options:o});let d="log_"+(0x1000000*Math.random()|0).toString(16).padStart(6,"0"),h=void 0===r?"":`, retryOf: ${r}`,p=Date.now();if(nz(this).debug(`[${d}] sending request`,nY({retryOfRequestLogID:r,method:o.method,url:u,options:o,headers:l.headers})),null==(i=o.signal)?void 0:i.aborted)throw new nl;let f=new AbortController,m=await this.fetchWithTimeout(u,l,c,f).catch(ns),g=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(null==(s=o.signal)?void 0:s.aborted)throw new nl;let n=ni(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(t)return nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - ${e}`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (${e})`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),this.retryRequest(o,t,null!=r?r:d);if(nz(this).info(`[${d}] connection ${n?"timed out":"failed"} - error; no more retries left`),nz(this).debug(`[${d}] connection ${n?"timed out":"failed"} (error; no more retries left)`,nY({retryOfRequestLogID:r,url:u,durationMs:g-p,message:m.message})),n)throw new nc;throw new nu({cause:m})}let y=`[${d}${h}] ${l.method} ${u} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${g-p}ms`;if(!m.ok){let e=await this.shouldRetry(m);if(t&&e){let e=`retrying, ${t} attempts remaining`;return await nI(m.body),nz(this).info(`${y} - ${e}`),nz(this).debug(`[${d}] response error (${e})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),this.retryRequest(o,t,null!=r?r:d,m.headers)}let n=e?"error; no more retries left":"error; not retryable";nz(this).info(`${y} - ${n}`);let i=await m.text().catch(e=>ns(e).message),s=(e=>{try{return JSON.parse(e)}catch(e){return}})(i),a=s?void 0:i;throw nz(this).debug(`[${d}] response error (${n})`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:a,durationMs:Date.now()-p})),this.makeStatusError(m.status,s,a,m.headers)}return nz(this).info(y),nz(this).debug(`[${d}] response start`,nY({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:g-p})),{response:m,options:o,controller:f,requestLogID:d,retryOfRequestLogID:r,startTime:p}}async fetchWithTimeout(e,t,r,n){let i=t||{},{signal:s,method:o}=i,a=ry(i,["signal","method"]);s&&s.addEventListener("abort",()=>n.abort());let l=setTimeout(()=>n.abort(),r),u=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||"object"==typeof a.body&&null!==a.body&&Symbol.asyncIterator in a.body,c=Object.assign(Object.assign(Object.assign({signal:n.signal},u?{duplex:"half"}:{}),{method:"GET"}),a);o&&(c.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,c)}finally{clearTimeout(l)}}async shouldRetry(e){let t=e.headers.get("x-should-retry");return"true"===t||"false"!==t&&(408===e.status||409===e.status||429===e.status||!!(e.status>=500))}async retryRequest(e,t,r,n){var i;let s,o,a=null==n?void 0:n.get("retry-after-ms");if(a){let e=parseFloat(a);Number.isNaN(e)||(s=e)}let l=null==n?void 0:n.get("retry-after");if(l&&!s){let e=parseFloat(l);s=Number.isNaN(e)?Date.parse(l)-Date.now():1e3*e}if(!(s&&0<=s&&s<6e4)){let r=null!=(i=e.maxRetries)?i:this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,r)}return await (o=s,new Promise(e=>setTimeout(e,o))),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){return Math.min(.5*Math.pow(2,t-e),8)*(1-.25*Math.random())*1e3}async buildRequest(e,{retryCount:t=0}={}){var r,n,i;let s=Object.assign({},e),{method:o,path:a,query:l,defaultBaseURL:u}=s,c=this.buildURL(a,l,u);"timeout"in s&&((e,t)=>{if("number"!=typeof t||!Number.isInteger(t))throw new no(`${e} must be an integer`);if(t<0)throw new no(`${e} must be a positive integer`)})("timeout",s.timeout),s.timeout=null!=(r=s.timeout)?r:this.timeout;let{bodyHeaders:d,body:h}=this.buildBody({options:s}),p=await this.buildHeaders({options:e,method:o,bodyHeaders:d,retryCount:t});return{req:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({method:o,headers:p},s.signal&&{signal:s.signal}),globalThis.ReadableStream&&h instanceof globalThis.ReadableStream&&{duplex:"half"}),h&&{body:h}),null!=(n=this.fetchOptions)?n:{}),null!=(i=s.fetchOptions)?i:{}),url:c,timeout:s.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&"get"!==r&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=await this.authHeaders(e),a=n2([s,Object.assign(Object.assign({Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i)},e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{}),null!=t?t:t=(()=>{var e,t,r,n,i;let s="u">typeof Deno&&null!=Deno.build?"deno":"u">typeof EdgeRuntime?"edge":"[object process]"===Object.prototype.toString.call(void 0!==globalThis.process?globalThis.process:0)?"node":"unknown";if("deno"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(Deno.build.os),"X-Stainless-Arch":nA(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":"string"==typeof Deno.version?Deno.version:null!=(t=null==(e=Deno.version)?void 0:e.deno)?t:"unknown"};if("u">typeof EdgeRuntime)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if("node"===s)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":nS(null!=(r=globalThis.process.platform)?r:"unknown"),"X-Stainless-Arch":nA(null!=(n=globalThis.process.arch)?n:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":null!=(i=globalThis.process.version)?i:"unknown"};let o=function(){if("u"<typeof navigator||!navigator)return null;for(let{key:e,pattern:t}of[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}]){let r=t.exec(navigator.userAgent);if(r){let t=r[1]||0,n=r[2]||0,i=r[3]||0;return{browser:e,version:`${t}.${n}.${i}`}}}return null}();return o?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${o.browser}`,"X-Stainless-Runtime-Version":o.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nw,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}})()),this._options.defaultHeaders,n,e.headers,o]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){let r;if(!e)return{bodyHeaders:void 0,body:void 0};let n=n2([t]);if(ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||"string"==typeof e&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream)return{bodyHeaders:void 0,body:e};if("object"!=typeof e||!(Symbol.asyncIterator in e)&&(!(Symbol.iterator in e)||!("next"in e)||"function"!=typeof e.next))return this.encoder({body:e,headers:n});return{bodyHeaders:void 0,body:(r=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator](),nT({start(){},async pull(e){let{done:t,value:n}=await r.next();t?e.close():e.enqueue(n)},async cancel(){var e;await (null==(e=r.return)?void 0:e.call(r))}}))}}}n6.DEFAULT_TIMEOUT=6e4;class n3 extends n6{constructor(){super(...arguments),this.interactions=new nF(this)}}n3.GeminiNextGenAPIClient=n3,n3.GeminiNextGenAPIClientError=no,n3.APIError=na,n3.APIConnectionError=nu,n3.APIConnectionTimeoutError=nc,n3.APIUserAbortError=nl,n3.NotFoundError=nf,n3.ConflictError=nm,n3.RateLimitError=ny,n3.BadRequestError=nd,n3.AuthenticationError=nh,n3.InternalServerError=n_,n3.PermissionDeniedError=np,n3.UnprocessableEntityError=ng,n3.toFile=nN,n3.Interactions=nF;let n8="x-goog-api-key",n5="https://www.googleapis.com/auth/cloud-platform";class n9{constructor(e){if(void 0!==e.apiKey){this.apiKey=e.apiKey;return}const t=function(e){let t;if(!e)return{scopes:[n5]};if((t=e).scopes){if("string"==typeof t.scopes&&t.scopes!==n5||Array.isArray(t.scopes)&&0>t.scopes.indexOf(n5))throw Error(`Invalid auth scopes. Scopes must include: ${n5}`)}else t.scopes=[n5];return t}(e.googleAuthOptions);this.googleAuth=new tr.GoogleAuth(t)}async addAuthHeaders(e,t){if(void 0!==this.apiKey){if(this.apiKey.startsWith("auth_tokens/"))throw Error("Ephemeral tokens are only supported by the live API.");this.addKeyHeader(e);return}return this.addGoogleAuthHeaders(e,t)}addKeyHeader(e){if(null===e.get(n8)){if(void 0===this.apiKey)throw Error("Trying to set API key header but apiKey is not set");e.append(n8,this.apiKey)}}async addGoogleAuthHeaders(e,t){if(void 0===this.googleAuth)throw Error("Trying to set google-auth headers but googleAuth is unset");for(let[r,n]of(await this.googleAuth.getRequestHeaders(t)))null===e.get(r)&&e.append(r,n)}}class n7{async download(e,t){if(e.downloadPath){let r=await ie(e,t);if(r instanceof tm){let t=(0,tn.createWriteStream)(e.downloadPath);ts.Readable.fromWeb(r.responseInternal.body).pipe(t),await (0,to.finished)(t)}else try{await (0,ti.writeFile)(e.downloadPath,r,{encoding:"base64"})}catch(t){throw Error(`Failed to write file to ${e.downloadPath}: ${t}`)}}}}async function ie(e,t){var r,n,i;let s=rr(e.file);if(void 0!==s)return await t.request({path:`files/${s}:download`,httpMethod:"GET",queryParams:{alt:"media"},httpOptions:null==(r=e.config)?void 0:r.httpOptions,abortSignal:null==(n=e.config)?void 0:n.abortSignal});if(re(e.file)){let t=null==(i=e.file.video)?void 0:i.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download generated video, Uri or videoBytes not found.")}if(rt(e.file)){let t=e.file.videoBytes;if("string"==typeof t)return t;throw Error("Failed to download video, Uri or videoBytes not found.")}throw Error("Unsupported file type")}class it{create(e,t,r){return new ir(e,t,r)}}class ir{constructor(e,t,r){this.url=e,this.headers=t,this.callbacks=r}connect(){this.ws=new ta.default(this.url,{headers:this.headers}),this.ws.onopen=this.callbacks.onopen,this.ws.onerror=this.callbacks.onerror,this.ws.onclose=this.callbacks.onclose,this.ws.onmessage=this.callbacks.onmessage}send(e){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.send(e)}close(){if(void 0===this.ws)throw Error("WebSocket is not connected");this.ws.close()}}function ii(e,t){let r,n,i,s={},o=th(e,["sdkHttpResponse"]);null!=o&&td(s,["sdkHttpResponse"],o);let a=th(e,["name"]);null!=a&&td(s,["name"],a);let l=th(e,["state"]);null!=l&&td(s,["state"],t7(l));let u=th(e,["createTime"]);null!=u&&td(s,["createTime"],u);let c=th(e,["tuningTask","startTime"]);null!=c&&td(s,["startTime"],c);let d=th(e,["tuningTask","completeTime"]);null!=d&&td(s,["endTime"],d);let h=th(e,["updateTime"]);null!=h&&td(s,["updateTime"],h);let p=th(e,["description"]);null!=p&&td(s,["description"],p);let f=th(e,["baseModel"]);null!=f&&td(s,["baseModel"],f);let m=th(e,["_self"]);return null!=m&&td(s,["tunedModel"],(r={},null!=(n=th(m,["name"]))&&td(r,["model"],n),null!=(i=th(m,["name"]))&&td(r,["endpoint"],i),r)),s}function is(e,t){let r={},n=th(e,["sdkHttpResponse"]);null!=n&&td(r,["sdkHttpResponse"],n);let i=th(e,["name"]);null!=i&&td(r,["name"],i);let s=th(e,["state"]);null!=s&&td(r,["state"],t7(s));let o=th(e,["createTime"]);null!=o&&td(r,["createTime"],o);let a=th(e,["startTime"]);null!=a&&td(r,["startTime"],a);let l=th(e,["endTime"]);null!=l&&td(r,["endTime"],l);let u=th(e,["updateTime"]);null!=u&&td(r,["updateTime"],u);let c=th(e,["error"]);null!=c&&td(r,["error"],c);let d=th(e,["description"]);null!=d&&td(r,["description"],d);let h=th(e,["baseModel"]);null!=h&&td(r,["baseModel"],h);let p=th(e,["tunedModel"]);null!=p&&td(r,["tunedModel"],p);let f=th(e,["preTunedModel"]);null!=f&&td(r,["preTunedModel"],f);let m=th(e,["supervisedTuningSpec"]);null!=m&&td(r,["supervisedTuningSpec"],m);let g=th(e,["preferenceOptimizationSpec"]);null!=g&&td(r,["preferenceOptimizationSpec"],g);let y=th(e,["tuningDataStats"]);null!=y&&td(r,["tuningDataStats"],y);let _=th(e,["encryptionSpec"]);null!=_&&td(r,["encryptionSpec"],_);let E=th(e,["partnerModelTuningSpec"]);null!=E&&td(r,["partnerModelTuningSpec"],E);let v=th(e,["customBaseModel"]);null!=v&&td(r,["customBaseModel"],v);let b=th(e,["experiment"]);null!=b&&td(r,["experiment"],b);let w=th(e,["labels"]);null!=w&&td(r,["labels"],w);let A=th(e,["outputUri"]);null!=A&&td(r,["outputUri"],A);let S=th(e,["pipelineJob"]);null!=S&&td(r,["pipelineJob"],S);let T=th(e,["serviceAccount"]);null!=T&&td(r,["serviceAccount"],T);let O=th(e,["tunedModelDisplayName"]);null!=O&&td(r,["tunedModelDisplayName"],O);let I=th(e,["veoTuningSpec"]);return null!=I&&td(r,["veoTuningSpec"],I),r}function io(e,t){let r={},n=th(e,["gcsUri"]);null!=n&&td(r,["validationDatasetUri"],n);let i=th(e,["vertexDatasetResource"]);return null!=i&&td(r,["validationDatasetUri"],i),r}class ia extends tu{constructor(e){super(),this.apiClient=e,this.list=async(e={})=>new rp(tt.PAGED_ITEM_TUNING_JOBS,e=>this.listInternal(e),await this.listInternal(e),e),this.get=async e=>await this.getInternal(e),this.tune=async e=>{var t;if(this.apiClient.isVertexAI())if(e.baseModel.startsWith("projects/")){let r={tunedModelName:e.baseModel};(null==(t=e.config)?void 0:t.preTunedModelCheckpointId)&&(r.checkpointId=e.config.preTunedModelCheckpointId);let n=Object.assign(Object.assign({},e),{preTunedModel:r});return n.baseModel=void 0,await this.tuneInternal(n)}else{let t=Object.assign({},e);return await this.tuneInternal(t)}{let t=Object.assign({},e),r=await this.tuneMldevInternal(t),n="";return void 0!==r.metadata&&void 0!==r.metadata.tunedModel?n=r.metadata.tunedModel:void 0!==r.name&&r.name.includes("/operations/")&&(n=r.name.split("/operations/")[0]),{name:n,state:eN.JOB_STATE_QUEUED}}}}async getInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>ii(e))}}async listInternal(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a,l,u,c=(n={},null!=(i=th(e,["config"]))&&(a=th(i,["pageSize"]),void 0!==n&&null!=a&&td(n,["_query","pageSize"],a),l=th(i,["pageToken"]),void 0!==n&&null!=l&&td(n,["_query","pageToken"],l),u=th(i,["filter"]),void 0!==n&&null!=u&&td(n,["_query","filter"],u)),n);return s=tc("tuningJobs",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tuningJobs"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>is(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}{let t,r,a,l,u,c=(t={},null!=(r=th(e,["config"]))&&(a=th(r,["pageSize"]),void 0!==t&&null!=a&&td(t,["_query","pageSize"],a),l=th(r,["pageToken"]),void 0!==t&&null!=l&&td(t,["_query","pageToken"],l),u=th(r,["filter"]),void 0!==t&&null!=u&&td(t,["_query","filter"],u)),t);return s=tc("tunedModels",c._url),o=c._query,delete c._url,delete c._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(c),httpMethod:"GET",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t=function(e){let t={},r=th(e,["sdkHttpResponse"]);null!=r&&td(t,["sdkHttpResponse"],r);let n=th(e,["nextPageToken"]);null!=n&&td(t,["nextPageToken"],n);let i=th(e,["tunedModels"]);if(null!=i){let e=i;Array.isArray(e)&&(e=e.map(e=>ii(e))),td(t,["tuningJobs"],e)}return t}(e),r=new tC;return Object.assign(r,t),r})}}async cancel(e){var t,r,n,i;let s="",o={};if(this.apiClient.isVertexAI()){let n,i,a=(n={},null!=(i=th(e,["name"]))&&td(n,["_url","name"],i),n);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}{let t,r,a=(t={},null!=(r=th(e,["name"]))&&td(t,["_url","name"],r),t);return s=tc("{name}:cancel",a._url),o=a._query,delete a._url,delete a._query,this.apiClient.request({path:s,queryParams:o,body:JSON.stringify(a),httpMethod:"POST",httpOptions:null==(n=e.config)?void 0:n.httpOptions,abortSignal:null==(i=e.config)?void 0:i.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n=(t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),t),i=new tR;return Object.assign(i,n),i})}}async tuneInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI()){let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===n){let r=th(e,["gcsUri"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}let i=th(r,["config","method"]);if(void 0===i&&(i="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","trainingDatasetUri"],r)}else if("PREFERENCE_TUNING"===i){let r=th(e,["vertexDatasetResource"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","trainingDatasetUri"],r)}if(void 0!==th(e,["examples"]))throw Error("examples parameter is not supported in Vertex AI.")}(l,s,e),null!=(u=th(e,["config"]))&&function(e,t,r){let n=th(r,["config","method"]);if(void 0===n&&(n="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec"],io(r))}else if("PREFERENCE_TUNING"===n){let r=th(e,["validationDataset"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec"],io(r))}let i=th(e,["tunedModelDisplayName"]);void 0!==t&&null!=i&&td(t,["tunedModelDisplayName"],i);let s=th(e,["description"]);void 0!==t&&null!=s&&td(t,["description"],s);let o=th(r,["config","method"]);if(void 0===o&&(o="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","epochCount"],r)}else if("PREFERENCE_TUNING"===o){let r=th(e,["epochCount"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","epochCount"],r)}let a=th(r,["config","method"]);if(void 0===a&&(a="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","learningRateMultiplier"],r)}else if("PREFERENCE_TUNING"===a){let r=th(e,["learningRateMultiplier"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","learningRateMultiplier"],r)}let l=th(r,["config","method"]);if(void 0===l&&(l="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","exportLastCheckpointOnly"],r)}else if("PREFERENCE_TUNING"===l){let r=th(e,["exportLastCheckpointOnly"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","exportLastCheckpointOnly"],r)}let u=th(r,["config","method"]);if(void 0===u&&(u="SUPERVISED_FINE_TUNING"),"SUPERVISED_FINE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["supervisedTuningSpec","hyperParameters","adapterSize"],r)}else if("PREFERENCE_TUNING"===u){let r=th(e,["adapterSize"]);void 0!==t&&null!=r&&td(t,["preferenceOptimizationSpec","hyperParameters","adapterSize"],r)}if(void 0!==th(e,["batchSize"]))throw Error("batchSize parameter is not supported in Vertex AI.");if(void 0!==th(e,["learningRate"]))throw Error("learningRate parameter is not supported in Vertex AI.");let c=th(e,["labels"]);void 0!==t&&null!=c&&td(t,["labels"],c);let d=th(e,["beta"]);void 0!==t&&null!=d&&td(t,["preferenceOptimizationSpec","hyperParameters","beta"],d)}(u,s,e),s);return n=tc("tuningJobs",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>is(e))}throw Error("This method is only supported by the Vertex AI.")}async tuneMldevInternal(e){var t,r;let n="",i={};if(this.apiClient.isVertexAI())throw Error("This method is only supported by the Gemini Developer API.");{let s,o,a,l,u,c=(s={},null!=(o=th(e,["baseModel"]))&&td(s,["baseModel"],o),null!=(a=th(e,["preTunedModel"]))&&td(s,["preTunedModel"],a),null!=(l=th(e,["trainingDataset"]))&&function(e){if(void 0!==th(e,["gcsUri"]))throw Error("gcsUri parameter is not supported in Gemini API.");if(void 0!==th(e,["vertexDatasetResource"]))throw Error("vertexDatasetResource parameter is not supported in Gemini API.");let t=th(e,["examples"]);if(null!=t){let e=t;Array.isArray(e)&&(e=e.map(e=>e)),td({},["examples","examples"],e)}}(l),null!=(u=th(e,["config"]))&&function(e,t){if(void 0!==th(e,["validationDataset"]))throw Error("validationDataset parameter is not supported in Gemini API.");let r=th(e,["tunedModelDisplayName"]);if(void 0!==t&&null!=r&&td(t,["displayName"],r),void 0!==th(e,["description"]))throw Error("description parameter is not supported in Gemini API.");let n=th(e,["epochCount"]);void 0!==t&&null!=n&&td(t,["tuningTask","hyperparameters","epochCount"],n);let i=th(e,["learningRateMultiplier"]);if(null!=i&&td({},["tuningTask","hyperparameters","learningRateMultiplier"],i),void 0!==th(e,["exportLastCheckpointOnly"]))throw Error("exportLastCheckpointOnly parameter is not supported in Gemini API.");if(void 0!==th(e,["preTunedModelCheckpointId"]))throw Error("preTunedModelCheckpointId parameter is not supported in Gemini API.");if(void 0!==th(e,["adapterSize"]))throw Error("adapterSize parameter is not supported in Gemini API.");let s=th(e,["batchSize"]);void 0!==t&&null!=s&&td(t,["tuningTask","hyperparameters","batchSize"],s);let o=th(e,["learningRate"]);if(void 0!==t&&null!=o&&td(t,["tuningTask","hyperparameters","learningRate"],o),void 0!==th(e,["labels"]))throw Error("labels parameter is not supported in Gemini API.");if(void 0!==th(e,["beta"]))throw Error("beta parameter is not supported in Gemini API.")}(u,s),s);return n=tc("tunedModels",c._url),i=c._query,delete c._url,delete c._query,this.apiClient.request({path:n,queryParams:i,body:JSON.stringify(c),httpMethod:"POST",httpOptions:null==(t=e.config)?void 0:t.httpOptions,abortSignal:null==(r=e.config)?void 0:r.abortSignal}).then(e=>e.json().then(t=>(t.sdkHttpResponse={headers:e.headers},t))).then(e=>{let t,r,n,i,s,o;return t={},null!=(r=th(e,["sdkHttpResponse"]))&&td(t,["sdkHttpResponse"],r),null!=(n=th(e,["name"]))&&td(t,["name"],n),null!=(i=th(e,["metadata"]))&&td(t,["metadata"],i),null!=(s=th(e,["done"]))&&td(t,["done"],s),null!=(o=th(e,["error"]))&&td(t,["error"],o),t})}}}let il="x-goog-upload-status";async function iu(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async function ic(e,t,r){var n;let i=await id(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async function id(e,t,r){var n,i;let s=0,o=0,a=new tm(new Response),l="upload";for(s=e.size;o<s;){let u=Math.min(8388608,s-o),c=e.slice(o,o+u);o+u>=s&&(l+=", finalize");let d=0,h=1e3;for(;d<3&&(null==(n=null==(a=await r.request({path:"",body:c,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":l,"X-Goog-Upload-Offset":String(o),"Content-Length":String(u)}}}))?void 0:a.headers)||!n[il]);)d++,await ip(h),h*=2;if(o+=u,(null==(i=null==a?void 0:a.headers)?void 0:i[il])!=="active")break;if(s<=o)throw Error("All content has been uploaded, but the upload status is not finalized.")}return a}async function ih(e){return{size:e.size,type:e.type}}function ip(e){return new Promise(t=>setTimeout(t,e))}class im{async stat(e){let t={size:0,type:void 0};return"string"==typeof e?(t.size=(await ti.stat(e)).size,t.type=this.inferMimeType(e),t):await ih(e)}async upload(e,t,r){return"string"==typeof e?await this.uploadFileFromPath(e,t,r):iu(e,t,r)}async uploadToFileSearchStore(e,t,r){return"string"==typeof e?await this.uploadFileToFileSearchStoreFromPath(e,t,r):ic(e,t,r)}inferMimeType(e){return({aac:"audio/aac",abw:"application/x-abiword",arc:"application/x-freearc",avi:"video/x-msvideo",azw:"application/vnd.amazon.ebook",bin:"application/octet-stream",bmp:"image/bmp",bz:"application/x-bzip",bz2:"application/x-bzip2",csh:"application/x-csh",css:"text/css",csv:"text/csv",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",eot:"application/vnd.ms-fontobject",epub:"application/epub+zip",gz:"application/gzip",gif:"image/gif",htm:"text/html",html:"text/html",ico:"image/vnd.microsoft.icon",ics:"text/calendar",jar:"application/java-archive",jpeg:"image/jpeg",jpg:"image/jpeg",js:"text/javascript",json:"application/json",jsonld:"application/ld+json",kml:"application/vnd.google-earth.kml+xml",kmz:"application/vnd.google-earth.kmz+xml",mjs:"text/javascript",mp3:"audio/mpeg",mp4:"video/mp4",mpeg:"video/mpeg",mpkg:"application/vnd.apple.installer+xml",odt:"application/vnd.oasis.opendocument.text",oga:"audio/ogg",ogv:"video/ogg",ogx:"application/ogg",opus:"audio/opus",otf:"font/otf",png:"image/png",pdf:"application/pdf",php:"application/x-httpd-php",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",rar:"application/vnd.rar",rtf:"application/rtf",sh:"application/x-sh",svg:"image/svg+xml",swf:"application/x-shockwave-flash",tar:"application/x-tar",tif:"image/tiff",tiff:"image/tiff",ts:"video/mp2t",ttf:"font/ttf",txt:"text/plain",vsd:"application/vnd.visio",wav:"audio/wav",weba:"audio/webm",webm:"video/webm",webp:"image/webp",woff:"font/woff",woff2:"font/woff2",xhtml:"application/xhtml+xml",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",xml:"application/xml",xul:"application/vnd.mozilla.xul+xml",zip:"application/zip","3gp":"video/3gpp","3g2":"video/3gpp2","7z":"application/x-7z-compressed"})[e.slice(e.lastIndexOf(".")+1).toLowerCase()]}async uploadFileFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");return s.file}async uploadFileToFileSearchStoreFromPath(e,t,r){var n;let i=await this.uploadFileFromPathInternal(e,t,r),s=await (null==i?void 0:i.json());if((null==(n=null==i?void 0:i.headers)?void 0:n[il])!=="final")throw Error("Failed to upload file: Upload status is not finalized.");let o=tf(s),a=new t$;return Object.assign(a,o),a}async uploadFileFromPathInternal(e,t,r){var n,i;let s,o=0,a=0,l=new tm(new Response),u="upload",c=tl.basename(e);try{if(!(s=await ti.open(e,"r")))throw Error("Failed to open file");for(o=(await s.stat()).size;a<o;){let e=Math.min(8388608,o-a);a+e>=o&&(u+=", finalize");let d=new Uint8Array(e),{bytesRead:h}=await s.read(d,0,e,a);if(h!==e)throw Error(`Failed to read ${e} bytes from file at offset ${a}. bytes actually read: ${h}`);let p=new Blob([d]),f=0,m=1e3;for(;f<3&&(null==(n=null==(l=await r.request({path:"",body:p,httpMethod:"POST",httpOptions:{apiVersion:"",baseUrl:t,headers:{"X-Goog-Upload-Command":u,"X-Goog-Upload-Offset":String(a),"Content-Length":String(h),"X-Goog-Upload-File-Name":c}}}))?void 0:l.headers)||!n[il]);)f++,await ip(m),m*=2;if(a+=h,(null==(i=null==l?void 0:l.headers)?void 0:i[il])!=="active")break;if(o<=a)throw Error("All content has been uploaded, but the upload status is not finalized.")}return l}finally{s&&await s.close()}}}class ig{get interactions(){if(void 0!==this._interactions)return this._interactions;console.warn("GoogleGenAI.interactions: Interactions usage is experimental and may change in future versions.");let e=this.httpOptions;(null==e?void 0:e.extraBody)&&console.warn("GoogleGenAI.interactions: Client level httpOptions.extraBody is not supported by the interactions client and will be ignored.");let t=new n3({baseURL:this.apiClient.getBaseUrl(),apiKey:this.apiKey,apiVersion:this.apiClient.getApiVersion(),clientAdapter:this.apiClient,defaultHeaders:this.apiClient.getDefaultHeaders(),timeout:null==e?void 0:e.timeout});return this._interactions=t.interactions,this._interactions}constructor(e){var t,r,n,o,a,l;if((e.project||e.location)&&e.apiKey)throw Error("Project/location and API key are mutually exclusive in the client initializer.");this.vertexai=null!=(r=null!=(t=e.vertexai)?t:function(e){var t;return void 0!==(t=iy(e))&&"true"===t.toLowerCase()}("GOOGLE_GENAI_USE_VERTEXAI"))&&r;const u=function(){let e=iy("GOOGLE_API_KEY"),t=iy("GEMINI_API_KEY");return e&&t&&console.warn("Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY."),e||t||void 0}(),c=iy("GOOGLE_CLOUD_PROJECT"),d=iy("GOOGLE_CLOUD_LOCATION");this.apiKey=null!=(n=e.apiKey)?n:u,this.project=null!=(o=e.project)?o:c,this.location=null!=(a=e.location)?a:d,e.vertexai&&((null==(l=e.googleAuthOptions)?void 0:l.credentials)&&(console.debug("The user provided Google Cloud credentials will take precedence over the API key from the environment variable."),this.apiKey=void 0),(c||d)&&e.apiKey?(console.debug("The user provided Vertex AI API key will take precedence over the project/location from the environment variables."),this.project=void 0,this.location=void 0):(e.project||e.location)&&u?(console.debug("The user provided project/location will take precedence over the API key from the environment variables."),this.apiKey=void 0):(c||d)&&u&&(console.debug("The project/location from the environment variables will take precedence over the API key from the environment variables."),this.apiKey=void 0),this.location||this.apiKey||(this.location="global"));const h=function(e,t,r,n){return(null==e?void 0:e.baseUrl)?e.baseUrl:t?null!=s?s:r:null!=i?i:n}(e.httpOptions,e.vertexai,iy("GOOGLE_VERTEX_BASE_URL"),iy("GOOGLE_GEMINI_BASE_URL"));h&&(e.httpOptions?e.httpOptions.baseUrl=h:e.httpOptions={baseUrl:h}),this.apiVersion=e.apiVersion,this.httpOptions=e.httpOptions;const p=new n9({apiKey:this.apiKey,googleAuthOptions:e.googleAuthOptions});this.apiClient=new rJ({auth:p,project:this.project,location:this.location,apiVersion:this.apiVersion,apiKey:this.apiKey,vertexai:this.vertexai,httpOptions:this.httpOptions,userAgentExtra:"gl-node/"+process.version,uploader:new im,downloader:new n7}),this.models=new r9(this.apiClient),this.live=new r1(this.apiClient,p,new it),this.batches=new rf(this.apiClient),this.chats=new rA(this.models,this.apiClient),this.caches=new rg(this.apiClient),this.files=new rO(this.apiClient),this.operations=new r7(this.apiClient),this.authTokens=new ne(this.apiClient),this.tunings=new ia(this.apiClient),this.fileSearchStores=new nr(this.apiClient)}}function iy(e){var t,r,n;return null!=(n=null==(r=null==(t=null==process?void 0:process.env)?void 0:t[e])?void 0:r.trim())?n:void 0}var i_=e.i(5898),iE=e.i(61829),iv=e.i(83598),ib=e.i(99617),iw=e.i(98003),iA=e.i(59398),iS=e.i(50377),iT=e.i(93716),iO=e.i(30166),iI=e.i(15851);let iC=(0,iS.createLogger)("ai:gemini");e.s(["GeminiProvider",0,class{ai;modelName;baseUrl;constructor(e){const t=e?.apiKey,r=e?.baseUrl;if(!t)throw Error("AI_AUTH_ERROR: GOOGLE_API_KEY is required for Gemini provider");this.ai=new ig({apiKey:t,httpOptions:r?{baseUrl:r}:void 0}),this.modelName=e?.model||"gemini-2.0-flash",this.baseUrl=r||"https://generativelanguage.googleapis.com",iC.info({provider:"Gemini",model:this.modelName,baseUrl:this.baseUrl,apiKeyPrefix:t.substring(0,8)+"..."},"AI Provider initialized")}async retryOperation(e,t=3){let r;for(let n=1;n<=t;n++)try{return await e()}catch(s){r=s;let e=s instanceof Error?s.message.toLowerCase():String(s);if(!(e.includes("fetch failed")||e.includes("network")||e.includes("connect")||e.includes("503")||e.includes("502")||e.includes("504")||e.includes("overloaded")||e.includes("timeout")||e.includes("etimedout")||e.includes("enotfound")||e.includes("econnreset")||e.includes("econnrefused")||e.includes("unavailable"))||n===t)throw s;let i=1e3*Math.pow(2,n-1);iC.warn({attempt:n,maxRetries:t,error:e,nextRetryDelayMs:i},"Gemini operation failed, retrying..."),await new Promise(e=>setTimeout(e,i))}throw r}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r),s=e.lastIndexOf(n);return -1===i||-1===s||i>=s?null:e.substring(i+r.length,s).trim()}parseResponse(e){iC.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),o=this.extractTag(e,"requires_image"),a=this.extractTag(e,"wrong_answer_text")||"",l=this.extractTag(e,"mistake_analysis")||"",u=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw iC.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let c="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(c=i);let d=[];s&&(d=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let h=o?.toLowerCase().trim()==="true",p=(0,iO.normalizeMistakeStatusForSave)(u,a),f={questionText:t,answerText:r,analysis:n,wrongAnswerText:a,mistakeAnalysis:l,mistakeStatus:p,subject:c,knowledgePoints:d,requiresImage:h,difficultyStars:(0,ib.parseDifficultyStars)(this.extractTag(e,"difficulty_stars")),...(0,ib.parseFigure)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},m=(0,ib.safeParseParsedQuestion)(f);return m.success?(iC.debug("Validated successfully via XML tags"),m.data):(iC.warn({validationError:m.error.format()},"Schema validation warning"),f)}async analyzeImage(e,t="image/jpeg",r="zh",n,i,s,o){let a=(0,iw.getAppConfig)(),l=o?{candidateTags:o}:await (0,iA.prefetchSubjectTags)(i,n),u=(0,i_.generateAnalyzePrompt)(r,n,i,{customTemplate:a.prompts?.analyze,...l},s);iC.box("🔍 AI Image Analysis Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,imageSize:`${e.length} bytes`,mimeType:t,model:this.modelName,language:r,grade:n||"all"}),iC.box("📝 Full Prompt",u);try{let r={model:this.modelName,contents:[{text:u},{inlineData:{data:`[...${e.length} bytes base64 data...]`,mimeType:t}}]};iC.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(r,null,2));let n=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:u},{inlineData:{data:e,mimeType:t}}]}));iC.box("📦 Full API Response Metadata",{usageMetadata:n.usageMetadata});let i=n.text||"";if(iC.box("🤖 AI Raw Response",i),!i)throw Error(n.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let s=this.parseResponse(i);return iC.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw iC.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,r="zh",n="medium",i,s){let o=(0,iw.getAppConfig)(),a=(0,i_.generateSimilarQuestionPrompt)(r,e,t,n,{customTemplate:o.prompts?.similar,originalFigureSvg:s},i);iC.box("🎯 Generate Similar Question Request",{provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:n,language:r}),iC.box("📝 Full Prompt",a);try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:a})),t=e.text||"";if(iC.box("🤖 AI Raw Response",t),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let r=this.parseResponse(t);return iC.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,iI.normalizeGeneratedQuestion)(r)}catch(e){throw iC.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,o){let{generateReanswerPrompt:a}=await e.A(30249),l=a(r,t,n,{candidateTags:o},s);iC.info({provider:"Gemini",endpoint:`${this.baseUrl}/v1beta/models/${this.modelName}:generateContent`,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),iC.debug({prompt:l},"Full prompt");try{let e;if(i){let t=i.replace(/^data:image\/\w+;base64,/,"");e=[{text:l},{inlineData:{mimeType:"image/jpeg",data:t}}]}else e=l;let t=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:e})),r=t.text||"";if(iC.debug({rawResponse:r},"AI raw response"),!r)throw Error(t.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let n=this.extractTag(r,"answer_text")||"",s=this.extractTag(r,"analysis")||"",o=(this.extractTag(r,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),a=this.extractTag(r,"wrong_answer_text")||"",u=this.extractTag(r,"mistake_analysis")||"",c=(0,iO.normalizeMistakeStatusForSave)(this.extractTag(r,"mistake_status"),a);return iC.info("Reanswer parsed successfully"),{answerText:n,analysis:s,knowledgePoints:o,wrongAnswerText:a,mistakeAnalysis:u,mistakeStatus:c,subject:(0,ib.normalizeSubject)(this.extractTag(r,"subject")),difficultyStars:(0,ib.parseDifficultyStars)(this.extractTag(r,"difficulty_stars"))}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,r,n){let i=(0,i_.generateGeogebraPrompt)(e,t,r,n);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:i})),t=e.text||"";if(iC.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let s=r.indexOf("{"),o=r.lastIndexOf("}");-1!==s&&-1!==o&&(r=r.substring(s,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,i_.generateMasteryPrompt)(e);iC.info({provider:"Gemini",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),r=e.text||"";if(iC.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseMasteryEvaluation)(r)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,i_.generateTagSuggestPrompt)(e);iC.info({provider:"Gemini",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:t})),n=r.text||"";if(iC.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseTagSuggestion)(n,e.allowedTags)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,r){let n=(0,i_.generateFigurePrompt)(r);iC.info({provider:"Gemini",model:this.modelName,imageSize:e.length},"Figure SVG Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:n},{inlineData:{data:e,mimeType:t}}]})),i=r.text||"";if(iC.debug({rawResponse:i},"Figure SVG AI raw response"),!i)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,ib.parseFigure)(this.extractTag(i,"has_figure"),this.extractTag(i,"figure_svg"))}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,i_.generateLatexFixPrompt)(e);iC.info({provider:"Gemini",model:this.modelName,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:t},{text:"请修复上述内容中的 LaTeX 语法。"}]})),n=r.text||"";if(iC.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error(r.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,iv.parseLatexFix)(n,e)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,r,n){let i=(0,i_.generateSvgAnimationPrompt)(e,t,r,n);iC.info({provider:"Gemini",model:this.modelName,questionLength:e.length},"SVG Animation Request");try{let e=await this.retryOperation(()=>this.ai.models.generateContent({model:this.modelName,contents:[{text:i},{text:"请为上述题目制作 SVG 动画讲解。"}]})),t=e.text||"";if(iC.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error(e.candidates?.[0]?.finishReason==="MAX_TOKENS"?iT.AI_OUTPUT_TRUNCATED:"Empty response from AI");return(0,iE.sanitizeSvgAnimation)(this.extractTag(t,"svg_animation")||t)}catch(e){throw iC.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(iC.error({error:e},"Gemini error"),e instanceof Error){if(e.message===iT.AI_OUTPUT_TRUNCATED||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],93963)},92938,e=>{"use strict";e.i(89228);var t=e.i(88045),t=t,r=e.i(5898),n=e.i(61829),i=e.i(83598),s=e.i(98003),o=e.i(99617),a=e.i(59398),l=e.i(50377),u=e.i(93716),c=e.i(30166),d=e.i(15851);let h=(0,l.createLogger)("ai:openai"),p="gpt-6.1-sol";e.s(["DEFAULT_OPENAI_MODEL",0,p,"OpenAIProvider",0,class{openai;model;baseURL;apiKey;isLongCat;constructor(e){const r=e?.apiKey,n=e?.baseUrl;if(!r)throw Error("AI_AUTH_ERROR: OPENAI_API_KEY is required for OpenAI provider");this.openai=new t.OpenAI({apiKey:r,baseURL:n||void 0,defaultHeaders:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36"}}),this.model=e?.model||p,this.baseURL=n||"https://api.openai.com/v1",this.apiKey=r,this.isLongCat=this.baseURL.includes("longcat.chat"),h.info({provider:"OpenAI",model:this.model,baseURL:this.baseURL,apiKeyPrefix:r.substring(0,8)+"..."},"AI Provider initialized")}adaptMessagesForLongCat(e){return e.map(e=>{if("string"==typeof e.content)return{...e,content:[{type:"text",text:e.content}]};if(Array.isArray(e.content)){let t=e.content.map(e=>"image_url"===e.type?{type:"input_image",input_image:{data:[e.image_url.url],type:"url"}}:e);return{...e,content:t}}return e})}extractTag(e,t){let r=`<${t}>`,n=`</${t}>`,i=e.indexOf(r);if(-1===i)return null;let s=i+r.length,o=e.lastIndexOf(n);return -1===o&&"analysis"===t?(h.warn({tagName:t},"Tag was verified unclosed, treating as truncated and reading to end"),e.substring(s).trim()):-1===o||s>=o?null:e.substring(s,o).trim()}parseResponse(e){h.debug({textLength:e.length},"Parsing AI response");let t=this.extractTag(e,"question_text"),r=this.extractTag(e,"answer_text"),n=this.extractTag(e,"analysis"),i=this.extractTag(e,"subject"),s=this.extractTag(e,"knowledge_points"),a=this.extractTag(e,"requires_image"),l=this.extractTag(e,"wrong_answer_text")||"",u=this.extractTag(e,"mistake_analysis")||"",d=this.extractTag(e,"mistake_status");if(!t||!r||!n)throw h.error({rawTextSample:e.substring(0,500)},"Missing critical XML tags"),Error("Invalid AI response: Missing critical XML tags (<question_text>, <answer_text>, or <analysis>)");let p="其他";i&&["数学","物理","化学","生物","英语","语文","历史","地理","政治","其他"].includes(i)&&(p=i);let f=[];s&&(f=s.split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0));let m=a?.toLowerCase().trim()==="true",g=(0,c.normalizeMistakeStatusForSave)(d,l),y={questionText:t,answerText:r,analysis:n,wrongAnswerText:l,mistakeAnalysis:u,mistakeStatus:g,subject:p,knowledgePoints:f,requiresImage:m,difficultyStars:(0,o.parseDifficultyStars)(this.extractTag(e,"difficulty_stars")),...(0,o.parseFigure)(this.extractTag(e,"has_figure"),this.extractTag(e,"figure_svg"))},_=(0,o.safeParseParsedQuestion)(y);return _.success?(h.debug("Validated successfully via XML tags"),_.data):(h.warn({validationError:_.error.format()},"Schema validation warning"),y)}async analyzeImage(e,t="image/jpeg",n="zh",i,o,l,c){let d=(0,s.getAppConfig)(),p=c?{candidateTags:c}:await (0,a.prefetchSubjectTags)(o,i),f=(0,r.generateAnalyzePrompt)(n,i,o,{customTemplate:d.prompts?.analyze,...p},l);h.box("🔍 AI Image Analysis Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,imageSize:`${e.length} bytes`,mimeType:t,model:this.model,language:n,grade:i||"all"}),h.box("📝 Full System Prompt",f);try{let r,n={model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,[...${e.length} bytes base64 data...]`}}]}],max_tokens:8192};if(h.box("📤 API Request (发送给 AI 的原始请求)",JSON.stringify(n,null,2)),this.isLongCat){let n=this.adaptMessagesForLongCat([{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}]),i=await fetch(`${this.baseURL}/chat/completions`,{method:"POST",headers:{Authorization:`Bearer ${this.apiKey}`,"Content-Type":"application/json"},body:JSON.stringify({model:this.model,messages:n,max_tokens:8192})});if(!i.ok){let e=await i.text();throw h.error({status:i.status,body:e},"LongCat API error"),Error(`${i.status} status code (${e})`)}r=await i.json()}else r=await (0,u.withTruncationRetry)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:f},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.box("📦 Full API Response",JSON.stringify(r,null,2)),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let i=r.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",i),!i)throw Error("Empty response from AI");let s=this.parseResponse(i);return h.box("✅ Parsed & Validated Result",JSON.stringify(s,null,2)),s}catch(e){throw h.box("❌ Error during AI analysis",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async generateSimilarQuestion(e,t,n="zh",i="medium",o,a){let l=(0,s.getAppConfig)(),c=(0,r.generateSimilarQuestionPrompt)(n,e,t,i,{customTemplate:l.prompts?.similar,originalFigureSvg:a},o),p=`
|
|
28
28
|
Original Question: "${e}"
|
|
29
29
|
Knowledge Points: ${t.join(", ")}
|
|
30
30
|
`;h.box("🎯 Generate Similar Question Request",{provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,originalQuestion:e.substring(0,100)+"...",knowledgePoints:t.join(", "),difficulty:i,language:n}),h.box("📝 System Prompt",c),h.box("📝 User Prompt",p);try{let e=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:c},{role:"user",content:p}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.box("🤖 AI Raw Response",t),!t)throw Error("Empty response from AI");let r=this.parseResponse(t);return h.box("✅ Parsed & Validated Result",JSON.stringify(r,null,2)),(0,d.normalizeGeneratedQuestion)(r)}catch(e){throw h.box("❌ Error during question generation",{error:e instanceof Error?e.message:String(e),stack:e instanceof Error?e.stack:void 0}),this.handleError(e),e}}async reanswerQuestion(t,r="zh",n,i,s,a){let{generateReanswerPrompt:l}=await e.A(30249),d=l(r,t,n,{candidateTags:a},s);h.info({provider:"OpenAI",endpoint:`${this.baseURL}/chat/completions`,model:this.model,questionLength:t.length,subject:n||"auto",hasImage:!!i},"Reanswer Question Request"),h.debug({prompt:d},"Full prompt");try{let e="请根据上述题目提供答案和解析。";if(i){let t=i.startsWith("data:")?i:`data:image/jpeg;base64,${i}`;h.debug({imageLength:t.length},"Image added to request"),e=[{type:"text",text:"请结合图片和题目描述提供答案和解析。"},{type:"image_url",image_url:{url:t}}]}else h.debug({imageBase64Type:typeof i,hasValue:!!i},"No image data");let t={model:this.model,messages:[{role:"system",content:d.substring(0,200)+"..."},{role:"user",content:"string"==typeof e?e:"[包含图片的多模态消息]"}],max_tokens:8192};h.debug({requestParams:t},"Request parameters");let r=await (0,u.withTruncationRetry)(t=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:d},{role:"user",content:e}],max_tokens:t}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens"));if(h.debug({response:JSON.stringify(r)},"Full API response"),!r||!r.choices||0===r.choices.length)throw h.error({response:JSON.stringify(r)},"Invalid API response - no choices array"),Error("AI_RESPONSE_ERROR: API returned empty or invalid response");let n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"AI raw response"),!n)throw Error("Empty response from AI");let s=this.extractTag(n,"answer_text")||"",a=this.extractTag(n,"analysis")||"",l=(this.extractTag(n,"knowledge_points")||"").split(/[,,\n]/).map(e=>e.trim()).filter(e=>e.length>0),p=this.extractTag(n,"wrong_answer_text")||"",f=this.extractTag(n,"mistake_analysis")||"",m=(0,c.normalizeMistakeStatusForSave)(this.extractTag(n,"mistake_status"),p);return h.info("Reanswer parsed successfully"),{answerText:s,analysis:a,knowledgePoints:l,wrongAnswerText:p,mistakeAnalysis:f,mistakeStatus:m,subject:(0,o.normalizeSubject)(this.extractTag(n,"subject")),difficultyStars:(0,o.parseDifficultyStars)(this.extractTag(n,"difficulty_stars"))}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during reanswer"),this.handleError(e),e}}async analyzeForGeogebra(e,t,n,i){let s=(0,r.generateGeogebraPrompt)(e,t,n,i);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"GeoGebra Analysis Request");try{let e=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:s},{role:"user",content:"请分析上述题目并生成 GeoGebra 演示命令。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"GeoGebra AI raw response"),!t)throw Error("Empty response from AI");let r=t.trim(),n=r.match(/```(?:json)?\s*([\s\S]*?)```/);n&&(r=n[1].trim());let i=r.indexOf("{"),o=r.lastIndexOf("}");-1!==i&&-1!==o&&(r=r.substring(i,o+1));let a=JSON.parse(r);return{suitable:!!a.suitable,commands:Array.isArray(a.commands)?a.commands:[],description:a.description||""}}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during GeoGebra analysis"),this.handleError(e),e}}async evaluateMastery(e){let t=(0,r.generateMasteryPrompt)(e);h.info({provider:"OpenAI",historyCount:e.history.length},"Mastery Evaluation Request");try{let e=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请根据上述练习历史给出掌握概率评估。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),r=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:r},"Mastery AI raw response"),!r)throw Error("Empty response from AI");return(0,o.parseMasteryEvaluation)(r)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during mastery evaluation"),this.handleError(e),e}}async suggestKnowledgeTags(e){let t=(0,r.generateTagSuggestPrompt)(e);h.info({provider:"OpenAI",subject:e.subject,allowedTagCount:e.allowedTags.length},"Tag Suggestion Request");try{let r=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请为上述题目选择知识点。"}],max_tokens:e}),4096,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Tag suggestion AI raw response"),!n)throw Error("Empty response from AI");return(0,o.parseTagSuggestion)(n,e.allowedTags)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during tag suggestion"),this.handleError(e),e}}async generateFigureSvg(e,t,n){let i=(0,r.generateFigurePrompt)(n);h.info({provider:"OpenAI",model:this.model,imageSize:e.length},"Figure SVG Request");try{let r=await (0,u.withTruncationRetry)(r=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:i},{role:"user",content:[{type:"image_url",image_url:{url:`data:${t};base64,${e}`}}]}],max_tokens:r}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"Figure SVG AI raw response"),!n)throw Error("Empty response from AI");return(0,o.parseFigure)(this.extractTag(n,"has_figure"),this.extractTag(n,"figure_svg"))}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during figure SVG generation"),this.handleError(e),e}}async fixLatex(e){let t=(0,r.generateLatexFixPrompt)(e);h.info({provider:"OpenAI",model:this.model,fields:Object.keys(e)},"LaTeX Fix Request");try{let r=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:t},{role:"user",content:"请修复上述内容中的 LaTeX 语法。"}],max_tokens:e}),8192,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),n=r.choices[0]?.message?.content||"";if(h.debug({rawResponse:n},"LaTeX fix AI raw response"),!n)throw Error("Empty response from AI");return(0,i.parseLatexFix)(n,e)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during LaTeX fix"),this.handleError(e),e}}async generateSvgAnimation(e,t,i,s){let o=(0,r.generateSvgAnimationPrompt)(e,t,i,s);h.info({provider:"OpenAI",model:this.model,questionLength:e.length},"SVG Animation Request");try{let e=await (0,u.withTruncationRetry)(e=>this.openai.chat.completions.create({model:this.model,messages:[{role:"system",content:o},{role:"user",content:"请为上述题目制作 SVG 动画讲解。"}],max_tokens:e}),16384,()=>h.warn("Output truncated by reasoning, retrying with larger max_tokens")),t=e.choices[0]?.message?.content||"";if(h.debug({rawResponse:t},"SVG animation AI raw response"),!t)throw Error("Empty response from AI");return(0,n.sanitizeSvgAnimation)(this.extractTag(t,"svg_animation")||t)}catch(e){throw h.error({error:e,stack:e instanceof Error?e.stack:void 0},"Error during SVG animation generation"),this.handleError(e),e}}handleError(e){if(h.error({error:e},"OpenAI error"),e instanceof Error){if(e.message===u.AI_OUTPUT_TRUNCATED||e.message.startsWith("AI_RESPONSE_ERROR:"))throw e;let t=e.message.toLowerCase();if(t.includes("fetch failed")||t.includes("network")||t.includes("connect"))throw Error("AI_CONNECTION_FAILED");if(t.includes("timeout")||t.includes("timed out")||t.includes("aborted")||t.includes("408"))throw Error("AI_TIMEOUT_ERROR");if(t.includes("quota")||t.includes("额度")||t.includes("rate limit")||t.includes("429")||t.includes("too many"))throw Error("AI_QUOTA_EXCEEDED");if(t.includes("403")||t.includes("forbidden")||t.includes("permission"))throw Error("AI_PERMISSION_DENIED");if(t.includes("404")||t.includes("not found")||t.includes("does not exist"))throw Error("AI_NOT_FOUND");if(t.includes("500")||t.includes("502")||t.includes("503")||t.includes("504")||t.includes("无可用")||t.includes("overloaded")||t.includes("unavailable"))throw Error("AI_SERVICE_UNAVAILABLE");if(t.includes("invalid json")||t.includes("parse"))throw Error("AI_RESPONSE_ERROR");if(t.includes("api key")||t.includes("unauthorized")||t.includes("401"))throw Error("AI_AUTH_ERROR")}throw Error("AI_UNKNOWN_ERROR")}}],92938)}];
|