diff --git a/.gitignore b/.gitignore index 7c98d80..5ea6d0e 100644 --- a/.gitignore +++ b/.gitignore @@ -83,3 +83,4 @@ target/ # pnpm test/ +.vercel diff --git a/app/api/agent/stream/route.ts b/app/api/agent/stream/route.ts index 22e2079..79a3f0c 100644 --- a/app/api/agent/stream/route.ts +++ b/app/api/agent/stream/route.ts @@ -134,14 +134,14 @@ export async function GET(request: Request) { send("start", { sessionId, goal, - model: "computer-use-preview-09-2025", + model: "computer-use-preview-10-2025", init, startedAt: new Date().toISOString(), }); const agent = stagehand.agent({ provider: "google", - model: "computer-use-preview-09-2025", + model: "computer-use-preview-10-2025", options: { apiKey: process.env.GOOGLE_API_KEY, }, diff --git a/app/api/session/route.ts b/app/api/session/route.ts index 41f11c6..c640ebf 100644 --- a/app/api/session/route.ts +++ b/app/api/session/route.ts @@ -86,7 +86,7 @@ async function createSession(timezone?: string) { width: 2560, height: 1440, }, - // @ts-ignore + //@ts-expect-error - not present in the types, but valid os: "windows", blockAds: true, advancedStealth: true diff --git a/next.config.ts b/next.config.ts index 923336f..5c61e97 100644 --- a/next.config.ts +++ b/next.config.ts @@ -1,4 +1,5 @@ import type { NextConfig } from "next"; +import path from "path"; const securityHeaders = [ { key: "Referrer-Policy", value: "strict-origin-when-cross-origin" }, @@ -21,6 +22,11 @@ const securityHeaders = [ ]; const nextConfig: NextConfig = { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + webpack: (config: any) => { + config.resolve.alias["@stagehand-ts"] = path.resolve(__dirname, "sdk/stagehand-ts"); + return config; + }, async headers() { return [ { diff --git a/package.json b/package.json index 90ec6db..12b8945 100644 --- a/package.json +++ b/package.json @@ -11,8 +11,7 @@ }, "dependencies": { "@browserbasehq/sdk": "^2.6.0", - "@browserbasehq/stagehand": "file:/Users/kylejeong/Desktop/private-cua-exp/stagehand-ts", - "@tailwindcss/typography": "^0.5.19", + "@browserbasehq/stagehand": "file:./sdk/stagehand-ts", "@vercel/analytics": "^1.4.1", "class-variance-authority": "^0.7.1", "clsx": "^2.1.1", @@ -32,6 +31,7 @@ "devDependencies": { "@eslint/eslintrc": "^3", "@eslint/js": "^9.34.0", + "@tailwindcss/typography": "^0.5.19", "@types/node": "^20", "@types/react": "^19", "@types/react-dom": "^19", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c985262..3768a86 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -12,11 +12,8 @@ importers: specifier: ^2.6.0 version: 2.6.0 '@browserbasehq/stagehand': - specifier: file:/Users/kylejeong/Desktop/private-cua-exp/stagehand-ts - version: file:../private-cua-exp/stagehand-ts(deepmerge@4.3.1)(dotenv@16.6.1)(react@19.1.1)(zod@3.25.76) - '@tailwindcss/typography': - specifier: ^0.5.19 - version: 0.5.19(tailwindcss@3.4.17) + specifier: file:./sdk/stagehand-ts + version: file:sdk/stagehand-ts(deepmerge@4.3.1)(dotenv@16.6.1)(react@19.1.1)(zod@3.25.76) '@vercel/analytics': specifier: ^1.4.1 version: 1.5.0(next@15.1.6(@opentelemetry/api@1.9.0)(react-dom@19.1.1(react@19.1.1))(react@19.1.1))(react@19.1.1) @@ -69,6 +66,9 @@ importers: '@eslint/js': specifier: ^9.34.0 version: 9.34.0 + '@tailwindcss/typography': + specifier: ^0.5.19 + version: 0.5.19(tailwindcss@3.4.17) '@types/node': specifier: ^20 version: 20.19.11 @@ -222,8 +222,8 @@ packages: '@browserbasehq/sdk@2.6.0': resolution: {integrity: sha512-83iXP5D7xMm8Wyn66TUaUrgoByCmAJuoMoZQI3sGg3JAiMlTfnCIMqyVBoNSaItaPIkaCnrsj6LiusmXV2X9YA==} - '@browserbasehq/stagehand@file:../private-cua-exp/stagehand-ts': - resolution: {directory: ../private-cua-exp/stagehand-ts, type: directory} + '@browserbasehq/stagehand@file:sdk/stagehand-ts': + resolution: {directory: sdk/stagehand-ts, type: directory} hasBin: true peerDependencies: deepmerge: ^4.3.1 @@ -277,9 +277,14 @@ packages: resolution: {integrity: sha512-Z5kJ+wU3oA7MMIqVR9tyZRtjYPr4OC004Q4Rw7pgOKUOKkJfZ3O24nz3WYfGRpMDNmcOi3TwQOmgm7B7Tpii0w==} engines: {node: ^18.18.0 || ^20.9.0 || >=21.1.0} - '@google/genai@0.8.0': - resolution: {integrity: sha512-Zs+OGyZKyMbFofGJTR9/jTQSv8kITh735N3tEuIZj4VlMQXTC0soCFahysJ9NaeenRlD7xGb6fyqmX+FwrpU6Q==} - engines: {node: '>=18.0.0'} + '@google/genai@1.22.0': + resolution: {integrity: sha512-siETS3zTm3EGpTT4+BFc1z20xXBYfueD3gCYfxkOjuAKRk8lt8TJevDHi3zepn1oSI6NhG/LZvy0i+Q3qheObg==} + engines: {node: '>=20.0.0'} + peerDependencies: + '@modelcontextprotocol/sdk': ^1.11.4 + peerDependenciesMeta: + '@modelcontextprotocol/sdk': + optional: true '@humanfs/core@0.19.1': resolution: {integrity: sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==} @@ -2994,11 +2999,11 @@ snapshots: transitivePeerDependencies: - encoding - '@browserbasehq/stagehand@file:../private-cua-exp/stagehand-ts(deepmerge@4.3.1)(dotenv@16.6.1)(react@19.1.1)(zod@3.25.76)': + '@browserbasehq/stagehand@file:sdk/stagehand-ts(deepmerge@4.3.1)(dotenv@16.6.1)(react@19.1.1)(zod@3.25.76)': dependencies: '@anthropic-ai/sdk': 0.39.0 '@browserbasehq/sdk': 2.6.0 - '@google/genai': 0.8.0 + '@google/genai': 1.22.0 ai: 4.3.19(react@19.1.1)(zod@3.25.76) deepmerge: 4.3.1 devtools-protocol: 0.0.1464554 @@ -3027,6 +3032,7 @@ snapshots: '@ai-sdk/xai': 1.2.18(zod@3.25.76) ollama-ai-provider: 1.2.0(zod@3.25.76) transitivePeerDependencies: + - '@modelcontextprotocol/sdk' - bufferutil - encoding - react @@ -3093,7 +3099,7 @@ snapshots: '@eslint/core': 0.15.2 levn: 0.4.1 - '@google/genai@0.8.0': + '@google/genai@1.22.0': dependencies: google-auth-library: 9.15.1 ws: 8.18.3 diff --git a/sdk/stagehand-ts/CHANGELOG.md b/sdk/stagehand-ts/CHANGELOG.md new file mode 100644 index 0000000..791a4d1 --- /dev/null +++ b/sdk/stagehand-ts/CHANGELOG.md @@ -0,0 +1,547 @@ +# @browserbasehq/stagehand + +## 2.4.2 + +### Patch Changes + +- [#865](https://github.com/browserbase/stagehand/pull/865) [`6b4e6e3`](https://github.com/browserbase/stagehand/commit/6b4e6e3f31d5496cf15728e9018eddeb04839542) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - improve type safety for trimTrailingTextNode + +- [#897](https://github.com/browserbase/stagehand/pull/897) [`e77d018`](https://github.com/browserbase/stagehand/commit/e77d0188683ebf596dfb78dfafbbca1dc32993f0) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix selfHeal to remember intially received arguments + +- [#920](https://github.com/browserbase/stagehand/pull/920) [`c20adb9`](https://github.com/browserbase/stagehand/commit/c20adb95539fed8c56a4aa413262a9c65a8e6474) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: tab handling on API + +- [#882](https://github.com/browserbase/stagehand/pull/882) [`b86df93`](https://github.com/browserbase/stagehand/commit/b86df93b9136aae96292121a29c25f3d74d84bf7) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove elements that don't have xpaths from observe response + +- [#905](https://github.com/browserbase/stagehand/pull/905) [`023c2c2`](https://github.com/browserbase/stagehand/commit/023c2c273b46d3792d7e5d3c902089487b16b531) Thanks [@tkattkat](https://github.com/tkattkat)! - Delete old images from anthropic cua client + +- [#925](https://github.com/browserbase/stagehand/pull/925) [`8c28647`](https://github.com/browserbase/stagehand/commit/8c2864755ecd05c8f7de235d4198deec0dd5f78e) Thanks [@miguelg719](https://github.com/miguelg719)! - Remove \_refreshPageFromApi() + +- [#887](https://github.com/browserbase/stagehand/pull/887) [`87e09c6`](https://github.com/browserbase/stagehand/commit/87e09c618940f364ec8af00455a19a17ec63cbd3) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: allow xpaths with prepended 'xpath=' for targeted extract + +- [#864](https://github.com/browserbase/stagehand/pull/864) [`a611115`](https://github.com/browserbase/stagehand/commit/a61111525d70b450bdfc43f112380f44899c9e97) Thanks [@miguelg719](https://github.com/miguelg719)! - Temporarily patch custom clients serialization error on api + +- [#881](https://github.com/browserbase/stagehand/pull/881) [`69913fe`](https://github.com/browserbase/stagehand/commit/69913fe1dfb8201ae2aeffa5f049fb46ab02cbc2) Thanks [@miguelg719](https://github.com/miguelg719)! - Pass sdk version number to API for debugging + +- [#913](https://github.com/browserbase/stagehand/pull/913) [`b1b83a1`](https://github.com/browserbase/stagehand/commit/b1b83a1d334fe76e5f5f9dd32dc92c16b7d40ce6) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - move iframe out of 'experimental' + +- [#891](https://github.com/browserbase/stagehand/pull/891) [`be8497c`](https://github.com/browserbase/stagehand/commit/be8497cb6b142cc893cea9692b8c47bd19514c60) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: nested iframe xpath bug + +- [#883](https://github.com/browserbase/stagehand/pull/883) [`98704c9`](https://github.com/browserbase/stagehand/commit/98704c9ed225ca25bbde4bb3dc286936e9c54471) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add timeout for JS click + +- [#907](https://github.com/browserbase/stagehand/pull/907) [`04978bd`](https://github.com/browserbase/stagehand/commit/04978bdd30d2edcbc69eb9fd91358a16975ea2eb) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - store mapping of CDP frame ID -> page + +## 2.4.1 + +### Patch Changes + +- [#856](https://github.com/browserbase/stagehand/pull/856) [`8a43c5a`](https://github.com/browserbase/stagehand/commit/8a43c5a86d4da40cfaedd9cf2e42186928bdf946) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - set download behaviour by default + +- [#857](https://github.com/browserbase/stagehand/pull/857) [`890ffcc`](https://github.com/browserbase/stagehand/commit/890ffccac5e0a60ade64a46eb550c981ffb3e84a) Thanks [@miguelg719](https://github.com/miguelg719)! - return "not-supported" for elements inside the shadow-dom + +- [#844](https://github.com/browserbase/stagehand/pull/844) [`64c1072`](https://github.com/browserbase/stagehand/commit/64c10727bda50470483a3eb175c02842db0923a1) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - don't automatically close tabs + +- [#860](https://github.com/browserbase/stagehand/pull/860) [`b077d3f`](https://github.com/browserbase/stagehand/commit/b077d3f48a97f47a71ccc79ae39b41e7f07f9c04) Thanks [@miguelg719](https://github.com/miguelg719)! - Set default schema on extract options with no schema + +- [#842](https://github.com/browserbase/stagehand/pull/842) [`8bcb5d7`](https://github.com/browserbase/stagehand/commit/8bcb5d77debf6bf7601fd5c090efd7fde75c5d5e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - improved handling for OS level dropdowns + +- [#846](https://github.com/browserbase/stagehand/pull/846) [`7bf10c5`](https://github.com/browserbase/stagehand/commit/7bf10c55b267078fe847c1d7f7a60d604f9c7c94) Thanks [@miguelg719](https://github.com/miguelg719)! - Filter attaching to target worker / shared_worker + +## 2.4.0 + +### Minor Changes + +- [#819](https://github.com/browserbase/stagehand/pull/819) [`6a18c1e`](https://github.com/browserbase/stagehand/commit/6a18c1ee1e46d55c6e90c4d5572e17ed8daa140c) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - try playwright click and fall back to JS click event + +### Patch Changes + +- [#826](https://github.com/browserbase/stagehand/pull/826) [`124e0d3`](https://github.com/browserbase/stagehand/commit/124e0d3bb54ddb6738ede6d7aa99a945ef1cacd1) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where we are unable to take actions on text nodes + +- [#818](https://github.com/browserbase/stagehand/pull/818) [`1660751`](https://github.com/browserbase/stagehand/commit/1660751cd14cb5b27d44f8167216afb8d1c3c45c) Thanks [@miguelg719](https://github.com/miguelg719)! - Added CUA support for Claude 4 models + +- [#821](https://github.com/browserbase/stagehand/pull/821) [`cadac9d`](https://github.com/browserbase/stagehand/commit/cadac9da09123d12e5d496a0e8b12660964c1b33) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - use playwright instead of playwright test + +- [#832](https://github.com/browserbase/stagehand/pull/832) [`759da55`](https://github.com/browserbase/stagehand/commit/759da55775eb2df81d56ae18c0f386fd9b02a9f0) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix \_refreshPageFromAPI to use parametrized apiKey + +- [#810](https://github.com/browserbase/stagehand/pull/810) [`a175a51`](https://github.com/browserbase/stagehand/commit/a175a519b8c14300db6f1ed30709e113d18e99db) Thanks [@miguelg719](https://github.com/miguelg719)! - Update logos + +- [#822](https://github.com/browserbase/stagehand/pull/822) [`8527a80`](https://github.com/browserbase/stagehand/commit/8527a80522c3eedb9516a6caa1a0e4e4be981a3d) Thanks [@miguelg719](https://github.com/miguelg719)! - Add model with date tag for OpenAI CUA + +- [#833](https://github.com/browserbase/stagehand/pull/833) [`55fca2f`](https://github.com/browserbase/stagehand/commit/55fca2f7da63cc0ef6e27b45a33f63c666cdce7e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - adjust stagehandLogger.warn() level to be 1 instead of 0 + +## 2.3.1 + +### Patch Changes + +- [#796](https://github.com/browserbase/stagehand/pull/796) [`12a99b3`](https://github.com/browserbase/stagehand/commit/12a99b398d8a4c3eea3ca69a3cf793faaaf4aea3) Thanks [@miguelg719](https://github.com/miguelg719)! - Added a experimental flag to enable the newest and most experimental features + +- [#807](https://github.com/browserbase/stagehand/pull/807) [`2451797`](https://github.com/browserbase/stagehand/commit/2451797f64c0efa4a72fd70265110003c8d0a6cd) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - include version number in StagehandDefaultError message + +- [#803](https://github.com/browserbase/stagehand/pull/803) [`1d631a5`](https://github.com/browserbase/stagehand/commit/1d631a57a197390f672b718ae5199991ab27cfb1) Thanks [@miguelg719](https://github.com/miguelg719)! - Enable session affinity for cache optimization + +- [#804](https://github.com/browserbase/stagehand/pull/804) [`9c398bb`](https://github.com/browserbase/stagehand/commit/9c398bb9ec2d10bdb53ad5aa7e3b58cce24fdb2b) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - update operatorResponseSchema based on new openai spec + +- [#786](https://github.com/browserbase/stagehand/pull/786) [`c19ad7f`](https://github.com/browserbase/stagehand/commit/c19ad7f1e082e91fdeaa9c2ef63767a5a2b3a195) Thanks [@miguelg719](https://github.com/miguelg719)! - Handle reroute to account for rollout + +## 2.3.0 + +### Minor Changes + +- [#737](https://github.com/browserbase/stagehand/pull/737) [`6ef6073`](https://github.com/browserbase/stagehand/commit/6ef60730cab0ad9025f44b6eeb2c83751d1dcd35) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - deprecate useTextExtract and remove functionality + +### Patch Changes + +- [#741](https://github.com/browserbase/stagehand/pull/741) [`5680d25`](https://github.com/browserbase/stagehand/commit/5680d2509352c383ad502c9f4fabde01fa638833) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - use safeparse for zod validation + +- [#783](https://github.com/browserbase/stagehand/pull/783) [`4de92a8`](https://github.com/browserbase/stagehand/commit/4de92a8af461fc95063faf39feee1d49259f58ba) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix the readme logo link + +## 2.2.1 + +### Patch Changes + +- [#721](https://github.com/browserbase/stagehand/pull/721) [`be8652e`](https://github.com/browserbase/stagehand/commit/be8652e770b57fdb3299fa0b2efa4eb0e816434e) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix stagehand.close() functionality to include calling browser.close() + +- [#724](https://github.com/browserbase/stagehand/pull/724) [`6b413b7`](https://github.com/browserbase/stagehand/commit/6b413b7ad00b13ca0bd53ee2e7393023821408b6) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - rm refine step in extract + +- [#712](https://github.com/browserbase/stagehand/pull/712) [`7eafbd9`](https://github.com/browserbase/stagehand/commit/7eafbd9b1a73b37effa444929767df7c592caf02) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - deprecated `onlyVisible` param and remove its functionality + +- [#725](https://github.com/browserbase/stagehand/pull/725) [`1b50aa6`](https://github.com/browserbase/stagehand/commit/1b50aa61cf0a429dd6cb2760a08f7f698a50454b) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - dont overwrite .describe() when user defines a zod schema with z.string().url().describe() + +- [#717](https://github.com/browserbase/stagehand/pull/717) [`f2b7f1f`](https://github.com/browserbase/stagehand/commit/f2b7f1f284eef1f96753319b66c7d0b273a6f8cd) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - don't publish uncompiled ts to npm + +- [#719](https://github.com/browserbase/stagehand/pull/719) [`c8d672f`](https://github.com/browserbase/stagehand/commit/c8d672f7c410c256defbc2e87ead99239837aa28) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix `Invalid schema for response_format` error when extracting links + +- [#722](https://github.com/browserbase/stagehand/pull/722) [`bebf204`](https://github.com/browserbase/stagehand/commit/bebf2044502333c694743078c5b0c9deae11fb79) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - replace NBSP with regular space & remove special characters from dom+a11y tree + +- [#714](https://github.com/browserbase/stagehand/pull/714) [`37d6810`](https://github.com/browserbase/stagehand/commit/37d6810a704773d0383a86f98f5f17c7d5b21975) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix the native AI SDK client implementation to optionally take in an API key + +## 2.2.0 + +### Minor Changes + +- [#655](https://github.com/browserbase/stagehand/pull/655) [`8814af9`](https://github.com/browserbase/stagehand/commit/8814af9ece99fddc3dd9fb32671d0513a3a00c67) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - extract links + +- [#675](https://github.com/browserbase/stagehand/pull/675) [`35c55eb`](https://github.com/browserbase/stagehand/commit/35c55ebf6c2867801a0a6f6988a883c8cb90cf9a) Thanks [@tkattkat](https://github.com/tkattkat)! - Added Gemini 2.5 Flash to Google supported models + +- [#668](https://github.com/browserbase/stagehand/pull/668) [`5c6d2cf`](https://github.com/browserbase/stagehand/commit/5c6d2cf89c9fbf198485506ed9ed75e07aec5cd4) Thanks [@miguelg719](https://github.com/miguelg719)! - Added a new class - Stagehand Evaluator - that wraps around a Stagehand object to determine whether a task is successful or not. Currently used for agent evals + +### Patch Changes + +- [#706](https://github.com/browserbase/stagehand/pull/706) [`18ac6fb`](https://github.com/browserbase/stagehand/commit/18ac6fba30f45b7557cecb890f4e84c75de8383c) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove unused fillInVariables fn + +- [#692](https://github.com/browserbase/stagehand/pull/692) [`6b95248`](https://github.com/browserbase/stagehand/commit/6b95248d6e02e5304ce4dd60499e31fc42af57eb) Thanks [@miguelg719](https://github.com/miguelg719)! - Updated the list of OpenAI models (4.1, o3...) + +- [#688](https://github.com/browserbase/stagehand/pull/688) [`7d81b3c`](https://github.com/browserbase/stagehand/commit/7d81b3c951c1f3dfc46845aefcc26ff175299bca) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - wrap page.evaluate to make sure we have injected browser side scripts before calling them + +- [#664](https://github.com/browserbase/stagehand/pull/664) [`b5ca00a`](https://github.com/browserbase/stagehand/commit/b5ca00a25ad0c33a5f4d3198e1bc59edb9956e7c) Thanks [@miguelg719](https://github.com/miguelg719)! - remove unnecessary log + +- [#683](https://github.com/browserbase/stagehand/pull/683) [`8f0f97b`](https://github.com/browserbase/stagehand/commit/8f0f97bc491e23ff0078c802aaf509fd04173c37) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - use javsacript click instead of playwright + +- [#705](https://github.com/browserbase/stagehand/pull/705) [`346ef5d`](https://github.com/browserbase/stagehand/commit/346ef5d0132dc1418dac18d26640a8df0435af57) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixed removing a hanging observation map that is no longer used + +- [#698](https://github.com/browserbase/stagehand/pull/698) [`c145bc1`](https://github.com/browserbase/stagehand/commit/c145bc1d90ffd0d71c412de3af1c26c121e0b101) Thanks [@sameelarif](https://github.com/sameelarif)! - Fixing LLM client support to natively integrate with AI SDK + +- [#687](https://github.com/browserbase/stagehand/pull/687) [`edd6d3f`](https://github.com/browserbase/stagehand/commit/edd6d3feb47aac9f312a5edad78bf850ae1541db) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixed the schema input for Gemini's response model + +- [#678](https://github.com/browserbase/stagehand/pull/678) [`5ec43d8`](https://github.com/browserbase/stagehand/commit/5ec43d8b9568c0f86b3e24bd83d1826c837656ed) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - allow form filling when form is not top-most element + +- [#694](https://github.com/browserbase/stagehand/pull/694) [`b8cc164`](https://github.com/browserbase/stagehand/commit/b8cc16405b712064a54c8cd591750368a47f35ea) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add telemetry for cua agents to stagehand.metrics + +- [#699](https://github.com/browserbase/stagehand/pull/699) [`d9f4243`](https://github.com/browserbase/stagehand/commit/d9f4243f6a8c8d4f3003ad6589f7eb4da6d23d0f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - rm deprecated primitives from stagehand object + +- [#710](https://github.com/browserbase/stagehand/pull/710) [`9f4ab76`](https://github.com/browserbase/stagehand/commit/9f4ab76a0c1f0c2171290765c48c3bcea5b50e0f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - support targeted extract for domExtract + +- [#677](https://github.com/browserbase/stagehand/pull/677) [`bc5a731`](https://github.com/browserbase/stagehand/commit/bc5a731241f7f4c5040dd672d8e3787555766421) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixes a redundant unnecessary log + +## 2.1.0 + +### Minor Changes + +- [#659](https://github.com/browserbase/stagehand/pull/659) [`f9a435e`](https://github.com/browserbase/stagehand/commit/f9a435e938daccfb2e54ca23fad8ef75128a4486) Thanks [@miguelg719](https://github.com/miguelg719)! - Added native support for Google Generative models (Gemini) + +### Patch Changes + +- [#647](https://github.com/browserbase/stagehand/pull/647) [`ca5467d`](https://github.com/browserbase/stagehand/commit/ca5467de7d31bfb270b6b625224a926c52c97900) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - collapse redundant text nodes into parent elements + +- [#636](https://github.com/browserbase/stagehand/pull/636) [`9037430`](https://github.com/browserbase/stagehand/commit/903743097367ba6bb12baa9f0fa8f7985f543fdc) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix token act metrics and inference logging being misplaced as observe metrics and inference logging + +- [#648](https://github.com/browserbase/stagehand/pull/648) [`169e7ea`](https://github.com/browserbase/stagehand/commit/169e7ea9e229503ae5958eaa4511531578ee3841) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add mapping of node id -> url + +- [#654](https://github.com/browserbase/stagehand/pull/654) [`57a9853`](https://github.com/browserbase/stagehand/commit/57a98538381e0e54fbb734b43c50d61fd0d567df) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix repeated up & down scrolling bug for clicks inside `act` + +- [#624](https://github.com/browserbase/stagehand/pull/624) [`cf167a4`](https://github.com/browserbase/stagehand/commit/cf167a437865e8e8bdb8739d22c3b3bb84e185de) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - export stagehand error classes so they can be referenced from @dist + +- [#640](https://github.com/browserbase/stagehand/pull/640) [`178f5f0`](https://github.com/browserbase/stagehand/commit/178f5f0a8fecd876adfb4e29983853bdf7ec72fd) Thanks [@yash1744](https://github.com/yash1744)! - Added support for stagehand agents to automatically redirect to https://google.com when the page URL is empty or set to about:blank, preventing empty screenshots and saving tokens. + +- [#661](https://github.com/browserbase/stagehand/pull/661) [`bf823a3`](https://github.com/browserbase/stagehand/commit/bf823a36930b0686b416a42302ef8c021b4aba75) Thanks [@kamath](https://github.com/kamath)! - fix press enter + +- [#633](https://github.com/browserbase/stagehand/pull/633) [`86724f6`](https://github.com/browserbase/stagehand/commit/86724f6fb0abc7292423ac5bd0bebcd352f95940) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix the getBrowser logic for redundant api calls and throw informed errors + +- [#656](https://github.com/browserbase/stagehand/pull/656) [`c630373`](https://github.com/browserbase/stagehand/commit/c630373dede4c775875834bfb860436ba2ea48d2) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - parse out % signs from variables in act + +- [#637](https://github.com/browserbase/stagehand/pull/637) [`944bbbf`](https://github.com/browserbase/stagehand/commit/944bbbfe8bfb357b4910584447a93f6f402c3826) Thanks [@kamath](https://github.com/kamath)! - Fix: forward along the stack trace in StagehandDefaultError + +## 2.0.0 + +### Major Changes + +- [#591](https://github.com/browserbase/stagehand/pull/591) [`e234a0f`](https://github.com/browserbase/stagehand/commit/e234a0f80bf4c07bcc57265da216cbc4ab3bd19d) Thanks [@miguelg719](https://github.com/miguelg719)! - Announcing **Stagehand 2.0**! 🎉 + + We're thrilled to announce the release of Stagehand 2.0, bringing significant improvements to make browser automation more powerful, faster, and easier to use than ever before. + + ### 🚀 New Features + + - **Introducing `stagehand.agent`**: A powerful new way to integrate SOTA Computer use models or Browserbase's [Open Operator](https://operator.browserbase.com) into Stagehand with one line of code! Perfect for multi-step workflows and complex interactions. [Learn more](https://docs.stagehand.dev/concepts/agent) + - **Lightning-fast `act` and `extract`**: Major performance improvements to make your automations run significantly faster. + - **Enhanced Logging**: Better visibility into what's happening during automation with improved logging and debugging capabilities. + - **Comprehensive Documentation**: A completely revamped documentation site with better examples, guides, and best practices. + - **Improved Error Handling**: More descriptive errors and better error recovery to help you debug issues faster. + + ### 🛠️ Developer Experience + + - **Better TypeScript Support**: Enhanced type definitions and better IDE integration + - **Better Error Messages**: Clearer, more actionable error messages to help you debug faster + - **Improved Caching**: More reliable action caching for better performance + + We're excited to see what you build with Stagehand 2.0! For questions or support, join our [Slack community](https://stagehand.dev/slack). + + For more details, check out our [documentation](https://docs.stagehand.dev). + +### Minor Changes + +- [#588](https://github.com/browserbase/stagehand/pull/588) [`ba9efc5`](https://github.com/browserbase/stagehand/commit/ba9efc5580a536bc3c158e507a6c6695825c2834) Thanks [@sameelarif](https://github.com/sameelarif)! - Added support for offloading agent tasks to the API. + +- [#600](https://github.com/browserbase/stagehand/pull/600) [`11e015d`](https://github.com/browserbase/stagehand/commit/11e015daac56dc961b8c8d54ce360fd00d4fee38) Thanks [@sameelarif](https://github.com/sameelarif)! - Added a `stagehand.history` array which stores an array of `act`, `extract`, `observe`, and `goto` calls made. Since this history array is stored on the `StagehandPage` level, it will capture methods even if indirectly called by an agent. + +- [#601](https://github.com/browserbase/stagehand/pull/601) [`1d22604`](https://github.com/browserbase/stagehand/commit/1d2260401e27bae25779a55bb2ed7b7153c34fd0) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add custom error classes + +- [#599](https://github.com/browserbase/stagehand/pull/599) [`75d8fb3`](https://github.com/browserbase/stagehand/commit/75d8fb36a67cd84eb55b509bf959edc7b05059da) Thanks [@miguelg719](https://github.com/miguelg719)! - cleaner logging with pino + +- [#609](https://github.com/browserbase/stagehand/pull/609) [`c92295d`](https://github.com/browserbase/stagehand/commit/c92295d8424dac1a4f81066ca260ade2d5fce80b) Thanks [@kamath](https://github.com/kamath)! - Removed deprecated fields and methods from Stagehand constructor and added cdpUrl to localBrowserLaunchOptions for custom CDP URLs support. + +- [#571](https://github.com/browserbase/stagehand/pull/571) [`73d6736`](https://github.com/browserbase/stagehand/commit/73d67368b88002c17814e46e75a99456bf355c4e) Thanks [@miguelg719](https://github.com/miguelg719)! - You can now use Computer Using Agents (CUA) natively in Stagehand for both Anthropic and OpenAI models! This unlocks a brand new frontier of applications for Stagehand users 🤘 + +- [#619](https://github.com/browserbase/stagehand/pull/619) [`7b0b996`](https://github.com/browserbase/stagehand/commit/7b0b9969a58014ae3e99b2054e4463b785073cfd) Thanks [@sameelarif](https://github.com/sameelarif)! - add disablePino flag to stagehand constructor params + +- [#620](https://github.com/browserbase/stagehand/pull/620) [`566e587`](https://github.com/browserbase/stagehand/commit/566e5877a1861e0eae5a118d34efe09d43a37098) Thanks [@kamath](https://github.com/kamath)! - You can now pass in an OpenAI instance as an `llmClient` to the Stagehand constructor! This allows you to use Stagehand with any OpenAI-compatible model, like Ollama, Gemini, etc., as well as OpenAI wrappers like Braintrust. + +- [#586](https://github.com/browserbase/stagehand/pull/586) [`c57dc19`](https://github.com/browserbase/stagehand/commit/c57dc19c448b8c2aab82953291f4e38f202c4729) Thanks [@sameelarif](https://github.com/sameelarif)! - Added native Stagehand agentic loop functionality. This allows you to build agentic workflows with a single prompt without using a computer-use model. To try it out, create a `stagehand.agent` without passing in a provider. + +### Patch Changes + +- [#580](https://github.com/browserbase/stagehand/pull/580) [`179e17c`](https://github.com/browserbase/stagehand/commit/179e17c2d1c9837de49c776d9850a330a759e73f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - refactor \_performPlaywrightMethod + +- [#608](https://github.com/browserbase/stagehand/pull/608) [`71ee10d`](https://github.com/browserbase/stagehand/commit/71ee10d50cb46e83d43fd783e1404569e6f317cf) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - added support for "scrolling to next/previous chunk" + +- [#594](https://github.com/browserbase/stagehand/pull/594) [`e483484`](https://github.com/browserbase/stagehand/commit/e48348412a6e651967ba22d097d5308af0e8d0a8) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - pass observeHandler into actHandler + +- [#569](https://github.com/browserbase/stagehand/pull/569) [`17e8b40`](https://github.com/browserbase/stagehand/commit/17e8b40f94b30f6e253443a4bbb8a3e364e58e38) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - you can now call stagehand.metrics to get token usage metrics. you can also set logInferenceToFile in stagehand config to log the entire call/response history from stagehand & the LLM. + +- [#617](https://github.com/browserbase/stagehand/pull/617) [`affa564`](https://github.com/browserbase/stagehand/commit/affa5646658399ab71ed08c1b9ce0fd776b46fca) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - use a11y tree for default extract + +- [#589](https://github.com/browserbase/stagehand/pull/589) [`0c4b1e7`](https://github.com/browserbase/stagehand/commit/0c4b1e7e6ff4b8a60af4a2d0d2056bff847227d5) Thanks [@miguelg719](https://github.com/miguelg719)! - Added CDP support for screenshots, find more about the benefits here: https://docs.browserbase.com/features/screenshots#why-use-cdp-for-screenshots%3F + +- [#584](https://github.com/browserbase/stagehand/pull/584) [`c7c1a80`](https://github.com/browserbase/stagehand/commit/c7c1a8066be33188ba1e900828045db61410025c) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix to remove unnecessary healtcheck ping on sdk + +- [#616](https://github.com/browserbase/stagehand/pull/616) [`2a27e1c`](https://github.com/browserbase/stagehand/commit/2a27e1c8e967befbbbb05ea71369878ac1573658) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixed new opened tab handling for CUA models + +- [#582](https://github.com/browserbase/stagehand/pull/582) [`dfd24e6`](https://github.com/browserbase/stagehand/commit/dfd24e638ef3723d3a8a3a33ff7942af0ac4745f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - support api usage for extract with no args + +- [#563](https://github.com/browserbase/stagehand/pull/563) [`98166d7`](https://github.com/browserbase/stagehand/commit/98166d76d30bc67d6b04b3d5c39f78f92c254b49) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - support scrolling in `act` + +- [#598](https://github.com/browserbase/stagehand/pull/598) [`53889d4`](https://github.com/browserbase/stagehand/commit/53889d4b6e772098beaba2e1ee5a24e6f07706bb) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix the open operator handler to work with anthropic + +- [#605](https://github.com/browserbase/stagehand/pull/605) [`b8beaec`](https://github.com/browserbase/stagehand/commit/b8beaec451a03eaa5d12281fe7c8d4eb9c9d7e81) Thanks [@sameelarif](https://github.com/sameelarif)! - Added support for resuming a Stagehand session created on the API. + +- [#612](https://github.com/browserbase/stagehand/pull/612) [`cd36068`](https://github.com/browserbase/stagehand/commit/cd3606854c465747c78b44763469dfdfa16db1b0) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove all logic related to dom based act + +- [#577](https://github.com/browserbase/stagehand/pull/577) [`4fdbf63`](https://github.com/browserbase/stagehand/commit/4fdbf6324a0dc68568bba73ea4d9018b2ed67849) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove debugDom + +- [#603](https://github.com/browserbase/stagehand/pull/603) [`2a14a60`](https://github.com/browserbase/stagehand/commit/2a14a607f3e7fa3ca9a02670afdc7e60ccfbfb3f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - rm unused handlePossiblePageNavigation + +- [#614](https://github.com/browserbase/stagehand/pull/614) [`a59eaef`](https://github.com/browserbase/stagehand/commit/a59eaef67c2f4a0cb07bb0046fe7e93e2ba4dc41) Thanks [@kamath](https://github.com/kamath)! - override whatwg-url to avoid punycode warning + +- [#573](https://github.com/browserbase/stagehand/pull/573) [`c24f3c9`](https://github.com/browserbase/stagehand/commit/c24f3c9a58873c3920fab0f9891c2bf5245c9b5e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - return act result in actFromObserve + +## 1.14.0 + +### Minor Changes + +- [#518](https://github.com/browserbase/stagehand/pull/518) [`516725f`](https://github.com/browserbase/stagehand/commit/516725fc1c5d12d22caac0078a118c77bfe033a8) Thanks [@sameelarif](https://github.com/sameelarif)! - `act()` can now use `observe()` under the hood, resulting in significant performance improvements. To opt-in to this change, set `slowDomBasedAct: false` in `ActOptions`. + +- [#483](https://github.com/browserbase/stagehand/pull/483) [`8c9445f`](https://github.com/browserbase/stagehand/commit/8c9445fde9724ae33eeeb1234fd5b9bbd418bfdb) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - When using `textExtract`, you can now do targetted extraction by passing an xpath string into extract via the `selector` parameter. This limits the dom processing step to a target element, reducing tokens and increasing speed. For example: + + ```typescript + const weatherData = await stagehand.page.extract({ + instruction: "extract the weather data for Sun, Feb 23 at 11PM", + schema: z.object({ + temperature: z.string(), + weather_description: z.string(), + wind: z.string(), + humidity: z.string(), + barometer: z.string(), + visibility: z.string(), + }), + modelName, + useTextExtract, + selector: xpath, // xpath of the element to extract from + }); + ``` + +- [#556](https://github.com/browserbase/stagehand/pull/556) [`499a72d`](https://github.com/browserbase/stagehand/commit/499a72dc56009791ce065270b854b12fc5570050) Thanks [@kamath](https://github.com/kamath)! - You can now set a timeout for dom-based stagehand act! Do this in `act` with `timeoutMs` as a parameter, or set a global param to `actTimeoutMs` in Stagehand config. + +- [#544](https://github.com/browserbase/stagehand/pull/544) [`55c9673`](https://github.com/browserbase/stagehand/commit/55c9673c5948743b804d70646f425a61818c7789) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - you can now deterministically get the full text representation of a webpage by calling `extract()` (with no arguments) + +- [#538](https://github.com/browserbase/stagehand/pull/538) [`d898d5b`](https://github.com/browserbase/stagehand/commit/d898d5b9e1c3b80e62e72d36d1754b3e50d5a2b4) Thanks [@sameelarif](https://github.com/sameelarif)! - Added `gpt-4.5-preview` and `claude-3-7-sonnet-latest` as supported models. + +- [#523](https://github.com/browserbase/stagehand/pull/523) [`44cf7cc`](https://github.com/browserbase/stagehand/commit/44cf7cc9ac1209c97d9153281970899b10a2ddc9) Thanks [@kwt00](https://github.com/kwt00)! You can now natively run Cerebras LLMs! `cerebras-llama-3.3-70b` and `cerebras-llama-3.1-8b` are now supported models as long as `CEREBRAS_API_KEY` is set in your environment. + +- [#542](https://github.com/browserbase/stagehand/pull/542) [`cf7fe66`](https://github.com/browserbase/stagehand/commit/cf7fe665e6d1eeda97582ee2816f1dc3a66c6152) Thanks [@sankalpgunturi](https://github.com/sankalpgunturi)! You can now natively run Groq LLMs! `groq-llama-3.3-70b-versatile` and `groq-llama-3.3-70b-specdec` are now supported models as long as `GROQ_API_KEY` is set in your environment. + +### Patch Changes + +- [#506](https://github.com/browserbase/stagehand/pull/506) [`e521645`](https://github.com/browserbase/stagehand/commit/e5216455ce3fc2a4f4f7aa5614ecc92354eb670c) Thanks [@miguelg719](https://github.com/miguelg719)! - fixing 5s timeout on actHandler + +- [#535](https://github.com/browserbase/stagehand/pull/535) [`3782054`](https://github.com/browserbase/stagehand/commit/3782054734dcd0346f84003ddd8e0e484b379459) Thanks [@miguelg719](https://github.com/miguelg719)! - Adding backwards compatibility to new act->observe pipeline by accepting actOptions + +- [#508](https://github.com/browserbase/stagehand/pull/508) [`270f666`](https://github.com/browserbase/stagehand/commit/270f6669f1638f52fd5cd3f133f76446ced6ef9f) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixed stagehand to support multiple pages with an enhanced context + +- [#559](https://github.com/browserbase/stagehand/pull/559) [`18533ad`](https://github.com/browserbase/stagehand/commit/18533ad824722e4e699323248297e184bae9254e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: continuously adjusting chunk size inside `act` + +- [#554](https://github.com/browserbase/stagehand/pull/554) [`5f1868b`](https://github.com/browserbase/stagehand/commit/5f1868bd95478b3eb517319ebca7b0af4e91d144) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix targetted extract issue with scrollintoview and not chunking correctly + +- [#555](https://github.com/browserbase/stagehand/pull/555) [`fc5e8b6`](https://github.com/browserbase/stagehand/commit/fc5e8b6c5a606da96e6ed572dc8ffc6caef57576) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix issue where processAllOfDom doesnt scroll to end of page when there is dynamic content + +- [#552](https://github.com/browserbase/stagehand/pull/552) [`a25a4cb`](https://github.com/browserbase/stagehand/commit/a25a4cb538d64f50b5bd834dd88e8e6086a73078) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - accept xpaths with 'xpath=' prepended to the front in addition to xpaths without + +- [#534](https://github.com/browserbase/stagehand/pull/534) [`f0c162a`](https://github.com/browserbase/stagehand/commit/f0c162a6b4d1ac72c42f26462d7241a08b5c4e0a) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - call this.end() if the process exists + +- [#528](https://github.com/browserbase/stagehand/pull/528) [`c820bfc`](https://github.com/browserbase/stagehand/commit/c820bfcfc9571fea90afd1595775c5946118cfaf) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - handle attempt to close session that has already been closed when using the api + +- [#520](https://github.com/browserbase/stagehand/pull/520) [`f49eebd`](https://github.com/browserbase/stagehand/commit/f49eebd98c1d61413a3ea4c798595db601d55da8) Thanks [@miguelg719](https://github.com/miguelg719)! - Performing act from a 'not-supported' ObserveResult will now throw an informed error + +## 1.13.1 + +### Patch Changes + +- [#509](https://github.com/browserbase/stagehand/pull/509) [`a7d345e`](https://github.com/browserbase/stagehand/commit/a7d345e75434aebb656e1aa5aa61caed00dc99a8) Thanks [@miguelg719](https://github.com/miguelg719)! - Bun runs will now throw a more informed error + +## 1.13.0 + +### Minor Changes + +- [#486](https://github.com/browserbase/stagehand/pull/486) [`33f2b3f`](https://github.com/browserbase/stagehand/commit/33f2b3f8deff86ac2073b6d35b7413b0aeaba2f9) Thanks [@sameelarif](https://github.com/sameelarif)! - [Unreleased] Parameterized offloading Stagehand method calls to the Stagehand API. In the future, this will allow for better observability and debugging experience. + +- [#494](https://github.com/browserbase/stagehand/pull/494) [`9ba4b0b`](https://github.com/browserbase/stagehand/commit/9ba4b0b563cbc77d40cac31c11e17e365a9d1749) Thanks [@pkiv](https://github.com/pkiv)! - Added LocalBrowserLaunchOptions to provide comprehensive configuration options for local browser instances. Deprecated the top-level headless option in favor of using localBrowserLaunchOptions.headless + +- [#500](https://github.com/browserbase/stagehand/pull/500) [`a683fab`](https://github.com/browserbase/stagehand/commit/a683fab9ca90c45d78f6602a228c2d3219b776dc) Thanks [@miguelg719](https://github.com/miguelg719)! - Including Iframes in ObserveResults. This appends any iframe(s) found in the page to the end of observe results on any observe call. + +- [#504](https://github.com/browserbase/stagehand/pull/504) [`577662e`](https://github.com/browserbase/stagehand/commit/577662e985a6a6b0477815853d98610f3a6b567d) Thanks [@sameelarif](https://github.com/sameelarif)! - Enabled support for Browserbase captcha solving after page navigations. This can be enabled with the new constructor parameter: `waitForCaptchaSolves`. + +- [#496](https://github.com/browserbase/stagehand/pull/496) [`28ca9fb`](https://github.com/browserbase/stagehand/commit/28ca9fbc6f3cdc88437001108a9a6c4388ba0303) Thanks [@sameelarif](https://github.com/sameelarif)! - Fixed browserbaseSessionCreateParams not being passed in to the API initialization payload. + +### Patch Changes + +- [#459](https://github.com/browserbase/stagehand/pull/459) [`62a29ee`](https://github.com/browserbase/stagehand/commit/62a29eea982bbb855e2f885c09ac4c1334f3e0dc) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - create a11y + dom hybrid input for observe + +- [#463](https://github.com/browserbase/stagehand/pull/463) [`e40bf6f`](https://github.com/browserbase/stagehand/commit/e40bf6f517331fc9952c3c9f2683b7e02ffb9735) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - include 'Scrollable' annotations in a11y-dom hybrid + +- [#480](https://github.com/browserbase/stagehand/pull/480) [`4c07c44`](https://github.com/browserbase/stagehand/commit/4c07c444f0e71faf54413b2eeab760c7916a36e3) Thanks [@miguelg719](https://github.com/miguelg719)! - Adding a fallback try on actFromObserveResult to use the description from observe and call regular act. + +- [#487](https://github.com/browserbase/stagehand/pull/487) [`2c855cf`](https://github.com/browserbase/stagehand/commit/2c855cffdfa2b0af9924612b9c59df7b65df6443) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - update refine extraction prompt to ensure correct schema is used + +- [#497](https://github.com/browserbase/stagehand/pull/497) [`945ed04`](https://github.com/browserbase/stagehand/commit/945ed0426d34d2cb833aec8ba67bd4cba6c3b660) Thanks [@kamath](https://github.com/kamath)! - add gpt 4o november snapshot + +## 1.12.0 + +### Minor Changes + +- [#426](https://github.com/browserbase/stagehand/pull/426) [`bbbcee7`](https://github.com/browserbase/stagehand/commit/bbbcee7e7d86f5bf90cbb93f2ac9ad5935f15896) Thanks [@miguelg719](https://github.com/miguelg719)! - Observe got a major upgrade. Now it will return a suggested playwright method with any necessary arguments for the generated candidate elements. It also includes a major speedup when using a11y tree processing for context. + +- [#452](https://github.com/browserbase/stagehand/pull/452) [`16837ec`](https://github.com/browserbase/stagehand/commit/16837ece839e192fbf7b68bec128dd02f22c2613) Thanks [@kamath](https://github.com/kamath)! - add o3-mini to availablemodel + +- [#441](https://github.com/browserbase/stagehand/pull/441) [`1032d7d`](https://github.com/browserbase/stagehand/commit/1032d7d7d9c1ef8f30183c9019ea8324f1bdd5c6) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - allow act to accept observe output + +### Patch Changes + +- [#458](https://github.com/browserbase/stagehand/pull/458) [`da2e5d1`](https://github.com/browserbase/stagehand/commit/da2e5d1314b7504877fd50090e6a4b47f44fb9f6) Thanks [@miguelg719](https://github.com/miguelg719)! - Updated getAccessibilityTree() to make sure it doesn't skip useful nodes. Improved getXPathByResolvedObjectId() to account for text nodes and not skip generation + +- [#448](https://github.com/browserbase/stagehand/pull/448) [`b216072`](https://github.com/browserbase/stagehand/commit/b2160723923ed78eba83e75c7270634ca7d217de) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - improve handling of radio button clicks + +- [#445](https://github.com/browserbase/stagehand/pull/445) [`5bc514f`](https://github.com/browserbase/stagehand/commit/5bc514fc18e6634b1c81553bbc1e8b7d71b67d34) Thanks [@miguelg719](https://github.com/miguelg719)! - Adding back useAccessibilityTree param to observe with a deprecation warning/error indicating to use onlyVisible instead + +## 1.11.0 + +### Minor Changes + +- [#428](https://github.com/browserbase/stagehand/pull/428) [`5efeb5a`](https://github.com/browserbase/stagehand/commit/5efeb5ad44852efe7b260862729a5ac74eaa0228) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - temporarily remove vision + +## 1.10.1 + +### Patch Changes + +- [#422](https://github.com/browserbase/stagehand/pull/422) [`a2878d0`](https://github.com/browserbase/stagehand/commit/a2878d0acaf393b37763fb0c07b1a24043f7eb8d) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixing a build type error for async functions being called inside evaulate for observeHandler. + +## 1.10.0 + +### Minor Changes + +- [#412](https://github.com/browserbase/stagehand/pull/412) [`4aa4813`](https://github.com/browserbase/stagehand/commit/4aa4813ad62cefc333a04ea6b1004f5888dec70f) Thanks [@miguelg719](https://github.com/miguelg719)! - Includes a new format to get website context using accessibility (a11y) trees. The new context is provided optionally with the flag useAccessibilityTree for observe tasks. + +- [#417](https://github.com/browserbase/stagehand/pull/417) [`1f2b2c5`](https://github.com/browserbase/stagehand/commit/1f2b2c57d93e3b276c61224e1e26c65c2cb50e12) Thanks [@sameelarif](https://github.com/sameelarif)! - Simplify Stagehand method calls by allowing a simple string input instead of an options object. + +- [#405](https://github.com/browserbase/stagehand/pull/405) [`0df1e23`](https://github.com/browserbase/stagehand/commit/0df1e233d4ad4ba39da457b6ed85916d8d20e12e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - in ProcessAllOfDom, scroll on large scrollable elements instead of just the root DOM + +- [#373](https://github.com/browserbase/stagehand/pull/373) [`ff00965`](https://github.com/browserbase/stagehand/commit/ff00965160d568ae0bc3ca437c01f95b5c6e9039) Thanks [@sameelarif](https://github.com/sameelarif)! - Allow the input of custom instructions into the constructor so that users can guide, or provide guardrails to, the LLM in making decisions. + +### Patch Changes + +- [#386](https://github.com/browserbase/stagehand/pull/386) [`2cee0a4`](https://github.com/browserbase/stagehand/commit/2cee0a45ae2b48d1de6543b196e338e7021e59fe) Thanks [@kamath](https://github.com/kamath)! - add demo gif + +- [#362](https://github.com/browserbase/stagehand/pull/362) [`9c20de3`](https://github.com/browserbase/stagehand/commit/9c20de3e66f0ac20374d5e5e02eb107c620a2263) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - reduce collisions and improve accuracy of textExtract + +- [#413](https://github.com/browserbase/stagehand/pull/413) [`737b4b2`](https://github.com/browserbase/stagehand/commit/737b4b208c9214e8bb22535ab7a8daccf37610d9) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - remove topMostElement check when verifying visibility of text nodes + +- [#388](https://github.com/browserbase/stagehand/pull/388) [`e93561d`](https://github.com/browserbase/stagehand/commit/e93561d7875210ce7bd7fe841fb52decf6011fb3) Thanks [@kamath](https://github.com/kamath)! - Export LLMClient type + +## 1.9.0 + +### Minor Changes + +- [#374](https://github.com/browserbase/stagehand/pull/374) [`207244e`](https://github.com/browserbase/stagehand/commit/207244e3a46c4474d4d28db039eab131164790ca) Thanks [@sameelarif](https://github.com/sameelarif)! - Pass in a Stagehand Page object into the `on("popup")` listener to allow for multi-page handling. + +- [#367](https://github.com/browserbase/stagehand/pull/367) [`75c0e20`](https://github.com/browserbase/stagehand/commit/75c0e20cde54951399753e0fa841df463e1271b8) Thanks [@kamath](https://github.com/kamath)! - Logger in LLMClient is inherited by default from Stagehand. Named rather than positional arguments are used in implemented LLMClients. + +- [#381](https://github.com/browserbase/stagehand/pull/381) [`db2ef59`](https://github.com/browserbase/stagehand/commit/db2ef5997664e81b1dfb5ca992392362f2d3bab1) Thanks [@kamath](https://github.com/kamath)! - make logs only sync + +- [#385](https://github.com/browserbase/stagehand/pull/385) [`5899ec2`](https://github.com/browserbase/stagehand/commit/5899ec2c4b73c636bfd8120ec3aac225af7dd949) Thanks [@sameelarif](https://github.com/sameelarif)! - Moved the LLMClient logger paremeter to the createChatCompletion method options. + +- [#364](https://github.com/browserbase/stagehand/pull/364) [`08907eb`](https://github.com/browserbase/stagehand/commit/08907ebbc2cb47cfc3151946764656a7f4ce99c6) Thanks [@kamath](https://github.com/kamath)! - exposed llmClient in stagehand constructor + +### Patch Changes + +- [#383](https://github.com/browserbase/stagehand/pull/383) [`a77efcc`](https://github.com/browserbase/stagehand/commit/a77efccfde3a3948013eda3a52935e8a21d45b3e) Thanks [@sameelarif](https://github.com/sameelarif)! - Unified LLM input/output types for reduced dependence on OpenAI types + +- [`b7b3701`](https://github.com/browserbase/stagehand/commit/b7b370160bf35b09f5dc132f6e86f6e34fb70a85) Thanks [@kamath](https://github.com/kamath)! - Fix $1-types exposed to the user + +- [#353](https://github.com/browserbase/stagehand/pull/353) [`5c6f14b`](https://github.com/browserbase/stagehand/commit/5c6f14bade201e08cb86d2e14e246cb65707f7ee) Thanks [@kamath](https://github.com/kamath)! - Throw custom error if context is referenced without initialization, remove act/extract handler from index + +- [#360](https://github.com/browserbase/stagehand/pull/360) [`89841fc`](https://github.com/browserbase/stagehand/commit/89841fc42ae82559baddfe2a9593bc3260c082a2) Thanks [@kamath](https://github.com/kamath)! - Remove stagehand nav entirely + +- [#379](https://github.com/browserbase/stagehand/pull/379) [`b1c6579`](https://github.com/browserbase/stagehand/commit/b1c657976847de86d82324030f90c2f6a1f3f976) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - dont require LLM Client to use non-ai stagehand functions + +- [#371](https://github.com/browserbase/stagehand/pull/371) [`30e7d09`](https://github.com/browserbase/stagehand/commit/30e7d091445004c71aec1748d3a7d75fb86d1f11) Thanks [@kamath](https://github.com/kamath)! - pretty readme :) + +- [#382](https://github.com/browserbase/stagehand/pull/382) [`a41271b`](https://github.com/browserbase/stagehand/commit/a41271baf351e20f4c79b4b654d8a947b615a121) Thanks [@sameelarif](https://github.com/sameelarif)! - Added example implementation of the Vercel AI SDK as an LLMClient + +- [#344](https://github.com/browserbase/stagehand/pull/344) [`c1cf345`](https://github.com/browserbase/stagehand/commit/c1cf34535ed30262989b1dbe262fb0414cdf8230) Thanks [@kamath](https://github.com/kamath)! - Remove duplicate logging and expose Page/BrowserContext types + +## 1.8.0 + +### Minor Changes + +- [#324](https://github.com/browserbase/stagehand/pull/324) [`cd23fa3`](https://github.com/browserbase/stagehand/commit/cd23fa33450107f29cb1ddb6edadfc769d336aa5) Thanks [@kamath](https://github.com/kamath)! - Move stagehand.act() -> stagehand.page.act() and deprecate stagehand.act() + +- [#319](https://github.com/browserbase/stagehand/pull/319) [`bacbe60`](https://github.com/browserbase/stagehand/commit/bacbe608058304bfa1f0ab049da4d8aa90e8d6f7) Thanks [@kamath](https://github.com/kamath)! - We now wrap playwright page/context within StagehandPage and StagehandContext objects. This helps us augment the Stagehand experience by being able to augment the underlying Playwright + +- [#324](https://github.com/browserbase/stagehand/pull/324) [`cd23fa3`](https://github.com/browserbase/stagehand/commit/cd23fa33450107f29cb1ddb6edadfc769d336aa5) Thanks [@kamath](https://github.com/kamath)! - moves extract and act -> page and deprecates stagehand.extract and stagehand.observe + +### Patch Changes + +- [#320](https://github.com/browserbase/stagehand/pull/320) [`c0cdd0e`](https://github.com/browserbase/stagehand/commit/c0cdd0e985d66f0464d2e70b7d0cb343b0efbd3f) Thanks [@kamath](https://github.com/kamath)! - bug fix: set this.env to LOCAL if BROWSERBASE_API_KEY is not defined + +- [#325](https://github.com/browserbase/stagehand/pull/325) [`cc46f34`](https://github.com/browserbase/stagehand/commit/cc46f345c0a1dc0af4abae7e207833df17da50e7) Thanks [@pkiv](https://github.com/pkiv)! - only start domdebug if enabled + +## 1.7.0 + +### Minor Changes + +- [#316](https://github.com/browserbase/stagehand/pull/316) [`902e633`](https://github.com/browserbase/stagehand/commit/902e633e126a58b80b757ea0ecada01a7675a473) Thanks [@kamath](https://github.com/kamath)! - rename browserbaseResumeSessionID -> browserbaseSessionID + +- [#296](https://github.com/browserbase/stagehand/pull/296) [`f11da27`](https://github.com/browserbase/stagehand/commit/f11da27a20409c240ceeea2003d520f676def61a) Thanks [@kamath](https://github.com/kamath)! - - Deprecate fields in `init` in favor of constructor options + + - Deprecate `initFromPage` in favor of `browserbaseResumeSessionID` in constructor + - Rename `browserBaseSessionCreateParams` -> `browserbaseSessionCreateParams` + +- [#304](https://github.com/browserbase/stagehand/pull/304) [`0b72f75`](https://github.com/browserbase/stagehand/commit/0b72f75f6a62aaeb28b0c488ae96db098d6a2846) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add textExtract: an optional, text based approach to the existing extract method. textExtract often performs better on long form extraction tasks. By default `extract` uses the existing approach `domExtract`. + +- [#298](https://github.com/browserbase/stagehand/pull/298) [`55f0cd2`](https://github.com/browserbase/stagehand/commit/55f0cd2fe7976e800833ec6e41e9af62d88d09d5) Thanks [@kamath](https://github.com/kamath)! - Add sessionId to public params + +### Patch Changes + +- [#283](https://github.com/browserbase/stagehand/pull/283) [`b902192`](https://github.com/browserbase/stagehand/commit/b902192bc7ff8eb02c85150c1fe6f89c2a95b211) Thanks [@sameelarif](https://github.com/sameelarif)! - allowed customization of eval config via .env + +- [#299](https://github.com/browserbase/stagehand/pull/299) [`fbe2300`](https://github.com/browserbase/stagehand/commit/fbe23007176488043c2415519f25021612fff989) Thanks [@sameelarif](https://github.com/sameelarif)! - log playwright actions for better debugging + +## 1.6.0 + +### Minor Changes + +- [#286](https://github.com/browserbase/stagehand/pull/286) [`9605836`](https://github.com/browserbase/stagehand/commit/9605836ee6b8207ed7dc9146e12ced1c78630d59) Thanks [@kamath](https://github.com/kamath)! - minor improvement in action + new eval case + +- [#279](https://github.com/browserbase/stagehand/pull/279) [`d6d7057`](https://github.com/browserbase/stagehand/commit/d6d70570623a718354797ef83aa8489eacc085d1) Thanks [@kamath](https://github.com/kamath)! - Add support for o1-mini and o1-preview in OpenAIClient + +- [#282](https://github.com/browserbase/stagehand/pull/282) [`5291797`](https://github.com/browserbase/stagehand/commit/529179724a53bf2fd578a4012fd6bc6b7348d1ae) Thanks [@kamath](https://github.com/kamath)! - Added eslint for stricter type checking. Streamlined most of the internal types throughout the cache, llm, and handlers. This should make it easier to add new LLMs down the line, maintain and update the existing code, and make it easier to add new features in the future. Types can be checked by running `npx eslint .` from the project directory. + +### Patch Changes + +- [#270](https://github.com/browserbase/stagehand/pull/270) [`6b10b3b`](https://github.com/browserbase/stagehand/commit/6b10b3b1160649b19f50d66588395ceb679b3d68) Thanks [@sameelarif](https://github.com/sameelarif)! - add close link to readme + +- [#288](https://github.com/browserbase/stagehand/pull/288) [`5afa0b9`](https://github.com/browserbase/stagehand/commit/5afa0b940a9f379a3719a5bbae249dd2a9ef8380) Thanks [@kamath](https://github.com/kamath)! - add multi-region support for browserbase + +- [#284](https://github.com/browserbase/stagehand/pull/284) [`474217c`](https://github.com/browserbase/stagehand/commit/474217cfaff8e68614212b66baa62d35493fd2ce) Thanks [@kamath](https://github.com/kamath)! - Build wasn't working, this addresses tsc failure. + +- [#236](https://github.com/browserbase/stagehand/pull/236) [`85483fe`](https://github.com/browserbase/stagehand/commit/85483fe091544fc079015c62b6923b03f8b9caa7) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - reduce chunk size + +## 1.5.0 + +### Minor Changes + +- [#266](https://github.com/browserbase/stagehand/pull/266) [`0e8f34f`](https://github.com/browserbase/stagehand/commit/0e8f34fc15aee91c548d09534deaccc8adca7c4d) Thanks [@kamath](https://github.com/kamath)! - Install wasn't working from NPM due to misconfigured build step. This attempts to fix that. + +## 1.4.0 + +### Minor Changes + +- [#253](https://github.com/browserbase/stagehand/pull/253) [`598cae2`](https://github.com/browserbase/stagehand/commit/598cae230c7b8d4e31ae22fd63047a91b63e51b8) Thanks [@sameelarif](https://github.com/sameelarif)! - clean up contexts after use + +### Patch Changes + +- [#225](https://github.com/browserbase/stagehand/pull/225) [`a2366fe`](https://github.com/browserbase/stagehand/commit/a2366feb023180fbb2ccc7a8379692f9f8347fe5) Thanks [@sameelarif](https://github.com/sameelarif)! - Ensuring cross-platform compatibility with tmp directories + +- [#249](https://github.com/browserbase/stagehand/pull/249) [`7d06d43`](https://github.com/browserbase/stagehand/commit/7d06d43f2b9a477fed35793d7479de9b183e8d53) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix broken evals + +- [#227](https://github.com/browserbase/stagehand/pull/227) [`647eefd`](https://github.com/browserbase/stagehand/commit/647eefd651852eec495faa1b8f4dbe6b1da17999) Thanks [@kamath](https://github.com/kamath)! - Fix debugDom still showing chunks when set to false + +- [#250](https://github.com/browserbase/stagehand/pull/250) [`5886620`](https://github.com/browserbase/stagehand/commit/5886620dd1b0a57c68bf810cf130df2ca0a50a69) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - add ci specific evals + +- [#222](https://github.com/browserbase/stagehand/pull/222) [`8dff026`](https://github.com/browserbase/stagehand/commit/8dff02674df7a6448f2262c7e212b58c03be57bc) Thanks [@sameelarif](https://github.com/sameelarif)! - Streamline type definitions and fix existing typescript errors + +- [#232](https://github.com/browserbase/stagehand/pull/232) [`b9f9949`](https://github.com/browserbase/stagehand/commit/b9f99494021e6a9e2487b77bb64ed0a491751400) Thanks [@kamath](https://github.com/kamath)! - Minor changes to package.json and tsconfig, mainly around the build process. Also add more type defs and remove unused dependencies. + +## 1.3.0 + +### Minor Changes + +- [#195](https://github.com/browserbase/stagehand/pull/195) [`87a6305`](https://github.com/browserbase/stagehand/commit/87a6305d9a2faf1ab5915965913bc14d5cc15772) Thanks [@kamath](https://github.com/kamath)! - - Adds structured and more standardized JSON logging + - Doesn't init cache if `enableCaching` is false, preventing `tmp/.cache` from being created + - Updates bundling for browser-side code to support NextJS and serverless + +## 1.2.0 + +### Minor Changes + +- [#179](https://github.com/browserbase/stagehand/pull/179) [`0031871`](https://github.com/browserbase/stagehand/commit/0031871d5a6d6180f272a68b88a8634e5a991785) Thanks [@navidkpr](https://github.com/navidkpr)! - Fixes: + + The last big change we pushed out, introduced a small regression. As a result, the gray outline showing the elements Stagehand is looking out is missing. This commit fixes that. We now process selectorMap properly now (using the updated type Record + + +

+ The AI Browser Automation Framework
+ Read the Docs +

+ +

+ + + + MIT License + + + + + + Slack Community + + +

+ +

+ browserbase%2Fstagehand | Trendshift +

+ +

+If you're looking for the Python implementation, you can find it + here +

+ +
+ Vibe code + Stagehand with + + Director + + + + Director + +
+ +## Why Stagehand? + +Most existing browser automation tools either require you to write low-level code in a framework like Selenium, Playwright, or Puppeteer, or use high-level agents that can be unpredictable in production. By letting developers choose what to write in code vs. natural language, Stagehand is the natural choice for browser automations in production. + +1. **Choose when to write code vs. natural language**: use AI when you want to navigate unfamiliar pages, and use code ([Playwright](https://playwright.dev/)) when you know exactly what you want to do. + +2. **Preview and cache actions**: Stagehand lets you preview AI actions before running them, and also helps you easily cache repeatable actions to save time and tokens. + +3. **Computer use models with one line of code**: Stagehand lets you integrate SOTA computer use models from OpenAI and Anthropic into the browser with one line of code. + +## Example + +Here's how to build a sample browser automation with Stagehand: + +
+
+ See Stagehand in Action +
+
+ +```typescript +// Use Playwright functions on the page object +const page = stagehand.page; +await page.goto("https://github.com/browserbase"); + +// Use act() to execute individual actions +await page.act("click on the stagehand repo"); + +// Use Computer Use agents for larger actions +const agent = stagehand.agent({ + provider: "openai", + model: "computer-use-preview", +}); +await agent.execute("Get to the latest PR"); + +// Use extract() to read data from the page +const { author, title } = await page.extract({ + instruction: "extract the author and title of the PR", + schema: z.object({ + author: z.string().describe("The username of the PR author"), + title: z.string().describe("The title of the PR"), + }), +}); +``` + +## Documentation + +Visit [docs.stagehand.dev](https://docs.stagehand.dev) to view the full documentation. + +## Getting Started + +Start with Stagehand with one line of code, or check out our [Quickstart Guide](https://docs.stagehand.dev/get_started/quickstart) for more information: + +```bash +npx create-browser-app +``` + +
+ +

Watch Anirudh demo create-browser-app to create a Stagehand project!

+
+ + + +
+ +### Build and Run from Source + +```bash +git clone https://github.com/browserbase/stagehand.git +cd stagehand +pnpm install +pnpm playwright install +pnpm run build +pnpm run example # run the blank script at ./examples/example.ts +pnpm run example 2048 # run the 2048 example at ./examples/2048.ts +``` + +Stagehand is best when you have an API key for an LLM provider and Browserbase credentials. To add these to your project, run: + +```bash +cp .env.example .env +nano .env # Edit the .env file to add API keys +``` + +## Contributing + +> [!NOTE] +> We highly value contributions to Stagehand! For questions or support, please join our [Slack community](https://join.slack.com/t/stagehand-dev/shared_invite/zt-38khc8iv5-T2acb50_0OILUaX7lxeBOg). + +At a high level, we're focused on improving reliability, speed, and cost in that order of priority. If you're interested in contributing, we strongly recommend reaching out to [Miguel Gonzalez](https://x.com/miguel_gonzf) or [Paul Klein](https://x.com/pk_iv) in our [Slack community](https://join.slack.com/t/stagehand-dev/shared_invite/zt-38khc8iv5-T2acb50_0OILUaX7lxeBOg) before starting to ensure that your contribution aligns with our goals. + +For more information, please see our [Contributing Guide](https://docs.stagehand.dev/examples/contributing). + +## Acknowledgements + +This project heavily relies on [Playwright](https://playwright.dev/) as a resilient backbone to automate the web. It also would not be possible without the awesome techniques and discoveries made by [tarsier](https://github.com/reworkd/tarsier), [gemini-zod](https://github.com/jbeoris/gemini-zod), and [fuji-web](https://github.com/normal-computing/fuji-web). + +We'd like to thank the following people for their major contributions to Stagehand: + +- [Paul Klein](https://github.com/pkiv) +- [Anirudh Kamath](https://github.com/kamath) +- [Sean McGuire](https://github.com/seanmcguire12) +- [Miguel Gonzalez](https://github.com/miguelg719) +- [Sameel Arif](https://github.com/sameelarif) +- [Filip Michalsky](https://github.com/filip-michalsky) +- [Jeremy Press](https://x.com/jeremypress) +- [Navid Pour](https://github.com/navidpour) + +## License + +Licensed under the MIT License. + +Copyright 2025 Browserbase, Inc. diff --git a/sdk/stagehand-ts/dist/evals/args.d.ts b/sdk/stagehand-ts/dist/evals/args.d.ts new file mode 100644 index 0000000..0a0aaf6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/args.d.ts @@ -0,0 +1,15 @@ +declare const parsedArgs: { + evalName?: string; + env?: string; + api?: string; + trials?: number; + concurrency?: number; + provider?: string; + dataset?: string; + max_k?: number; + leftover: string[]; +}; +declare const DEFAULT_EVAL_CATEGORIES: string[]; +declare let filterByCategory: string | null; +declare let filterByEvalName: string | null; +export { filterByCategory, filterByEvalName, DEFAULT_EVAL_CATEGORIES, parsedArgs, }; diff --git a/sdk/stagehand-ts/dist/evals/cli.d.ts b/sdk/stagehand-ts/dist/evals/cli.d.ts new file mode 100644 index 0000000..b798801 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/cli.d.ts @@ -0,0 +1,2 @@ +#!/usr/bin/env node +export {}; diff --git a/sdk/stagehand-ts/dist/evals/cli.js b/sdk/stagehand-ts/dist/evals/cli.js new file mode 100755 index 0000000..4d52fef --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/cli.js @@ -0,0 +1,1106 @@ +#!/usr/bin/env node +var __create = Object.create; +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __defNormalProp = (obj, key, value) => + key in obj + ? __defProp(obj, key, { + enumerable: true, + configurable: true, + writable: true, + value, + }) + : (obj[key] = value); +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __copyProps = (to, from, except, desc) => { + if ((from && typeof from === "object") || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { + get: () => from[key], + enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable, + }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => ( + (target = mod != null ? __create(__getProtoOf(mod)) : {}), + __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule + ? __defProp(target, "default", { value: mod, enumerable: true }) + : target, + mod, + ) +); + +// evals/cli.ts +var import_process = __toESM(require("process")); + +// node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/ansi-styles/index.js +var ANSI_BACKGROUND_OFFSET = 10; +var wrapAnsi16 = + (offset = 0) => + (code) => + `\x1B[${code + offset}m`; +var wrapAnsi256 = + (offset = 0) => + (code) => + `\x1B[${38 + offset};5;${code}m`; +var wrapAnsi16m = + (offset = 0) => + (red, green, blue) => + `\x1B[${38 + offset};2;${red};${green};${blue}m`; +var styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + // Bright color + blackBright: [90, 39], + gray: [90, 39], + // Alias of `blackBright` + grey: [90, 39], + // Alias of `blackBright` + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39], + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + // Bright color + bgBlackBright: [100, 49], + bgGray: [100, 49], + // Alias of `bgBlackBright` + bgGrey: [100, 49], + // Alias of `bgBlackBright` + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49], + }, +}; +var modifierNames = Object.keys(styles.modifier); +var foregroundColorNames = Object.keys(styles.color); +var backgroundColorNames = Object.keys(styles.bgColor); +var colorNames = [...foregroundColorNames, ...backgroundColorNames]; +function assembleStyles() { + const codes = /* @__PURE__ */ new Map(); + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\x1B[${style[0]}m`, + close: `\x1B[${style[1]}m`, + }; + group[styleName] = styles[styleName]; + codes.set(style[0], style[1]); + } + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false, + }); + } + Object.defineProperty(styles, "codes", { + value: codes, + enumerable: false, + }); + styles.color.close = "\x1B[39m"; + styles.bgColor.close = "\x1B[49m"; + styles.color.ansi = wrapAnsi16(); + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi = wrapAnsi16(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + Object.defineProperties(styles, { + rgbToAnsi256: { + value(red, green, blue) { + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + if (red > 248) { + return 231; + } + return Math.round(((red - 8) / 247) * 24) + 232; + } + return ( + 16 + + 36 * Math.round((red / 255) * 5) + + 6 * Math.round((green / 255) * 5) + + Math.round((blue / 255) * 5) + ); + }, + enumerable: false, + }, + hexToRgb: { + value(hex) { + const matches = /[a-f\d]{6}|[a-f\d]{3}/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + let [colorString] = matches; + if (colorString.length === 3) { + colorString = [...colorString] + .map((character) => character + character) + .join(""); + } + const integer = Number.parseInt(colorString, 16); + return [ + /* eslint-disable no-bitwise */ + (integer >> 16) & 255, + (integer >> 8) & 255, + integer & 255, + /* eslint-enable no-bitwise */ + ]; + }, + enumerable: false, + }, + hexToAnsi256: { + value: (hex) => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false, + }, + ansi256ToAnsi: { + value(code) { + if (code < 8) { + return 30 + code; + } + if (code < 16) { + return 90 + (code - 8); + } + let red; + let green; + let blue; + if (code >= 232) { + red = ((code - 232) * 10 + 8) / 255; + green = red; + blue = red; + } else { + code -= 16; + const remainder = code % 36; + red = Math.floor(code / 36) / 5; + green = Math.floor(remainder / 6) / 5; + blue = (remainder % 6) / 5; + } + const value = Math.max(red, green, blue) * 2; + if (value === 0) { + return 30; + } + let result = + 30 + + ((Math.round(blue) << 2) | + (Math.round(green) << 1) | + Math.round(red)); + if (value === 2) { + result += 60; + } + return result; + }, + enumerable: false, + }, + rgbToAnsi: { + value: (red, green, blue) => + styles.ansi256ToAnsi(styles.rgbToAnsi256(red, green, blue)), + enumerable: false, + }, + hexToAnsi: { + value: (hex) => styles.ansi256ToAnsi(styles.hexToAnsi256(hex)), + enumerable: false, + }, + }); + return styles; +} +var ansiStyles = assembleStyles(); +var ansi_styles_default = ansiStyles; + +// node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/vendor/supports-color/index.js +var import_node_process = __toESM(require("process"), 1); +var import_node_os = __toESM(require("os"), 1); +var import_node_tty = __toESM(require("tty"), 1); +function hasFlag( + flag, + argv = globalThis.Deno + ? globalThis.Deno.args + : import_node_process.default.argv, +) { + const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--"; + const position = argv.indexOf(prefix + flag); + const terminatorPosition = argv.indexOf("--"); + return ( + position !== -1 && + (terminatorPosition === -1 || position < terminatorPosition) + ); +} +var { env } = import_node_process.default; +var flagForceColor; +if ( + hasFlag("no-color") || + hasFlag("no-colors") || + hasFlag("color=false") || + hasFlag("color=never") +) { + flagForceColor = 0; +} else if ( + hasFlag("color") || + hasFlag("colors") || + hasFlag("color=true") || + hasFlag("color=always") +) { + flagForceColor = 1; +} +function envForceColor() { + if ("FORCE_COLOR" in env) { + if (env.FORCE_COLOR === "true") { + return 1; + } + if (env.FORCE_COLOR === "false") { + return 0; + } + return env.FORCE_COLOR.length === 0 + ? 1 + : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3); + } +} +function translateLevel(level) { + if (level === 0) { + return false; + } + return { + level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} +function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) { + const noFlagForceColor = envForceColor(); + if (noFlagForceColor !== void 0) { + flagForceColor = noFlagForceColor; + } + const forceColor = sniffFlags ? flagForceColor : noFlagForceColor; + if (forceColor === 0) { + return 0; + } + if (sniffFlags) { + if ( + hasFlag("color=16m") || + hasFlag("color=full") || + hasFlag("color=truecolor") + ) { + return 3; + } + if (hasFlag("color=256")) { + return 2; + } + } + if ("TF_BUILD" in env && "AGENT_NAME" in env) { + return 1; + } + if (haveStream && !streamIsTTY && forceColor === void 0) { + return 0; + } + const min = forceColor || 0; + if (env.TERM === "dumb") { + return min; + } + if (import_node_process.default.platform === "win32") { + const osRelease = import_node_os.default.release().split("."); + if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } + return 1; + } + if ("CI" in env) { + if ( + ["GITHUB_ACTIONS", "GITEA_ACTIONS", "CIRCLECI"].some((key) => key in env) + ) { + return 3; + } + if ( + ["TRAVIS", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some( + (sign) => sign in env, + ) || + env.CI_NAME === "codeship" + ) { + return 1; + } + return min; + } + if ("TEAMCITY_VERSION" in env) { + return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0; + } + if (env.COLORTERM === "truecolor") { + return 3; + } + if (env.TERM === "xterm-kitty") { + return 3; + } + if ("TERM_PROGRAM" in env) { + const version = Number.parseInt( + (env.TERM_PROGRAM_VERSION || "").split(".")[0], + 10, + ); + switch (env.TERM_PROGRAM) { + case "iTerm.app": { + return version >= 3 ? 3 : 2; + } + case "Apple_Terminal": { + return 2; + } + } + } + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } + if ( + /^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM) + ) { + return 1; + } + if ("COLORTERM" in env) { + return 1; + } + return min; +} +function createSupportsColor(stream, options = {}) { + const level = _supportsColor( + stream, + __spreadValues( + { + streamIsTTY: stream && stream.isTTY, + }, + options, + ), + ); + return translateLevel(level); +} +var supportsColor = { + stdout: createSupportsColor({ isTTY: import_node_tty.default.isatty(1) }), + stderr: createSupportsColor({ isTTY: import_node_tty.default.isatty(2) }), +}; +var supports_color_default = supportsColor; + +// node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/utilities.js +function stringReplaceAll(string, substring, replacer) { + let index = string.indexOf(substring); + if (index === -1) { + return string; + } + const substringLength = substring.length; + let endIndex = 0; + let returnValue = ""; + do { + returnValue += string.slice(endIndex, index) + substring + replacer; + endIndex = index + substringLength; + index = string.indexOf(substring, endIndex); + } while (index !== -1); + returnValue += string.slice(endIndex); + return returnValue; +} +function stringEncaseCRLFWithFirstIndex(string, prefix, postfix, index) { + let endIndex = 0; + let returnValue = ""; + do { + const gotCR = string[index - 1] === "\r"; + returnValue += + string.slice(endIndex, gotCR ? index - 1 : index) + + prefix + + (gotCR ? "\r\n" : "\n") + + postfix; + endIndex = index + 1; + index = string.indexOf("\n", endIndex); + } while (index !== -1); + returnValue += string.slice(endIndex); + return returnValue; +} + +// node_modules/.pnpm/chalk@5.4.1/node_modules/chalk/source/index.js +var { stdout: stdoutColor, stderr: stderrColor } = supports_color_default; +var GENERATOR = Symbol("GENERATOR"); +var STYLER = Symbol("STYLER"); +var IS_EMPTY = Symbol("IS_EMPTY"); +var levelMapping = ["ansi", "ansi", "ansi256", "ansi16m"]; +var styles2 = /* @__PURE__ */ Object.create(null); +var applyOptions = (object, options = {}) => { + if ( + options.level && + !( + Number.isInteger(options.level) && + options.level >= 0 && + options.level <= 3 + ) + ) { + throw new Error("The `level` option should be an integer from 0 to 3"); + } + const colorLevel = stdoutColor ? stdoutColor.level : 0; + object.level = options.level === void 0 ? colorLevel : options.level; +}; +var chalkFactory = (options) => { + const chalk2 = (...strings) => strings.join(" "); + applyOptions(chalk2, options); + Object.setPrototypeOf(chalk2, createChalk.prototype); + return chalk2; +}; +function createChalk(options) { + return chalkFactory(options); +} +Object.setPrototypeOf(createChalk.prototype, Function.prototype); +for (const [styleName, style] of Object.entries(ansi_styles_default)) { + styles2[styleName] = { + get() { + const builder = createBuilder( + this, + createStyler(style.open, style.close, this[STYLER]), + this[IS_EMPTY], + ); + Object.defineProperty(this, styleName, { value: builder }); + return builder; + }, + }; +} +styles2.visible = { + get() { + const builder = createBuilder(this, this[STYLER], true); + Object.defineProperty(this, "visible", { value: builder }); + return builder; + }, +}; +var getModelAnsi = (model, level, type, ...arguments_) => { + if (model === "rgb") { + if (level === "ansi16m") { + return ansi_styles_default[type].ansi16m(...arguments_); + } + if (level === "ansi256") { + return ansi_styles_default[type].ansi256( + ansi_styles_default.rgbToAnsi256(...arguments_), + ); + } + return ansi_styles_default[type].ansi( + ansi_styles_default.rgbToAnsi(...arguments_), + ); + } + if (model === "hex") { + return getModelAnsi( + "rgb", + level, + type, + ...ansi_styles_default.hexToRgb(...arguments_), + ); + } + return ansi_styles_default[type][model](...arguments_); +}; +var usedModels = ["rgb", "hex", "ansi256"]; +for (const model of usedModels) { + styles2[model] = { + get() { + const { level } = this; + return function (...arguments_) { + const styler = createStyler( + getModelAnsi(model, levelMapping[level], "color", ...arguments_), + ansi_styles_default.color.close, + this[STYLER], + ); + return createBuilder(this, styler, this[IS_EMPTY]); + }; + }, + }; + const bgModel = "bg" + model[0].toUpperCase() + model.slice(1); + styles2[bgModel] = { + get() { + const { level } = this; + return function (...arguments_) { + const styler = createStyler( + getModelAnsi(model, levelMapping[level], "bgColor", ...arguments_), + ansi_styles_default.bgColor.close, + this[STYLER], + ); + return createBuilder(this, styler, this[IS_EMPTY]); + }; + }, + }; +} +var proto = Object.defineProperties( + () => {}, + __spreadProps(__spreadValues({}, styles2), { + level: { + enumerable: true, + get() { + return this[GENERATOR].level; + }, + set(level) { + this[GENERATOR].level = level; + }, + }, + }), +); +var createStyler = (open, close, parent) => { + let openAll; + let closeAll; + if (parent === void 0) { + openAll = open; + closeAll = close; + } else { + openAll = parent.openAll + open; + closeAll = close + parent.closeAll; + } + return { + open, + close, + openAll, + closeAll, + parent, + }; +}; +var createBuilder = (self, _styler, _isEmpty) => { + const builder = (...arguments_) => + applyStyle( + builder, + arguments_.length === 1 ? "" + arguments_[0] : arguments_.join(" "), + ); + Object.setPrototypeOf(builder, proto); + builder[GENERATOR] = self; + builder[STYLER] = _styler; + builder[IS_EMPTY] = _isEmpty; + return builder; +}; +var applyStyle = (self, string) => { + if (self.level <= 0 || !string) { + return self[IS_EMPTY] ? "" : string; + } + let styler = self[STYLER]; + if (styler === void 0) { + return string; + } + const { openAll, closeAll } = styler; + if (string.includes("\x1B")) { + while (styler !== void 0) { + string = stringReplaceAll(string, styler.close, styler.open); + styler = styler.parent; + } + } + const lfIndex = string.indexOf("\n"); + if (lfIndex !== -1) { + string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); + } + return openAll + string + closeAll; +}; +Object.defineProperties(createChalk.prototype, styles2); +var chalk = createChalk(); +var chalkStderr = createChalk({ level: stderrColor ? stderrColor.level : 0 }); +var source_default = chalk; + +// evals/cli.ts +var import_fs = __toESM(require("fs")); +var import_path = __toESM(require("path")); +var import_child_process = require("child_process"); +var CONFIG_PATH = import_path.default.join(__dirname, "evals.config.json"); +function loadConfig() { + return JSON.parse(import_fs.default.readFileSync(CONFIG_PATH, "utf-8")); +} +function saveConfig(config) { + import_fs.default.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2)); +} +function printHelp() { + console.log( + source_default.yellow(`\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u287E\u283B\u28F6\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28A0\u2876\u281B\u28B3\u2846\u2800\u2800\u2800\u2800\u28B8\u2847\u2800\u28B8\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u2847\u2800\u28B8\u28F7\u2836\u28E6\u28F4\u2836\u28FE\u2847\u2800\u28B8\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u2847\u2800\u28B8\u2847\u2800\u28B8\u2847\u2800\u28B8\u2847\u2800\u28B8\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u2847\u2800\u2818\u2837\u28E4\u28BE\u284F\u2809\u2809\u2809\u2819\u28FE\u2847\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u28B8\u2847\u2800\u2800\u2800\u2800\u2808\u28FB\u287F\u281F\u2802\u2800\u28FF\u2803\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u28F7\u2800\u2800\u2800\u2800\u28B0\u284F\u2800\u2800\u2800\u2880\u28FF\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2819\u28F7\u2840\u2800\u2800\u2800\u2800\u2800\u2800\u2880\u287E\u2801\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2808\u2819\u2837\u28E6\u28E4\u28E4\u28F4\u283E\u280B\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800 +\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800\u2800`), + ); + console.log(source_default.yellow.bold("\nStagehand Evals CLI")); + console.log(source_default.cyan("\nevals [options]\n")); + console.log(source_default.magenta.underline("Commands")); + console.log(" run Execute evals or benchmarks"); + console.log(" list List available evals/benchmarks"); + console.log(" config Get/set default configuration"); + console.log(" help Show this help message\n"); + console.log(source_default.magenta.underline("Examples")); + console.log(source_default.dim(" # Run all custom evals")); + console.log(source_default.green(" evals run all\n")); + console.log(source_default.dim(" # Run specific category")); + console.log( + source_default.green(" evals run act") + + source_default.cyan(" -e browserbase -t 5\n"), + ); + console.log(source_default.dim(" # Run specific eval")); + console.log(source_default.green(" evals run login\n")); + console.log(source_default.dim(" # Run benchmark")); + console.log( + source_default.green(" evals run benchmark:onlineMind2Web") + + source_default.cyan(" -l 10 -f difficulty=easy\n"), + ); + console.log(source_default.dim(" # Configure defaults")); + console.log(source_default.green(" evals config set env browserbase")); + console.log(source_default.green(" evals config set trials 5\n")); + console.log(source_default.magenta.underline("Options")); + console.log( + source_default.cyan(" -e, --env".padEnd(20)) + + "Environment: local|browserbase", + ); + console.log( + source_default.cyan(" -t, --trials".padEnd(20)) + + "Number of trials per eval", + ); + console.log( + source_default.cyan(" -c, --concurrency".padEnd(20)) + + "Max parallel sessions", + ); + console.log( + source_default.cyan(" -m, --model".padEnd(20)) + "Model override", + ); + console.log( + source_default.cyan(" -p, --provider".padEnd(20)) + "Provider override", + ); + console.log( + source_default.cyan(" --api".padEnd(20)) + "Use Stagehand API\n", + ); + console.log(source_default.dim(" Benchmark-specific:")); + console.log( + source_default.cyan(" -l, --limit".padEnd(20)) + "Max tasks to run", + ); + console.log( + source_default.cyan(" -s, --sample".padEnd(20)) + + "Random sample before limit", + ); + console.log( + source_default.cyan(" -f, --filter".padEnd(20)) + + "Benchmark filters (key=value)\n", + ); +} +function handleConfig(args) { + const config = loadConfig(); + if (args.length === 0) { + console.log(source_default.blue.bold("\nCurrent Configuration")); + console.log(source_default.cyan("\nDefaults:")); + Object.entries(config.defaults).forEach(([key, value]) => { + console.log( + ` ${key}: ${source_default.yellow(value != null ? value : "not set")}`, + ); + }); + return; + } + if (args[0] === "set" && args.length >= 3) { + const [, key, ...valueParts] = args; + const value = valueParts.join(" "); + if (!(key in config.defaults)) { + console.error(source_default.red(`Error: Unknown config key "${key}"`)); + console.log( + source_default.dim( + `Valid keys: ${Object.keys(config.defaults).join(", ")}`, + ), + ); + import_process.default.exit(1); + } + let parsedValue = value; + if (key === "trials" || key === "concurrency") { + parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + console.error(source_default.red(`Error: ${key} must be a number`)); + import_process.default.exit(1); + } + } else if (key === "api") { + parsedValue = value === "true"; + } else if (value === "null" || value === "none") { + parsedValue = null; + } + if (key === "env") { + config.defaults.env = parsedValue; + } else if (key === "trials") { + config.defaults.trials = parsedValue; + } else if (key === "concurrency") { + config.defaults.concurrency = parsedValue; + } else if (key === "provider") { + config.defaults.provider = parsedValue; + } else if (key === "model") { + config.defaults.model = parsedValue; + } else if (key === "api") { + config.defaults.api = parsedValue; + } + saveConfig(config); + console.log(source_default.green(`\u2713 Set ${key} to ${parsedValue}`)); + } else if (args[0] === "reset") { + const defaultConfig = { + env: "local", + trials: 3, + concurrency: 3, + provider: null, + model: null, + api: false, + }; + if (args[1] && args[1] in config.defaults) { + const key = args[1]; + if (key === "env") { + config.defaults.env = defaultConfig.env; + } else if (key === "trials") { + config.defaults.trials = defaultConfig.trials; + } else if (key === "concurrency") { + config.defaults.concurrency = defaultConfig.concurrency; + } else if (key === "provider") { + config.defaults.provider = defaultConfig.provider; + } else if (key === "model") { + config.defaults.model = defaultConfig.model; + } else if (key === "api") { + config.defaults.api = defaultConfig.api; + } + saveConfig(config); + console.log(source_default.green(`\u2713 Reset ${args[1]} to default`)); + } else if (!args[1]) { + config.defaults = defaultConfig; + saveConfig(config); + console.log( + source_default.green("\u2713 Reset all settings to defaults"), + ); + } else { + console.error( + source_default.red(`Error: Unknown config key "${args[1]}"`), + ); + import_process.default.exit(1); + } + } else if (args[0] === "path") { + console.log(CONFIG_PATH); + } else { + console.error(source_default.red("Error: Invalid config command")); + console.log( + source_default.dim( + "Usage: evals config [set | reset [key] | path]", + ), + ); + import_process.default.exit(1); + } +} +function handleList(args) { + const config = loadConfig(); + console.log(source_default.blue.bold("\nAvailable Evals\n")); + const categories = /* @__PURE__ */ new Map(); + config.tasks.forEach((task) => { + task.categories.forEach((cat) => { + if (!categories.has(cat)) { + categories.set(cat, []); + } + categories.get(cat).push(task.name); + }); + }); + console.log(source_default.magenta.underline("Custom Eval Categories")); + Array.from(categories.entries()) + .filter(([cat]) => !cat.includes("external_agent_benchmarks")) + .forEach(([category, tasks]) => { + console.log( + ` ${source_default.cyan(category)} ${source_default.dim(`(${tasks.length} evals)`)}`, + ); + }); + console.log(source_default.magenta.underline("\nBenchmarks")); + Object.keys(config.benchmarks).forEach((name) => { + const shorthand = `b:${name}`; + console.log( + ` ${source_default.cyan(shorthand.padEnd(20))} ${source_default.dim(`benchmark:${name}`)}`, + ); + }); + if (args.includes("--detailed") || args.includes("-d")) { + console.log(source_default.magenta.underline("\n\nDetailed Task List")); + categories.forEach((tasks, category) => { + if (!category.includes("external_agent_benchmarks")) { + console.log( + source_default.cyan(` +${category}:`), + ); + tasks.forEach((task) => { + console.log(` - ${task}`); + }); + } + }); + } else { + console.log( + source_default.yellow( + "\n\u{1F4A1} Tip: Use 'evals list --detailed' to see all individual tasks", + ), + ); + } +} +function parseArgs(rawArgs) { + const options = {}; + const filters = []; + let target; + for (let i = 0; i < rawArgs.length; i++) { + const arg = rawArgs[i]; + if (arg.startsWith("-")) { + const flagName = arg.replace(/^--?/, ""); + const flagMap = { + e: "env", + t: "trials", + c: "concurrency", + m: "model", + p: "provider", + l: "limit", + s: "sample", + f: "filter", + }; + const optionName = flagMap[flagName] || flagName; + if (optionName === "api") { + options.api = true; + } else if (optionName === "filter") { + const filterValue = rawArgs[++i]; + if (filterValue && filterValue.includes("=")) { + const [key, value] = filterValue.split("="); + filters.push([key, value]); + } + } else { + const value = rawArgs[++i]; + if (value && !value.startsWith("-")) { + if ( + ["trials", "concurrency", "limit", "sample"].includes(optionName) + ) { + options[optionName] = parseInt(value, 10); + } else { + options[optionName] = value; + } + } + } + } else if (!target) { + target = arg; + } + } + return { options, target, filters }; +} +function handleRun(args) { + const config = loadConfig(); + const { options, target, filters } = parseArgs(args); + const finalOptions = __spreadValues( + __spreadValues({}, config.defaults), + options, + ); + const env2 = __spreadValues({}, import_process.default.env); + if (finalOptions.env === "browserbase") { + env2.EVAL_ENV = "BROWSERBASE"; + } else { + env2.EVAL_ENV = "LOCAL"; + } + if (finalOptions.api) { + env2.USE_API = "true"; + } + if (finalOptions.trials) { + env2.EVAL_TRIAL_COUNT = String(finalOptions.trials); + } + if (finalOptions.concurrency) { + env2.EVAL_MAX_CONCURRENCY = String(finalOptions.concurrency); + } + if (finalOptions.provider) { + env2.EVAL_PROVIDER = finalOptions.provider; + } + if (finalOptions.model) { + env2.EVAL_MODEL_OVERRIDE = finalOptions.model; + } + let evalName; + let categoryFilter; + if (target) { + if (target.startsWith("b:") || target.startsWith("benchmark:")) { + const benchmarkName = target.replace(/^(b:|benchmark:)/, ""); + if (!config.benchmarks[benchmarkName]) { + console.error( + source_default.red(`Error: Unknown benchmark "${benchmarkName}"`), + ); + console.log( + source_default.dim( + `Available benchmarks: ${Object.keys(config.benchmarks).join(", ")}`, + ), + ); + import_process.default.exit(1); + } + const benchmarkMap = { + webbench: "agent/webbench", + gaia: "agent/gaia", + webvoyager: "agent/webvoyager", + osworld: "agent/osworld", + onlineMind2Web: "agent/onlineMind2Web", + }; + evalName = benchmarkMap[benchmarkName]; + env2.EVAL_DATASET = benchmarkName; + if (options.limit) { + env2.EVAL_MAX_K = String(options.limit); + env2[`EVAL_${benchmarkName.toUpperCase()}_LIMIT`] = String( + options.limit, + ); + } + if (options.sample) { + env2[`EVAL_${benchmarkName.toUpperCase()}_SAMPLE`] = String( + options.sample, + ); + } + filters.forEach(([key, value]) => { + const envKey = `EVAL_${benchmarkName.toUpperCase()}_${key.toUpperCase()}`; + env2[envKey] = value; + }); + } else if (target === "all") { + } else if (target.includes("/") || target.includes("*")) { + evalName = target; + } else { + const categories = /* @__PURE__ */ new Set(); + config.tasks.forEach((task) => { + task.categories.forEach((cat) => categories.add(cat)); + }); + if (categories.has(target)) { + categoryFilter = target; + } else { + evalName = target; + } + } + } + const legacyArgs = []; + if (evalName) { + legacyArgs.push(`name=${evalName}`); + } else if (categoryFilter) { + legacyArgs.push("category", categoryFilter); + } + console.log(source_default.blue.bold("\nRunning evals...\n")); + const buildChild = (0, import_child_process.spawn)("pnpm", ["run", "build"], { + stdio: "inherit", + shell: true, + }); + buildChild.on("exit", (buildCode) => { + if (buildCode !== 0) { + import_process.default.exit(buildCode || 1); + } + const compiledEvalPath = import_path.default.join( + __dirname, + "index.eval.js", + ); + const sourceEvalPath = import_path.default.resolve( + __dirname, + "..", + "..", + "evals", + "index.eval.ts", + ); + let child; + if (import_fs.default.existsSync(compiledEvalPath)) { + child = (0, import_child_process.spawn)( + import_process.default.execPath, + [compiledEvalPath, ...legacyArgs], + { + env: env2, + stdio: "inherit", + shell: true, + }, + ); + } else { + let tsxCliPath; + try { + tsxCliPath = require.resolve("tsx/dist/cli.js"); + } catch (e) {} + const tsxArgs = [sourceEvalPath, ...legacyArgs]; + if (tsxCliPath) { + child = (0, import_child_process.spawn)( + import_process.default.execPath, + [tsxCliPath, ...tsxArgs], + { + env: env2, + stdio: "inherit", + shell: true, + }, + ); + } else { + child = (0, import_child_process.spawn)("tsx", tsxArgs, { + env: env2, + stdio: "inherit", + shell: true, + }); + } + } + child.on("exit", (code) => { + import_process.default.exit(code || 0); + }); + }); +} +function main() { + const args = import_process.default.argv.slice(2); + const command = args[0]; + const commandArgs = args.slice(1); + switch (command) { + case "run": + handleRun(commandArgs); + break; + case "list": + handleList(commandArgs); + break; + case "config": + handleConfig(commandArgs); + break; + case "help": + case "--help": + case "-h": + printHelp(); + break; + case void 0: + console.error(source_default.red("Error: No command specified")); + printHelp(); + import_process.default.exit(1); + break; + default: + if (!command.startsWith("-")) { + handleRun(args); + } else { + console.error( + source_default.red(`Error: Unknown command "${command}"`), + ); + printHelp(); + import_process.default.exit(1); + } + } +} +main(); diff --git a/sdk/stagehand-ts/dist/evals/core/summary.d.ts b/sdk/stagehand-ts/dist/evals/core/summary.d.ts new file mode 100644 index 0000000..9a9a53c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/core/summary.d.ts @@ -0,0 +1,2 @@ +import type { SummaryResult } from "@/types/evals"; +export declare const generateSummary: (results: SummaryResult[], experimentName: string) => Promise; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/bb.playwright.config.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/bb.playwright.config.d.ts new file mode 100644 index 0000000..9400fa6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/bb.playwright.config.d.ts @@ -0,0 +1,5 @@ +/** + * See https://playwright.dev/docs/test-configuration. + */ +declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>; +export default _default; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/e2e.playwright.config.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/e2e.playwright.config.d.ts new file mode 100644 index 0000000..9400fa6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/e2e.playwright.config.d.ts @@ -0,0 +1,5 @@ +/** + * See https://playwright.dev/docs/test-configuration. + */ +declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>; +export default _default; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/local.playwright.config.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/local.playwright.config.d.ts new file mode 100644 index 0000000..9400fa6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/local.playwright.config.d.ts @@ -0,0 +1,5 @@ +/** + * See https://playwright.dev/docs/test-configuration. + */ +declare const _default: import("@playwright/test").PlaywrightTestConfig<{}, {}>; +export default _default; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/stagehand.config.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/stagehand.config.d.ts new file mode 100644 index 0000000..4c2b110 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/stagehand.config.d.ts @@ -0,0 +1,3 @@ +import type { ConstructorParams } from "@browserbasehq/stagehand"; +declare const StagehandConfig: ConstructorParams; +export default StagehandConfig; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/addInitScript.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/addInitScript.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/addInitScript.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/cookies.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/cookies.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/cookies.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/multiPage.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/multiPage.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/multiPage.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/page.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/page.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/page.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/routing.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/routing.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/BrowserContext/routing.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/Errors/apiKeyError.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/Errors/apiKeyError.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/Errors/apiKeyError.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/contexts.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/contexts.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/contexts.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/downloads.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/downloads.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/downloads.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/sessions.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/sessions.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/sessions.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/uploads.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/uploads.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/browserbase/uploads.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/local/create.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/local/create.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/local/create.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/local/downloads.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/local/downloads.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/local/downloads.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addInitScript.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addInitScript.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addInitScript.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addRemoveLocatorHandler.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addRemoveLocatorHandler.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addRemoveLocatorHandler.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addTags.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addTags.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/addTags.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/bringToFront.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/bringToFront.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/bringToFront.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/content.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/content.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/content.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/evaluate.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/evaluate.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/evaluate.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/expose.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/expose.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/expose.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/frames.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/frames.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/frames.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/getBy.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/getBy.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/getBy.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/livePageProxy.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/livePageProxy.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/livePageProxy.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/navigation.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/navigation.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/navigation.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/on.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/on.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/on.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/pageContext.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/pageContext.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/pageContext.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/reload.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/reload.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/reload.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/deterministic/tests/page/waitFor.test.d.ts b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/waitFor.test.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/deterministic/tests/page/waitFor.test.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/env.d.ts b/sdk/stagehand-ts/dist/evals/env.d.ts new file mode 100644 index 0000000..47ed104 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/env.d.ts @@ -0,0 +1,13 @@ +/** + * Determine the current environment in which the evaluations are running: + * - BROWSERBASE or LOCAL + * + * The environment is read from the EVAL_ENV environment variable. + */ +export declare const env: "BROWSERBASE" | "LOCAL"; +/** + * Enable or disable caching based on the EVAL_ENABLE_CACHING environment variable. + * Caching may improve performance by not re-fetching or re-computing certain results. + * By default, caching is disabled unless explicitly enabled. + */ +export declare const enableCaching: boolean; diff --git a/sdk/stagehand-ts/dist/evals/evals.config.json b/sdk/stagehand-ts/dist/evals/evals.config.json new file mode 100644 index 0000000..5c76f88 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/evals.config.json @@ -0,0 +1,556 @@ +{ + "defaults": { + "env": "browserbase", + "trials": 1, + "concurrency": 20, + "provider": null, + "model": null, + "api": false + }, + "benchmarks": { + "webbench": { + "limit": 25, + "filters": ["difficulty", "category", "use_hitl"] + }, + "gaia": { + "limit": 25, + "filters": ["level"] + }, + "webvoyager": { + "limit": 25 + }, + "osworld": { + "limit": 25, + "filters": ["source", "evaluation_type"], + "timeout": 60000 + }, + "onlineMind2Web": { + "limit": 25 + } + }, + "tasks": [ + { + "name": "history", + "categories": ["combination"] + }, + { + "name": "expect_act_timeout", + "categories": ["regression"] + }, + { + "name": "extract_repo_name", + "categories": ["extract"] + }, + { + "name": "amazon_add_to_cart", + "categories": ["act"] + }, + { + "name": "instructions", + "categories": ["regression", "combination"] + }, + { + "name": "bidnet", + "categories": ["act"] + }, + { + "name": "ionwave", + "categories": ["act", "regression"] + }, + { + "name": "nonsense_action", + "categories": ["act"] + }, + { + "name": "peeler_simple", + "categories": ["act"] + }, + { + "name": "simple_google_search", + "categories": ["act"] + }, + { + "name": "vantechjournal", + "categories": ["act"] + }, + { + "name": "wikipedia", + "categories": ["act"] + }, + + { + "name": "allrecipes", + "categories": ["combination"] + }, + { + "name": "arxiv", + "categories": ["combination"] + }, + { + "name": "extract_collaborators", + "categories": ["combination"] + }, + { + "name": "extract_github_commits", + "categories": ["combination"] + }, + { + "name": "imdb_movie_details", + "categories": ["combination"] + }, + { + "name": "peeler_complex", + "categories": ["combination"] + }, + { + "name": "sciquest", + "categories": ["combination"] + }, + { + "name": "wichita", + "categories": ["combination", "regression"] + }, + { + "name": "hn_aisdk", + "categories": ["llm_clients"] + }, + { + "name": "hn_langchain", + "categories": ["llm_clients"] + }, + { + "name": "hn_customOpenAI", + "categories": ["llm_clients"] + }, + { + "name": "apple", + "categories": ["experimental"] + }, + { + "name": "combination_sauce", + "categories": ["experimental"] + }, + { + "name": "costar", + "categories": ["experimental"] + }, + { + "name": "extract_aigrant_companies", + "categories": ["regression"] + }, + { + "name": "extract_capacitor_info", + "categories": ["experimental"] + }, + { + "name": "extract_partners", + "categories": ["experimental"] + }, + { + "name": "extract_press_releases", + "categories": ["experimental"] + }, + { + "name": "extract_snowshoeing_destinations", + "categories": ["experimental"] + }, + { + "name": "homedepot", + "categories": ["experimental"] + }, + { + "name": "rakuten_jp", + "categories": ["experimental"] + }, + { + "name": "stock_x", + "categories": ["experimental"] + }, + { + "name": "ted_talk", + "categories": ["experimental"] + }, + + { + "name": "extract_baptist_health", + "categories": ["extract"] + }, + { + "name": "extract_github_stars", + "categories": ["extract"] + }, + { + "name": "extract_memorial_healthcare", + "categories": ["extract", "regression"] + }, + { + "name": "extract_nhl_stats", + "categories": ["extract"] + }, + { + "name": "extract_professional_info", + "categories": ["extract"] + }, + { + "name": "extract_csa", + "categories": ["extract"] + }, + { + "name": "extract_resistor_info", + "categories": ["extract"] + }, + { + "name": "extract_rockauto", + "categories": ["extract"] + }, + { + "name": "extract_staff_members", + "categories": ["extract"] + }, + + { + "name": "ionwave_observe", + "categories": ["observe"] + }, + { + "name": "panamcs", + "categories": ["observe"] + }, + { + "name": "vanta_h", + "categories": ["experimental"] + }, + { + "name": "extract_area_codes", + "categories": ["extract"] + }, + { + "name": "extract_public_notices", + "categories": ["extract"] + }, + { + "name": "extract_jstor_news", + "categories": ["extract"] + }, + { + "name": "extract_apartments", + "categories": ["extract"] + }, + { + "name": "extract_zillow", + "categories": ["extract"] + }, + { + "name": "observe_github", + "categories": ["observe", "regression"] + }, + { + "name": "observe_vantechjournal", + "categories": ["observe", "regression"] + }, + { + "name": "observe_amazon_add_to_cart", + "categories": ["observe"] + }, + { + "name": "observe_simple_google_search", + "categories": ["observe"] + }, + { + "name": "observe_yc_startup", + "categories": ["observe"] + }, + { + "name": "observe_taxes", + "categories": ["observe"] + }, + { + "name": "observe_iframes1", + "categories": ["regression", "observe"] + }, + { + "name": "observe_iframes2", + "categories": ["regression", "observe"] + }, + { + "name": "extract_hamilton_weather", + "categories": ["targeted_extract", "regression"] + }, + { + "name": "extract_regulations_table", + "categories": ["targeted_extract"] + }, + { + "name": "extract_recipe", + "categories": ["targeted_extract"] + }, + { + "name": "extract_aigrant_targeted", + "categories": ["targeted_extract"] + }, + { + "name": "extract_aigrant_targeted_2", + "categories": ["targeted_extract"] + }, + { + "name": "extract_geniusee", + "categories": ["targeted_extract"] + }, + { + "name": "extract_geniusee_2", + "categories": ["targeted_extract"] + }, + { + "name": "scroll_50", + "categories": ["regression", "act"] + }, + { + "name": "scroll_75", + "categories": ["regression", "act"] + }, + { + "name": "nextChunk", + "categories": ["regression", "act"] + }, + { + "name": "prevChunk", + "categories": ["regression", "act"] + }, + { + "name": "google_flights", + "categories": ["act"] + }, + { + "name": "extract_jfk_links", + "categories": ["extract"] + }, + { + "name": "extract_single_link", + "categories": ["extract"] + }, + { + "name": "dropdown", + "categories": ["act"] + }, + { + "name": "radio_btn", + "categories": ["act"] + }, + { + "name": "checkboxes", + "categories": ["act"] + }, + { + "name": "agent/iframe_form", + "categories": ["agent"] + }, + { + "name": "agent/iframe_form_multiple", + "categories": ["agent"] + }, + { + "name": "agent/google_flights", + "categories": ["agent"] + }, + { + "name": "agent/github_react_version", + "categories": ["agent"] + }, + { + "name": "agent/steam_games", + "categories": ["agent"] + }, + { + "name": "agent/ubereats", + "categories": ["agent"] + }, + { + "name": "agent/kith", + "categories": ["agent"] + }, + { + "name": "agent/apple_tv", + "categories": ["agent"] + }, + { + "name": "agent/apple_trade_in", + "categories": ["agent"] + }, + { + "name": "agent/arxiv_gpt_report", + "categories": ["agent"] + }, + { + "name": "agent/sf_library_card", + "categories": ["agent"] + }, + { + "name": "agent/sf_library_card_multiple", + "categories": ["agent"] + }, + { + "name": "agent/hugging_face", + "categories": ["agent"] + }, + { + "name": "agent/google_maps_3", + "categories": ["agent"] + }, + { + "name": "login", + "categories": ["act", "regression"] + }, + { + "name": "iframe_hn", + "categories": ["extract"] + }, + { + "name": "iframe_same_proc", + "categories": ["act"] + }, + { + "name": "iframe_form_filling", + "categories": ["act"] + }, + { + "name": "iframes_nested", + "categories": ["act"] + }, + { + "name": "no_js_click", + "categories": ["act", "regression"] + }, + { + "name": "tab_handling", + "categories": ["act"] + }, + { + "name": "agent/kayak", + "categories": ["agent"] + }, + { + "name": "multi_tab", + "categories": ["act"] + }, + { + "name": "shadow_dom", + "categories": ["act"] + }, + { + "name": "os_dropdown", + "categories": ["act"] + }, + { + "name": "custom_dropdown", + "categories": ["act"] + }, + { + "name": "hidden_input_dropdown", + "categories": ["act"] + }, + { + "name": "nested_iframes_2", + "categories": ["act"] + }, + { + "name": "heal_scroll_50", + "categories": ["act"] + }, + { + "name": "heal_simple_google_search", + "categories": ["regression", "act"] + }, + { + "name": "heal_custom_dropdown", + "categories": ["act"] + }, + { + "name": "agent/trivago", + "categories": ["agent"] + }, + { + "name": "agent/google_maps", + "categories": ["agent"] + }, + { + "name": "agent/google_maps_2", + "categories": ["agent"] + }, + { + "name": "agent/youtube", + "categories": ["agent"] + }, + { + "name": "agent/sign_in", + "categories": ["agent"] + }, + { + "name": "osr_in_oopif", + "categories": ["act"] + }, + { + "name": "csr_in_oopif", + "categories": ["act"] + }, + { + "name": "csr_in_spif", + "categories": ["act"] + }, + { + "name": "csr_in_spif", + "categories": ["act"] + }, + { + "name": "spif_in_osr", + "categories": ["act"] + }, + { + "name": "oopif_in_osr", + "categories": ["act"] + }, + { + "name": "spif_in_csr", + "categories": ["act"] + }, + { + "name": "oopif_in_csr", + "categories": ["act"] + }, + { + "name": "osr_in_spif", + "categories": ["act"] + }, + { + "name": "namespace_xpath", + "categories": ["act"] + }, + { + "name": "iframe_scroll", + "categories": ["act"] + }, + { + "name": "agent/gaia", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/webvoyager", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/onlineMind2Web", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/nba_trades", + "categories": ["agent"] + }, + { + "name": "agent/github", + "categories": ["agent"] + }, + { + "name": "agent/all_recipes", + "categories": ["agent"] + } + ] +} diff --git a/sdk/stagehand-ts/dist/evals/evaluator.d.ts b/sdk/stagehand-ts/dist/evals/evaluator.d.ts new file mode 100644 index 0000000..0abe31e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/evaluator.d.ts @@ -0,0 +1,29 @@ +/** + * This class is responsible for evaluating the result of an agentic task. + * The first version includes a VLM evaluator specifically prompted to evaluate the state of a task + * usually represented as a screenshot. + * The evaluator will reply with YES or NO given the state of the provided task. + */ +import { AvailableModel, ClientOptions, Stagehand } from "@browserbasehq/stagehand"; +import { EvaluateOptions, BatchAskOptions, EvaluationResult } from "@/types/evaluator"; +export declare class Evaluator { + private stagehand; + private modelName; + private modelClientOptions; + private silentLogger; + constructor(stagehand: Stagehand, modelName?: AvailableModel, modelClientOptions?: ClientOptions); + ask(options: EvaluateOptions): Promise; + /** + * Evaluates multiple questions with optional answers and/or screenshot. + * Similar to ask() but processes multiple questions in a single call. + * Returns an array of evaluation results. + * + * @param options - The options for batch evaluation + * @returns A promise that resolves to an array of EvaluationResults + */ + batchAsk(options: BatchAskOptions): Promise; + /** + * Private method to evaluate with multiple screenshots + */ + private _evaluateWithMultipleScreenshots; +} diff --git a/sdk/stagehand-ts/dist/evals/index-parallel.eval.d.ts b/sdk/stagehand-ts/dist/evals/index-parallel.eval.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/sdk/stagehand-ts/dist/evals/index.eval.d.ts b/sdk/stagehand-ts/dist/evals/index.eval.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/index.eval.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/evals/initStagehand.d.ts b/sdk/stagehand-ts/dist/evals/initStagehand.d.ts new file mode 100644 index 0000000..d018e04 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/initStagehand.d.ts @@ -0,0 +1,37 @@ +/** + * This file provides a function to initialize a Stagehand instance for use in evaluations. + * It configures the Stagehand environment and sets default options based on the current environment + * (e.g., local or BROWSERBASE), caching preferences, and verbosity. It also establishes a logger for + * capturing logs emitted by Stagehand. + * + * We create a central config object (`StagehandConfig`) that defines all parameters for Stagehand. + * + * The `initStagehand` function takes the model name, an optional DOM settling timeout, and an EvalLogger, + * then uses these to override some default values before creating and initializing the Stagehand instance. + */ +import { ConstructorParams, LLMClient } from "@browserbasehq/stagehand"; +import { EvalLogger } from "./logger"; +import type { StagehandInitResult } from "@/types/evals"; +import { AvailableModel } from "@browserbasehq/stagehand"; +/** + * Initializes a Stagehand instance for a given model: + * - modelName: The model to use (overrides default in StagehandConfig) + * - domSettleTimeoutMs: Optional timeout for DOM settling operations + * - logger: An EvalLogger instance for capturing logs + * + * Returns: + * - stagehand: The initialized Stagehand instance + * - logger: The provided logger, associated with the Stagehand instance + * - initResponse: Any response data returned by Stagehand initialization + */ +export declare const initStagehand: ({ llmClient, modelClientOptions, domSettleTimeoutMs, logger, configOverrides, actTimeoutMs, modelName, }: { + llmClient?: LLMClient; + modelClientOptions?: { + apiKey: string; + }; + domSettleTimeoutMs?: number; + logger: EvalLogger; + configOverrides?: Partial; + actTimeoutMs?: number; + modelName: AvailableModel; +}) => Promise; diff --git a/sdk/stagehand-ts/dist/evals/llm_clients/hn_aisdk.d.ts b/sdk/stagehand-ts/dist/evals/llm_clients/hn_aisdk.d.ts new file mode 100644 index 0000000..8cf1cf5 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/llm_clients/hn_aisdk.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hn_aisdk: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/llm_clients/hn_customOpenAI.d.ts b/sdk/stagehand-ts/dist/evals/llm_clients/hn_customOpenAI.d.ts new file mode 100644 index 0000000..5f7ae2c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/llm_clients/hn_customOpenAI.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hn_customOpenAI: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/llm_clients/hn_langchain.d.ts b/sdk/stagehand-ts/dist/evals/llm_clients/hn_langchain.d.ts new file mode 100644 index 0000000..4929f83 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/llm_clients/hn_langchain.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hn_langchain: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/logger.d.ts b/sdk/stagehand-ts/dist/evals/logger.d.ts new file mode 100644 index 0000000..a52c2af --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/logger.d.ts @@ -0,0 +1,50 @@ +import { LogLineEval } from "@/types/evals"; +import { Stagehand, LogLine } from "@browserbasehq/stagehand"; +/** + * EvalLogger: + * A logger class used during evaluations to capture and print log lines. + * + * Capabilities: + * - Maintains an internal array of log lines (EvalLogger.logs) for later retrieval. + * - Can be initialized with a Stagehand instance to provide consistent logging. + * - Supports logging at different levels (info, error, warn). + * - Each log line is converted to a string and printed to console for immediate feedback. + * - Also keeps a structured version of the logs that can be returned for analysis or + * included in evaluation output. + */ +export declare class EvalLogger { + private logs; + stagehand?: Stagehand; + constructor(); + /** + * init: + * Associates this logger with a given Stagehand instance. + * This allows the logger to provide additional context if needed. + */ + init(stagehand: Stagehand): void; + /** + * log: + * Logs a message at the default (info) level. + * Uses `logLineToString` to produce a readable output on the console, + * and then stores the parsed log line in `this.logs`. + */ + log(logLine: LogLine): void; + /** + * error: + * Logs an error message with `console.error` and stores it. + * Useful for capturing and differentiating error-level logs. + */ + error(logLine: LogLine): void; + /** + * warn: + * Logs a warning message with `console.warn` and stores it. + * Helps differentiate warnings from regular info logs. + */ + warn(logLine: LogLine): void; + /** + * getLogs: + * Retrieves the array of stored log lines. + * Useful for returning logs after a task completes, for analysis or debugging. + */ + getLogs(): LogLineEval[]; +} diff --git a/sdk/stagehand-ts/dist/evals/scoring.d.ts b/sdk/stagehand-ts/dist/evals/scoring.d.ts new file mode 100644 index 0000000..2453d3c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/scoring.d.ts @@ -0,0 +1,25 @@ +/** + * This file implements scoring functions needed by braintrust. + */ +import { EvalArgs, EvalInput, EvalResult } from "@/types/evals"; +/** + * Scoring function: exactMatch + * Given the arguments (including input, output, and expected result), + * this returns a score of 1 if the result matches the expectation, and 0 otherwise. + * + * If "expected" is true, it checks if the output indicates success. + * If "expected" is a boolean or an object with _success flag, + * it checks if output is exactly that success condition. + */ +export declare function exactMatch(args: EvalArgs): EvalResult; +/** + * Scoring function: errorMatch + * Determines if an error occurred in the task. + * Scores 1 if an error is found, otherwise 0. + */ +export declare function errorMatch(args: EvalArgs): EvalResult; diff --git a/sdk/stagehand-ts/dist/evals/suites/gaia.d.ts b/sdk/stagehand-ts/dist/evals/suites/gaia.d.ts new file mode 100644 index 0000000..ca4c1ef --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/suites/gaia.d.ts @@ -0,0 +1,2 @@ +import type { Testcase } from "@/types/evals"; +export declare const buildGAIATestcases: (models: string[]) => Testcase[]; diff --git a/sdk/stagehand-ts/dist/evals/suites/onlineMind2Web.d.ts b/sdk/stagehand-ts/dist/evals/suites/onlineMind2Web.d.ts new file mode 100644 index 0000000..e9c9e2c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/suites/onlineMind2Web.d.ts @@ -0,0 +1,2 @@ +import type { Testcase } from "@/types/evals"; +export declare const buildOnlineMind2WebTestcases: (models: string[]) => Testcase[]; diff --git a/sdk/stagehand-ts/dist/evals/suites/webvoyager.d.ts b/sdk/stagehand-ts/dist/evals/suites/webvoyager.d.ts new file mode 100644 index 0000000..9c2d50f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/suites/webvoyager.d.ts @@ -0,0 +1,2 @@ +import type { Testcase } from "@/types/evals"; +export declare const buildWebVoyagerTestcases: (models: string[]) => Testcase[]; diff --git a/sdk/stagehand-ts/dist/evals/taskConfig.d.ts b/sdk/stagehand-ts/dist/evals/taskConfig.d.ts new file mode 100644 index 0000000..0b62e7d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/taskConfig.d.ts @@ -0,0 +1,33 @@ +/** + * This file is responsible for: + * - Loading and parsing the `evals.config.json` file, which defines tasks (evaluations) and their associated categories. + * - Building a lookup structure (`tasksByName`) to map each task name to its categories. + * - Filtering tasks based on command-line arguments (e.g., `filterByEvalName`) and ensuring that requested tasks exist. + * - Determining which models to use for evaluations, depending on the category and environment variables. + * - Validating that the chosen models are supported. + * + * The exported objects (`tasksByName`, `MODELS`, `config`) are used by the main evaluation script and other modules + * to know which tasks and models are available, and to configure the evaluations accordingly. + */ +import { AvailableModel } from "@browserbasehq/stagehand"; +/** + * The `tasksConfig` defines all tasks from the config file. Each task has a name and categories. + * We create a mapping `tasksByName` from task name to its categories for quick lookup. + */ +type TaskConfig = { + name: string; + categories: string[]; +}; +declare const tasksConfig: TaskConfig[]; +declare const tasksByName: Record; +/** + * getModelList: + * Returns a list of models to be used for the given category. + * If category is "experimental", it merges DEFAULT_EVAL_MODELS and EXPERIMENTAL_EVAL_MODELS. + * Otherwise, returns DEFAULT_EVAL_MODELS filtered by provider if specified. + */ +declare const getModelList: (category?: string) => string[]; +declare const MODELS: AvailableModel[]; +export { tasksByName, MODELS, tasksConfig, getModelList }; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/all_recipes.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/all_recipes.d.ts new file mode 100644 index 0000000..2fba23f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/all_recipes.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const all_recipes: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/apple_trade_in.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/apple_trade_in.d.ts new file mode 100644 index 0000000..6698de1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/apple_trade_in.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const apple_trade_in: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/apple_tv.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/apple_tv.d.ts new file mode 100644 index 0000000..9b0bcc1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/apple_tv.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const apple_tv: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/arxiv_gpt_report.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/arxiv_gpt_report.d.ts new file mode 100644 index 0000000..71ee78b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/arxiv_gpt_report.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const arxiv_gpt_report: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/gaia.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/gaia.d.ts new file mode 100644 index 0000000..3236029 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/gaia.d.ts @@ -0,0 +1,9 @@ +import { EvalFunction } from "@/types/evals"; +/** + * Data-driven GAIA agent eval + * - Expects per-test params injected via eval runner: { id, level, web, ques } + * - Starts at `web`, runs the agent with `ques` as instruction + * - Requires the agent to output a final answer in the form: "Final Answer: " + * - Marks success if such an answer string is present (exact matching against dataset can be layered later) + */ +export declare const gaia: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/github.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/github.d.ts new file mode 100644 index 0000000..7841977 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/github.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const github: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/github_react_version.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/github_react_version.d.ts new file mode 100644 index 0000000..1c5fde4 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/github_react_version.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const github_react_version: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/google_flights.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/google_flights.d.ts new file mode 100644 index 0000000..1daaba3 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/google_flights.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const google_flights: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps.d.ts new file mode 100644 index 0000000..2dcd75a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const google_maps: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_2.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_2.d.ts new file mode 100644 index 0000000..aafced6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_2.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const google_maps_2: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_3.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_3.d.ts new file mode 100644 index 0000000..49daa3f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/google_maps_3.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const google_maps_3: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/google_shopping.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/google_shopping.d.ts new file mode 100644 index 0000000..befbe80 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/google_shopping.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const google_shopping: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/hotel_booking.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/hotel_booking.d.ts new file mode 100644 index 0000000..88a75ff --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/hotel_booking.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hotel_booking: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/hugging_face.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/hugging_face.d.ts new file mode 100644 index 0000000..f9d16ec --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/hugging_face.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hugging_face: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form.d.ts new file mode 100644 index 0000000..54786fb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_form: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form_multiple.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form_multiple.d.ts new file mode 100644 index 0000000..d3f64ec --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/iframe_form_multiple.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_form_multiple: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/kayak.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/kayak.d.ts new file mode 100644 index 0000000..0795365 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/kayak.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const kayak: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/kith.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/kith.d.ts new file mode 100644 index 0000000..40d183c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/kith.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const kith: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/nba_trades.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/nba_trades.d.ts new file mode 100644 index 0000000..766dd77 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/nba_trades.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const nba_trades: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/onlineMind2Web.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/onlineMind2Web.d.ts new file mode 100644 index 0000000..178dd4f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/onlineMind2Web.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const onlineMind2Web: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card.d.ts new file mode 100644 index 0000000..48b9a50 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const sf_library_card: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card_multiple.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card_multiple.d.ts new file mode 100644 index 0000000..88de3bb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/sf_library_card_multiple.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const sf_library_card_multiple: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/sign_in.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/sign_in.d.ts new file mode 100644 index 0000000..c57b75a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/sign_in.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const sign_in: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/steam_games.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/steam_games.d.ts new file mode 100644 index 0000000..ea4b546 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/steam_games.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const steam_games: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/trivago.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/trivago.d.ts new file mode 100644 index 0000000..90e7fef --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/trivago.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const trivago: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/ubereats.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/ubereats.d.ts new file mode 100644 index 0000000..144784e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/ubereats.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const ubereats: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/webvoyager.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/webvoyager.d.ts new file mode 100644 index 0000000..1506e4b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/webvoyager.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const webvoyager: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/agent/youtube.d.ts b/sdk/stagehand-ts/dist/evals/tasks/agent/youtube.d.ts new file mode 100644 index 0000000..7adf556 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/agent/youtube.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const youtube: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/allrecipes.d.ts b/sdk/stagehand-ts/dist/evals/tasks/allrecipes.d.ts new file mode 100644 index 0000000..d38ef5f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/allrecipes.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const allrecipes: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/amazon_add_to_cart.d.ts b/sdk/stagehand-ts/dist/evals/tasks/amazon_add_to_cart.d.ts new file mode 100644 index 0000000..002a1ef --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/amazon_add_to_cart.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const amazon_add_to_cart: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/apple.d.ts b/sdk/stagehand-ts/dist/evals/tasks/apple.d.ts new file mode 100644 index 0000000..193d947 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/apple.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const apple: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/arxiv.d.ts b/sdk/stagehand-ts/dist/evals/tasks/arxiv.d.ts new file mode 100644 index 0000000..cf5dad7 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/arxiv.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const arxiv: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/bidnet.d.ts b/sdk/stagehand-ts/dist/evals/tasks/bidnet.d.ts new file mode 100644 index 0000000..6f65567 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/bidnet.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const bidnet: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/checkboxes.d.ts b/sdk/stagehand-ts/dist/evals/tasks/checkboxes.d.ts new file mode 100644 index 0000000..dee7b9f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/checkboxes.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const checkboxes: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/combination_sauce.d.ts b/sdk/stagehand-ts/dist/evals/tasks/combination_sauce.d.ts new file mode 100644 index 0000000..9f560a8 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/combination_sauce.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const combination_sauce: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/costar.d.ts b/sdk/stagehand-ts/dist/evals/tasks/costar.d.ts new file mode 100644 index 0000000..4977532 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/costar.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const costar: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/csr_in_oopif.d.ts b/sdk/stagehand-ts/dist/evals/tasks/csr_in_oopif.d.ts new file mode 100644 index 0000000..5229022 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/csr_in_oopif.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const csr_in_oopif: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/csr_in_spif.d.ts b/sdk/stagehand-ts/dist/evals/tasks/csr_in_spif.d.ts new file mode 100644 index 0000000..ce0110d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/csr_in_spif.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const csr_in_spif: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/custom_dropdown.d.ts b/sdk/stagehand-ts/dist/evals/tasks/custom_dropdown.d.ts new file mode 100644 index 0000000..59c3e75 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/custom_dropdown.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const custom_dropdown: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/dropdown.d.ts b/sdk/stagehand-ts/dist/evals/tasks/dropdown.d.ts new file mode 100644 index 0000000..2155fd1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/dropdown.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const dropdown: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/expect_act_timeout.d.ts b/sdk/stagehand-ts/dist/evals/tasks/expect_act_timeout.d.ts new file mode 100644 index 0000000..6a144f0 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/expect_act_timeout.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const expect_act_timeout: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_companies.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_companies.d.ts new file mode 100644 index 0000000..e0207e3 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_companies.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_aigrant_companies: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted.d.ts new file mode 100644 index 0000000..6de2188 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_aigrant_targeted: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted_2.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted_2.d.ts new file mode 100644 index 0000000..7c341ee --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_aigrant_targeted_2.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_aigrant_targeted_2: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_apartments.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_apartments.d.ts new file mode 100644 index 0000000..84aa2c1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_apartments.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "../../types/evals"; +export declare const extract_apartments: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_area_codes.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_area_codes.d.ts new file mode 100644 index 0000000..1b454e5 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_area_codes.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_area_codes: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_baptist_health.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_baptist_health.d.ts new file mode 100644 index 0000000..2d25aa1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_baptist_health.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_baptist_health: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_capacitor_info.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_capacitor_info.d.ts new file mode 100644 index 0000000..a141235 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_capacitor_info.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_capacitor_info: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_collaborators.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_collaborators.d.ts new file mode 100644 index 0000000..bb5ce26 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_collaborators.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_collaborators: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_csa.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_csa.d.ts new file mode 100644 index 0000000..3351026 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_csa.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_csa: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee.d.ts new file mode 100644 index 0000000..3f294cb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_geniusee: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee_2.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee_2.d.ts new file mode 100644 index 0000000..82d6cc7 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_geniusee_2.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_geniusee_2: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_github_commits.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_github_commits.d.ts new file mode 100644 index 0000000..dd3befa --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_github_commits.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_github_commits: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_github_stars.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_github_stars.d.ts new file mode 100644 index 0000000..588213b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_github_stars.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_github_stars: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_hamilton_weather.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_hamilton_weather.d.ts new file mode 100644 index 0000000..923f8b6 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_hamilton_weather.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_hamilton_weather: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_jfk_links.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_jfk_links.d.ts new file mode 100644 index 0000000..273e958 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_jfk_links.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_jfk_links: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_jstor_news.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_jstor_news.d.ts new file mode 100644 index 0000000..e4efd12 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_jstor_news.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_jstor_news: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_memorial_healthcare.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_memorial_healthcare.d.ts new file mode 100644 index 0000000..2b2fd6b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_memorial_healthcare.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_memorial_healthcare: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_nhl_stats.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_nhl_stats.d.ts new file mode 100644 index 0000000..03a4171 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_nhl_stats.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_nhl_stats: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_partners.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_partners.d.ts new file mode 100644 index 0000000..369159d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_partners.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_partners: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_press_releases.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_press_releases.d.ts new file mode 100644 index 0000000..5673d25 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_press_releases.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_press_releases: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_professional_info.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_professional_info.d.ts new file mode 100644 index 0000000..7df283c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_professional_info.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_professional_info: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_public_notices.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_public_notices.d.ts new file mode 100644 index 0000000..517e334 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_public_notices.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_public_notices: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_recipe.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_recipe.d.ts new file mode 100644 index 0000000..2bb710f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_recipe.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_recipe: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_regulations_table.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_regulations_table.d.ts new file mode 100644 index 0000000..68ce80d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_regulations_table.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_regulations_table: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_repo_name.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_repo_name.d.ts new file mode 100644 index 0000000..f278a54 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_repo_name.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_repo_name: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_resistor_info.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_resistor_info.d.ts new file mode 100644 index 0000000..dfd2d1d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_resistor_info.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_resistor_info: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_rockauto.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_rockauto.d.ts new file mode 100644 index 0000000..5bdf714 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_rockauto.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_rockauto: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_single_link.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_single_link.d.ts new file mode 100644 index 0000000..d59e28f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_single_link.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_single_link: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_snowshoeing_destinations.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_snowshoeing_destinations.d.ts new file mode 100644 index 0000000..2ee1e88 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_snowshoeing_destinations.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_snowshoeing_destinations: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_staff_members.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_staff_members.d.ts new file mode 100644 index 0000000..4bba9ee --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_staff_members.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const extract_staff_members: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/extract_zillow.d.ts b/sdk/stagehand-ts/dist/evals/tasks/extract_zillow.d.ts new file mode 100644 index 0000000..f68940c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/extract_zillow.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "../../types/evals"; +export declare const extract_zillow: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/google_flights.d.ts b/sdk/stagehand-ts/dist/evals/tasks/google_flights.d.ts new file mode 100644 index 0000000..e48b72c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/google_flights.d.ts @@ -0,0 +1,11 @@ +import { EvalFunction } from "@/types/evals"; +/** + * This eval attempts to click on an element that should not pass the playwright actionability check + * which happens by default if you call locator.click (more information here: + * https://playwright.dev/docs/actionability) + * + * If this eval passes, it means that we have correctly set {force: true} in performPlaywrightMethod, + * and the click was successful even though the target element (found by the xpath) did not + * pass the actionability check. + */ +export declare const google_flights: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/heal_custom_dropdown.d.ts b/sdk/stagehand-ts/dist/evals/tasks/heal_custom_dropdown.d.ts new file mode 100644 index 0000000..883fa67 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/heal_custom_dropdown.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const heal_custom_dropdown: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/heal_scroll_50.d.ts b/sdk/stagehand-ts/dist/evals/tasks/heal_scroll_50.d.ts new file mode 100644 index 0000000..2da30ff --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/heal_scroll_50.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const heal_scroll_50: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/heal_simple_google_search.d.ts b/sdk/stagehand-ts/dist/evals/tasks/heal_simple_google_search.d.ts new file mode 100644 index 0000000..98c740f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/heal_simple_google_search.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const heal_simple_google_search: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/hidden_input_dropdown.d.ts b/sdk/stagehand-ts/dist/evals/tasks/hidden_input_dropdown.d.ts new file mode 100644 index 0000000..2718fa2 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/hidden_input_dropdown.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const hidden_input_dropdown: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/history.d.ts b/sdk/stagehand-ts/dist/evals/tasks/history.d.ts new file mode 100644 index 0000000..ff9c650 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/history.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const history: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/homedepot.d.ts b/sdk/stagehand-ts/dist/evals/tasks/homedepot.d.ts new file mode 100644 index 0000000..73cc6f0 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/homedepot.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const homedepot: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/iframe_form_filling.d.ts b/sdk/stagehand-ts/dist/evals/tasks/iframe_form_filling.d.ts new file mode 100644 index 0000000..162d8c5 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/iframe_form_filling.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_form_filling: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/iframe_hn.d.ts b/sdk/stagehand-ts/dist/evals/tasks/iframe_hn.d.ts new file mode 100644 index 0000000..25422d1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/iframe_hn.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_hn: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/iframe_same_proc.d.ts b/sdk/stagehand-ts/dist/evals/tasks/iframe_same_proc.d.ts new file mode 100644 index 0000000..6f3bfca --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/iframe_same_proc.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_same_proc: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/iframe_scroll.d.ts b/sdk/stagehand-ts/dist/evals/tasks/iframe_scroll.d.ts new file mode 100644 index 0000000..c5d7ea8 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/iframe_scroll.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframe_scroll: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/iframes_nested.d.ts b/sdk/stagehand-ts/dist/evals/tasks/iframes_nested.d.ts new file mode 100644 index 0000000..7d326cb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/iframes_nested.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const iframes_nested: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/imdb_movie_details.d.ts b/sdk/stagehand-ts/dist/evals/tasks/imdb_movie_details.d.ts new file mode 100644 index 0000000..4f2c89a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/imdb_movie_details.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const imdb_movie_details: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/instructions.d.ts b/sdk/stagehand-ts/dist/evals/tasks/instructions.d.ts new file mode 100644 index 0000000..53d6e7b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/instructions.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const instructions: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/ionwave.d.ts b/sdk/stagehand-ts/dist/evals/tasks/ionwave.d.ts new file mode 100644 index 0000000..b9375bb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/ionwave.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const ionwave: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/ionwave_observe.d.ts b/sdk/stagehand-ts/dist/evals/tasks/ionwave_observe.d.ts new file mode 100644 index 0000000..654e6c4 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/ionwave_observe.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const ionwave_observe: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/login.d.ts b/sdk/stagehand-ts/dist/evals/tasks/login.d.ts new file mode 100644 index 0000000..eafe796 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/login.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const login: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/multi_tab.d.ts b/sdk/stagehand-ts/dist/evals/tasks/multi_tab.d.ts new file mode 100644 index 0000000..6354842 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/multi_tab.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const multi_tab: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/namespace_xpath.d.ts b/sdk/stagehand-ts/dist/evals/tasks/namespace_xpath.d.ts new file mode 100644 index 0000000..f6aff2e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/namespace_xpath.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const namespace_xpath: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/nested_iframes_2.d.ts b/sdk/stagehand-ts/dist/evals/tasks/nested_iframes_2.d.ts new file mode 100644 index 0000000..0dc287e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/nested_iframes_2.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const nested_iframes_2: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/nextChunk.d.ts b/sdk/stagehand-ts/dist/evals/tasks/nextChunk.d.ts new file mode 100644 index 0000000..063c0e1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/nextChunk.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const nextChunk: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/no_js_click.d.ts b/sdk/stagehand-ts/dist/evals/tasks/no_js_click.d.ts new file mode 100644 index 0000000..f626bc5 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/no_js_click.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const no_js_click: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/nonsense_action.d.ts b/sdk/stagehand-ts/dist/evals/tasks/nonsense_action.d.ts new file mode 100644 index 0000000..38330cf --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/nonsense_action.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const nonsense_action: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_amazon_add_to_cart.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_amazon_add_to_cart.d.ts new file mode 100644 index 0000000..ec06943 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_amazon_add_to_cart.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_amazon_add_to_cart: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_github.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_github.d.ts new file mode 100644 index 0000000..b9b8a4c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_github.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_github: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_iframes1.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_iframes1.d.ts new file mode 100644 index 0000000..15fcb11 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_iframes1.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_iframes1: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_iframes2.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_iframes2.d.ts new file mode 100644 index 0000000..9d9056b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_iframes2.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_iframes2: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_simple_google_search.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_simple_google_search.d.ts new file mode 100644 index 0000000..23f06cb --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_simple_google_search.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_simple_google_search: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_taxes.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_taxes.d.ts new file mode 100644 index 0000000..35486bd --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_taxes.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_taxes: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_vantechjournal.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_vantechjournal.d.ts new file mode 100644 index 0000000..05ea11a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_vantechjournal.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_vantechjournal: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/observe_yc_startup.d.ts b/sdk/stagehand-ts/dist/evals/tasks/observe_yc_startup.d.ts new file mode 100644 index 0000000..045ac99 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/observe_yc_startup.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const observe_yc_startup: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/oopif_in_csr.d.ts b/sdk/stagehand-ts/dist/evals/tasks/oopif_in_csr.d.ts new file mode 100644 index 0000000..ae0391e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/oopif_in_csr.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const oopif_in_csr: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/oopif_in_osr.d.ts b/sdk/stagehand-ts/dist/evals/tasks/oopif_in_osr.d.ts new file mode 100644 index 0000000..ca7c26e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/oopif_in_osr.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const oopif_in_osr: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/os_dropdown.d.ts b/sdk/stagehand-ts/dist/evals/tasks/os_dropdown.d.ts new file mode 100644 index 0000000..eeb75dc --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/os_dropdown.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const os_dropdown: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/osr_in_oopif.d.ts b/sdk/stagehand-ts/dist/evals/tasks/osr_in_oopif.d.ts new file mode 100644 index 0000000..58f041c --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/osr_in_oopif.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const osr_in_oopif: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/osr_in_spif.d.ts b/sdk/stagehand-ts/dist/evals/tasks/osr_in_spif.d.ts new file mode 100644 index 0000000..14854aa --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/osr_in_spif.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const osr_in_spif: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/panamcs.d.ts b/sdk/stagehand-ts/dist/evals/tasks/panamcs.d.ts new file mode 100644 index 0000000..aecab8f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/panamcs.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const panamcs: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/peeler_complex.d.ts b/sdk/stagehand-ts/dist/evals/tasks/peeler_complex.d.ts new file mode 100644 index 0000000..90c114d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/peeler_complex.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const peeler_complex: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/peeler_simple.d.ts b/sdk/stagehand-ts/dist/evals/tasks/peeler_simple.d.ts new file mode 100644 index 0000000..ba5b672 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/peeler_simple.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const peeler_simple: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/prevChunk.d.ts b/sdk/stagehand-ts/dist/evals/tasks/prevChunk.d.ts new file mode 100644 index 0000000..3359cdc --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/prevChunk.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const prevChunk: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/radio_btn.d.ts b/sdk/stagehand-ts/dist/evals/tasks/radio_btn.d.ts new file mode 100644 index 0000000..c1df7df --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/radio_btn.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const radio_btn: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/rakuten_jp.d.ts b/sdk/stagehand-ts/dist/evals/tasks/rakuten_jp.d.ts new file mode 100644 index 0000000..80ad5e1 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/rakuten_jp.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const rakuten_jp: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/sciquest.d.ts b/sdk/stagehand-ts/dist/evals/tasks/sciquest.d.ts new file mode 100644 index 0000000..47de830 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/sciquest.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const sciquest: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/scroll_50.d.ts b/sdk/stagehand-ts/dist/evals/tasks/scroll_50.d.ts new file mode 100644 index 0000000..3c06ac9 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/scroll_50.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const scroll_50: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/scroll_75.d.ts b/sdk/stagehand-ts/dist/evals/tasks/scroll_75.d.ts new file mode 100644 index 0000000..d190a3e --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/scroll_75.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const scroll_75: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/shadow_dom.d.ts b/sdk/stagehand-ts/dist/evals/tasks/shadow_dom.d.ts new file mode 100644 index 0000000..3b8e5bf --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/shadow_dom.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const shadow_dom: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/simple_google_search.d.ts b/sdk/stagehand-ts/dist/evals/tasks/simple_google_search.d.ts new file mode 100644 index 0000000..338a3ce --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/simple_google_search.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const simple_google_search: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/spif_in_csr.d.ts b/sdk/stagehand-ts/dist/evals/tasks/spif_in_csr.d.ts new file mode 100644 index 0000000..bfb2f7a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/spif_in_csr.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const spif_in_csr: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/spif_in_osr.d.ts b/sdk/stagehand-ts/dist/evals/tasks/spif_in_osr.d.ts new file mode 100644 index 0000000..0b09e63 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/spif_in_osr.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const spif_in_osr: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/stock_x.d.ts b/sdk/stagehand-ts/dist/evals/tasks/stock_x.d.ts new file mode 100644 index 0000000..011bc71 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/stock_x.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const stock_x: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/tab_handling.d.ts b/sdk/stagehand-ts/dist/evals/tasks/tab_handling.d.ts new file mode 100644 index 0000000..ec00416 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/tab_handling.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const tab_handling: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/ted_talk.d.ts b/sdk/stagehand-ts/dist/evals/tasks/ted_talk.d.ts new file mode 100644 index 0000000..ec44c1a --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/ted_talk.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const ted_talk: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/vanta_h.d.ts b/sdk/stagehand-ts/dist/evals/tasks/vanta_h.d.ts new file mode 100644 index 0000000..83388f2 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/vanta_h.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const vanta_h: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/vantechjournal.d.ts b/sdk/stagehand-ts/dist/evals/tasks/vantechjournal.d.ts new file mode 100644 index 0000000..1932f4b --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/vantechjournal.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const vantechjournal: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/wichita.d.ts b/sdk/stagehand-ts/dist/evals/tasks/wichita.d.ts new file mode 100644 index 0000000..448b201 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/wichita.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const wichita: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/tasks/wikipedia.d.ts b/sdk/stagehand-ts/dist/evals/tasks/wikipedia.d.ts new file mode 100644 index 0000000..f80e73d --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/tasks/wikipedia.d.ts @@ -0,0 +1,2 @@ +import { EvalFunction } from "@/types/evals"; +export declare const wikipedia: EvalFunction; diff --git a/sdk/stagehand-ts/dist/evals/utils.d.ts b/sdk/stagehand-ts/dist/evals/utils.d.ts new file mode 100644 index 0000000..c2818e5 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/utils.d.ts @@ -0,0 +1,61 @@ +import { LogLine } from "@browserbasehq/stagehand"; +/** + * normalizeString: + * Prepares a string for comparison by: + * - Converting to lowercase + * - Collapsing multiple spaces to a single space + * - Removing punctuation and special characters that are not alphabetic or numeric + * - Normalizing spacing around commas + * - Trimming leading and trailing whitespace + * + * This helps create a stable string representation to compare against expected outputs, + * even if the actual output contains minor formatting differences. + */ +export declare function normalizeString(str: string): string; +/** + * compareStrings: + * Compares two strings (actual vs. expected) using a similarity metric (Jaro-Winkler). + * + * Arguments: + * - actual: The actual output string to be checked. + * - expected: The expected string we want to match against. + * - similarityThreshold: A number between 0 and 1. Default is 0.85. + * If the computed similarity is greater than or equal to this threshold, + * we consider the strings sufficiently similar. + * + * Returns: + * - similarity: A number indicating how similar the two strings are. + * - meetsThreshold: A boolean indicating if the similarity meets or exceeds the threshold. + * + * This function is useful for tasks where exact string matching is too strict, + * allowing for fuzzy matching that tolerates minor differences in formatting or spelling. + */ +export declare function compareStrings(actual: string, expected: string, similarityThreshold?: number): { + similarity: number; + meetsThreshold: boolean; +}; +/** + * generateTimestamp: + * Generates a timestamp string formatted as "YYYYMMDDHHMMSS". + * Used to create unique experiment names, ensuring that results can be + * distinguished by the time they were generated. + */ +export declare function generateTimestamp(): string; +/** + * generateExperimentName: + * Creates a unique name for the experiment based on optional evalName or category, + * the environment (e.g., dev or CI), and the current timestamp. + * This is used to label the output files and directories. + */ +export declare function generateExperimentName({ evalName, category, environment, }: { + evalName?: string; + category?: string; + environment: string; +}): string; +export declare function logLineToString(logLine: LogLine): string; +export declare function dedent(strings: TemplateStringsArray, ...values: unknown[]): string; +export declare function sampleUniform(arr: T[], k: number): T[]; +export declare function readJsonlFile(filePath: string): string[]; +export declare function parseJsonlRows(lines: string[], validator: (parsed: unknown) => parsed is T): T[]; +export declare function applySampling(candidates: T[], sampleCount?: number, maxCases?: number): T[]; +export declare function optimizedScreenshot(img: Buffer, scaleFactor: number): Promise; diff --git a/sdk/stagehand-ts/dist/evals/utils/ScreenshotCollector.d.ts b/sdk/stagehand-ts/dist/evals/utils/ScreenshotCollector.d.ts new file mode 100644 index 0000000..988fed4 --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/utils/ScreenshotCollector.d.ts @@ -0,0 +1,34 @@ +import { Page } from "@playwright/test"; +export interface ScreenshotCollectorOptions { + interval?: number; + maxScreenshots?: number; + captureOnNavigation?: boolean; +} +export declare class ScreenshotCollector { + private screenshots; + private page; + private interval; + private maxScreenshots; + private captureOnNavigation; + private intervalId?; + private navigationListeners; + private isCapturing; + private lastScreenshot?; + private ssimThreshold; + private mseThreshold; + constructor(page: Page, options?: ScreenshotCollectorOptions); + start(): void; + stop(): Buffer[]; + private captureScreenshot; + getScreenshots(): Buffer[]; + getScreenshotCount(): number; + clear(): void; + /** + * Manually add a screenshot to the collection + * @param screenshot The screenshot buffer to add + * @param source Optional source identifier for logging + */ + addScreenshot(screenshot: Buffer): Promise; + private calculateMSE; + private calculateSSIM; +} diff --git a/sdk/stagehand-ts/dist/evals/utils/imageResize.d.ts b/sdk/stagehand-ts/dist/evals/utils/imageResize.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/sdk/stagehand-ts/dist/evals/utils/imageUtils.d.ts b/sdk/stagehand-ts/dist/evals/utils/imageUtils.d.ts new file mode 100644 index 0000000..d8de55f --- /dev/null +++ b/sdk/stagehand-ts/dist/evals/utils/imageUtils.d.ts @@ -0,0 +1 @@ +export declare function imageResize(img: Buffer, scaleFactor: number): Promise; diff --git a/sdk/stagehand-ts/dist/evals/worker.d.ts b/sdk/stagehand-ts/dist/evals/worker.d.ts new file mode 100644 index 0000000..e69de29 diff --git a/sdk/stagehand-ts/dist/examples/2048.d.ts b/sdk/stagehand-ts/dist/examples/2048.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/2048.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/actionable_observe_example.d.ts b/sdk/stagehand-ts/dist/examples/actionable_observe_example.d.ts new file mode 100644 index 0000000..262f7d5 --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/actionable_observe_example.d.ts @@ -0,0 +1,14 @@ +/** + * This example shows how to use actionable observe() + * + * You can use observe to get a cache-able Playwright action as JSON, then pass that JSON to act() to perform the action. + * + * This is useful for: + * - Previewing actions before running them + * - Saving actions to a file and replaying them later + * - Hiding sensitive information from LLMs + * + * For more on caching, see: https://docs.stagehand.dev/examples/caching + * Also check out the form_filling_sensible.ts example for a more complex example of using observe() to fill out a form. + */ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/bb-cua-example.d.ts b/sdk/stagehand-ts/dist/examples/bb-cua-example.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/bb-cua-example.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/cua-example.d.ts b/sdk/stagehand-ts/dist/examples/cua-example.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/cua-example.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/custom_client_aisdk.d.ts b/sdk/stagehand-ts/dist/examples/custom_client_aisdk.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/custom_client_aisdk.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/custom_client_langchain.d.ts b/sdk/stagehand-ts/dist/examples/custom_client_langchain.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/custom_client_langchain.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/custom_client_openai.d.ts b/sdk/stagehand-ts/dist/examples/custom_client_openai.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/custom_client_openai.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/example.d.ts b/sdk/stagehand-ts/dist/examples/example.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/example.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/external_clients/aisdk.d.ts b/sdk/stagehand-ts/dist/examples/external_clients/aisdk.d.ts new file mode 100644 index 0000000..5968b32 --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/external_clients/aisdk.d.ts @@ -0,0 +1,11 @@ +import { LanguageModel } from "ai"; +import { CreateChatCompletionOptions, LLMClient } from "@browserbasehq/stagehand"; +import { ChatCompletion } from "openai/resources"; +export declare class AISdkClient extends LLMClient { + type: "aisdk"; + private model; + constructor({ model }: { + model: LanguageModel; + }); + createChatCompletion({ options, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/examples/external_clients/customOpenAI.d.ts b/sdk/stagehand-ts/dist/examples/external_clients/customOpenAI.d.ts new file mode 100644 index 0000000..cf0afe9 --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/external_clients/customOpenAI.d.ts @@ -0,0 +1,18 @@ +/** + * Welcome to the Stagehand custom OpenAI client! + * + * This is a client for models that are compatible with the OpenAI API, like Ollama, Gemini, etc. + * You can just pass in an OpenAI instance to the client and it will work. + */ +import { CreateChatCompletionOptions, LLMClient } from "@browserbasehq/stagehand"; +import OpenAI from "openai"; +import type { ChatCompletion } from "openai/resources/chat/completions"; +export declare class CustomOpenAIClient extends LLMClient { + type: "openai"; + private client; + constructor({ modelName, client }: { + modelName: string; + client: OpenAI; + }); + createChatCompletion({ options, retries, logger, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/examples/external_clients/langchain.d.ts b/sdk/stagehand-ts/dist/examples/external_clients/langchain.d.ts new file mode 100644 index 0000000..330e5e0 --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/external_clients/langchain.d.ts @@ -0,0 +1,9 @@ +import { BaseChatModel } from "@langchain/core/language_models/chat_models"; +import { CreateChatCompletionOptions, LLMClient } from "@browserbasehq/stagehand"; +import { ChatCompletion } from "openai/resources"; +export declare class LangchainClient extends LLMClient { + type: "langchainClient"; + private model; + constructor(model: BaseChatModel); + createChatCompletion({ options, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/examples/form_filling_sensible.d.ts b/sdk/stagehand-ts/dist/examples/form_filling_sensible.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/form_filling_sensible.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/google_enter.d.ts b/sdk/stagehand-ts/dist/examples/google_enter.d.ts new file mode 100644 index 0000000..a5cd71f --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/google_enter.d.ts @@ -0,0 +1,6 @@ +/** + * This example shows how to use the Stagehand agent to navigate to Google and search for "Browserbase". + * + * It's mainly meant to sanity check using page.act() to press enter, since some LLMs have issues with it. + */ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/instructions.d.ts b/sdk/stagehand-ts/dist/examples/instructions.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/instructions.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/local-cua-example.d.ts b/sdk/stagehand-ts/dist/examples/local-cua-example.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/local-cua-example.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/operator-example.d.ts b/sdk/stagehand-ts/dist/examples/operator-example.d.ts new file mode 100644 index 0000000..40bc14e --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/operator-example.d.ts @@ -0,0 +1,8 @@ +/** + * This example shows how to use the Stagehand operator to do simple autonomous tasks. + * + * This is built off of our open source project, Open Operator: https://operator.browserbase.com + * + * To learn more about Stagehand Agents, see: https://docs.stagehand.dev/concepts/agent + */ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/parameterizeApiKey.d.ts b/sdk/stagehand-ts/dist/examples/parameterizeApiKey.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/parameterizeApiKey.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/popup.d.ts b/sdk/stagehand-ts/dist/examples/popup.d.ts new file mode 100644 index 0000000..9fc8c59 --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/popup.d.ts @@ -0,0 +1,6 @@ +/** + * This example shows how to use nested Stagehand pages within event listeners + * + * It also shows how to wait for something to happen on a page before continuing. + */ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/pwtest.d.ts b/sdk/stagehand-ts/dist/examples/pwtest.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/pwtest.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/examples/wordle.d.ts b/sdk/stagehand-ts/dist/examples/wordle.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/examples/wordle.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/index.d.ts b/sdk/stagehand-ts/dist/index.d.ts new file mode 100644 index 0000000..3021ee2 --- /dev/null +++ b/sdk/stagehand-ts/dist/index.d.ts @@ -0,0 +1,1045 @@ +import { Cookie, Page as Page$1, Browser as Browser$1, BrowserContext as BrowserContext$1, Frame, CDPSession } from 'playwright'; +import { z, ZodType, ZodError } from 'zod/v3'; +import Browserbase from '@browserbasehq/sdk'; +import { ClientOptions as ClientOptions$2 } from '@anthropic-ai/sdk'; +import { ClientOptions as ClientOptions$1 } from 'openai'; +import { generateObject, generateText, streamText, streamObject, experimental_generateImage, embed, embedMany, experimental_transcribe, experimental_generateSpeech } from 'ai'; + +type LogLevel = 0 | 1 | 2; +/** + * Mapping between numeric log levels and their names + * + * 0 - error/warn - Critical issues or important warnings + * 1 - info - Standard information messages + * 2 - debug - Detailed information for debugging + */ +declare const LOG_LEVEL_NAMES: Record; +type LogLine = { + id?: string; + category?: string; + message: string; + level?: LogLevel; + timestamp?: string; + auxiliary?: { + [key: string]: { + value: string; + type: "object" | "string" | "html" | "integer" | "float" | "boolean"; + }; + }; +}; +type Logger = (logLine: LogLine) => void; + +declare const AvailableModelSchema: z.ZodEnum<["gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "o4-mini", "o3", "o3-mini", "o1", "o1-mini", "gpt-4o", "gpt-4o-mini", "gpt-4o-2024-08-06", "gpt-4.5-preview", "o1-preview", "claude-3-5-sonnet-latest", "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-20240620", "claude-3-7-sonnet-latest", "claude-3-7-sonnet-20250219", "cerebras-llama-3.3-70b", "cerebras-llama-3.1-8b", "groq-llama-3.3-70b-versatile", "groq-llama-3.3-70b-specdec", "gemini-1.5-flash", "gemini-1.5-pro", "gemini-1.5-flash-8b", "gemini-2.0-flash-lite", "gemini-2.0-flash", "gemini-2.5-flash-preview-04-17", "gemini-2.5-pro-preview-03-25"]>; +type AvailableModel = z.infer | string; +type ModelProvider = "openai" | "anthropic" | "cerebras" | "groq" | "google" | "aisdk"; +type ClientOptions = ClientOptions$1 | ClientOptions$2; +interface AnthropicJsonSchemaObject { + definitions?: { + MySchema?: { + properties?: Record; + required?: string[]; + }; + }; + properties?: Record; + required?: string[]; +} + +interface LLMTool { + type: "function"; + name: string; + description: string; + parameters: Record; +} + +interface ChatMessage { + role: "system" | "user" | "assistant"; + content: ChatMessageContent; +} +type ChatMessageContent = string | (ChatMessageImageContent | ChatMessageTextContent)[]; +interface ChatMessageImageContent { + type: string; + image_url?: { + url: string; + }; + text?: string; + source?: { + type: string; + media_type: string; + data: string; + }; +} +interface ChatMessageTextContent { + type: string; + text: string; +} +declare const AnnotatedScreenshotText = "This is a screenshot of the current page state with the elements annotated on it. Each element id is annotated with a number to the top left of it. Duplicate annotations at the same location are under each other vertically."; +interface ChatCompletionOptions { + messages: ChatMessage[]; + temperature?: number; + top_p?: number; + frequency_penalty?: number; + presence_penalty?: number; + image?: { + buffer: Buffer; + description?: string; + }; + response_model?: { + name: string; + schema: ZodType; + }; + tools?: LLMTool[]; + tool_choice?: "auto" | "none" | "required"; + maxTokens?: number; + requestId?: string; +} +type LLMResponse = { + id: string; + object: string; + created: number; + model: string; + choices: { + index: number; + message: { + role: string; + content: string | null; + tool_calls: { + id: string; + type: string; + function: { + name: string; + arguments: string; + }; + }[]; + }; + finish_reason: string; + }[]; + usage: { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + }; +}; +interface CreateChatCompletionOptions { + options: ChatCompletionOptions; + logger: (message: LogLine) => void; + retries?: number; +} +declare abstract class LLMClient { + type: "openai" | "anthropic" | "cerebras" | "groq" | (string & {}); + modelName: AvailableModel | (string & {}); + hasVision: boolean; + clientOptions: ClientOptions; + userProvidedInstructions?: string; + constructor(modelName: AvailableModel, userProvidedInstructions?: string); + abstract createChatCompletion(options: CreateChatCompletionOptions): Promise; + generateObject: typeof generateObject; + generateText: typeof generateText; + streamText: typeof streamText; + streamObject: typeof streamObject; + generateImage: typeof experimental_generateImage; + embed: typeof embed; + embedMany: typeof embedMany; + transcribe: typeof experimental_transcribe; + generateSpeech: typeof experimental_generateSpeech; +} + +declare class LLMProvider { + private logger; + private enableCaching; + private cache; + constructor(logger: (message: LogLine) => void, enableCaching: boolean); + cleanRequestCache(requestId: string): void; + getClient(modelName: AvailableModel, clientOptions?: ClientOptions): LLMClient; + static getModelProvider(modelName: AvailableModel): ModelProvider; +} + +interface AgentAction$1 { + type: string; + [key: string]: unknown; +} +interface AgentResult$1 { + success: boolean; + message: string; + actions: AgentAction$1[]; + completed: boolean; + metadata?: Record; + usage?: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; +} +interface AgentOptions$1 { + maxSteps?: number; + autoScreenshot?: boolean; + waitBetweenActions?: number; + context?: string; +} +interface AgentExecuteOptions$1 extends AgentOptions$1 { + instruction: string; +} +type AgentProviderType = "openai" | "anthropic" | "google"; +interface AgentClientOptions { + apiKey: string; + organization?: string; + baseURL?: string; + defaultMaxSteps?: number; + [key: string]: unknown; +} +type AgentType = "openai" | "anthropic" | "google"; +interface AgentExecutionOptions { + options: AgentExecuteOptions$1; + logger: (message: LogLine) => void; + retries?: number; +} +interface AgentHandlerOptions { + modelName: string; + clientOptions?: Record; + userProvidedInstructions?: string; + agentType: AgentType; + experimental?: boolean; +} +interface ActionExecutionResult { + success: boolean; + error?: string; + data?: unknown; +} +interface ToolUseItem extends ResponseItem { + type: "tool_use"; + id: string; + name: string; + input: Record; +} +interface AnthropicMessage { + role: string; + content: string | Array; +} +interface AnthropicContentBlock { + type: string; + [key: string]: unknown; +} +interface AnthropicTextBlock extends AnthropicContentBlock { + type: "text"; + text: string; +} +interface AnthropicToolResult { + type: "tool_result"; + tool_use_id: string; + content: string | Array; +} +interface ResponseItem { + type: string; + id: string; + [key: string]: unknown; +} +interface ComputerCallItem extends ResponseItem { + type: "computer_call"; + call_id: string; + action: { + type: string; + [key: string]: unknown; + }; + pending_safety_checks?: Array<{ + id: string; + code: string; + message: string; + }>; +} +interface FunctionCallItem extends ResponseItem { + type: "function_call"; + call_id: string; + name: string; + arguments: string; +} +type ResponseInputItem = { + role: string; + content: string; +} | { + type: "computer_call_output"; + call_id: string; + output: { + type: "input_image"; + image_url: string; + current_url?: string; + error?: string; + [key: string]: unknown; + } | string; + acknowledged_safety_checks?: Array<{ + id: string; + code: string; + message: string; + }>; +} | { + type: "function_call_output"; + call_id: string; + output: string; +}; +interface AgentInstance { + execute: (instructionOrOptions: string | AgentExecuteOptions$1) => Promise; +} + +interface ConstructorParams { + /** + * The environment to use for Stagehand + */ + env: "LOCAL" | "BROWSERBASE"; + /** + * Your Browserbase API key + */ + apiKey?: string; + /** + * Your Browserbase project ID + */ + projectId?: string; + /** + * The verbosity of the Stagehand logger + * 0 - No logs + * 1 - Only errors + * 2 - All logs + */ + verbose?: 0 | 1 | 2; + /** + * The LLM provider to use for Stagehand + * See + */ + llmProvider?: LLMProvider; + /** + * The logger to use for Stagehand + */ + logger?: (message: LogLine) => void | Promise; + /** + * The timeout to use for the DOM to settle + * @default 10000 + */ + domSettleTimeoutMs?: number; + /** + * The parameters to use for creating a Browserbase session + * See https://docs.browserbase.com/reference/api/create-a-session + */ + browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams; + /** + * Enable caching of LLM responses + * @default true + */ + enableCaching?: boolean; + /** + * The ID of a Browserbase session to resume + */ + browserbaseSessionID?: string; + /** + * The model to use for Stagehand + */ + modelName?: AvailableModel; + /** + * The LLM client to use for Stagehand + */ + llmClient?: LLMClient; + /** + * The parameters to use for the LLM client + * Useful for parameterizing LLM API Keys + */ + modelClientOptions?: ClientOptions; + /** + * Customize the Stagehand system prompt + */ + systemPrompt?: string; + /** + * Offload Stagehand method calls to the Stagehand API. + * Must have a valid API key to use + */ + useAPI?: boolean; + /** + * Wait for captchas to be solved after navigation when using Browserbase environment. + * + * @default false + */ + waitForCaptchaSolves?: boolean; + /** + * The parameters to use for launching a local browser + */ + localBrowserLaunchOptions?: LocalBrowserLaunchOptions; + /** + * Log the inference to a file + */ + logInferenceToFile?: boolean; + selfHeal?: boolean; + /** + * Disable Pino (helpful for Next.js or test environments) + */ + disablePino?: boolean; + /** + * Experimental Flag: Enables the latest experimental features + */ + experimental?: boolean; +} +interface InitResult { + debugUrl: string; + sessionUrl: string; + sessionId: string; +} +interface ActOptions { + action: string; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + variables?: Record; + domSettleTimeoutMs?: number; + timeoutMs?: number; + iframes?: boolean; + frameId?: string; +} +interface ActResult { + success: boolean; + message: string; + action: string; +} +interface ExtractOptions { + instruction?: string; + schema?: T; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + domSettleTimeoutMs?: number; + /** + * @deprecated The `useTextExtract` parameter has no effect in this version of Stagehand and will be removed in later versions. + */ + useTextExtract?: boolean; + selector?: string; + iframes?: boolean; + frameId?: string; +} +type ExtractResult = z.infer; +interface ObserveOptions { + instruction?: string; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + domSettleTimeoutMs?: number; + returnAction?: boolean; + /** + * @deprecated The `onlyVisible` parameter has no effect in this version of Stagehand and will be removed in later versions. + */ + onlyVisible?: boolean; + drawOverlay?: boolean; + iframes?: boolean; + frameId?: string; +} +interface ObserveResult { + selector: string; + description: string; + backendNodeId?: number; + method?: string; + arguments?: string[]; +} +interface LocalBrowserLaunchOptions { + args?: string[]; + chromiumSandbox?: boolean; + devtools?: boolean; + env?: Record; + executablePath?: string; + handleSIGHUP?: boolean; + handleSIGINT?: boolean; + handleSIGTERM?: boolean; + headless?: boolean; + ignoreDefaultArgs?: boolean | Array; + proxy?: { + server: string; + bypass?: string; + username?: string; + password?: string; + }; + tracesDir?: string; + userDataDir?: string; + preserveUserDataDir?: boolean; + acceptDownloads?: boolean; + downloadsPath?: string; + extraHTTPHeaders?: Record; + geolocation?: { + latitude: number; + longitude: number; + accuracy?: number; + }; + hasTouch?: boolean; + ignoreHTTPSErrors?: boolean; + locale?: string; + permissions?: Array; + recordHar?: { + omitContent?: boolean; + content?: "omit" | "embed" | "attach"; + path: string; + mode?: "full" | "minimal"; + urlFilter?: string | RegExp; + }; + recordVideo?: { + dir: string; + size?: { + width: number; + height: number; + }; + }; + viewport?: { + width: number; + height: number; + }; + deviceScaleFactor?: number; + timezoneId?: string; + bypassCSP?: boolean; + cookies?: Cookie[]; + cdpUrl?: string; +} +interface StagehandMetrics { + actPromptTokens: number; + actCompletionTokens: number; + actInferenceTimeMs: number; + extractPromptTokens: number; + extractCompletionTokens: number; + extractInferenceTimeMs: number; + observePromptTokens: number; + observeCompletionTokens: number; + observeInferenceTimeMs: number; + agentPromptTokens: number; + agentCompletionTokens: number; + agentInferenceTimeMs: number; + totalPromptTokens: number; + totalCompletionTokens: number; + totalInferenceTimeMs: number; +} +/** + * Options for executing a task with an agent + */ +interface AgentExecuteParams { + /** + * The instruction to execute with the agent + */ + instruction: string; + /** + * Maximum number of steps the agent can take to complete the task + * @default 10 + */ + maxSteps?: number; + /** + * Take a screenshot automatically before each agent step + * @default true + */ + autoScreenshot?: boolean; + /** + * Wait time in milliseconds between agent actions + * @default 0 + */ + waitBetweenActions?: number; + /** + * Additional context to provide to the agent + */ + context?: string; +} +/** + * Configuration for agent functionality + */ +interface AgentConfig { + /** + * The provider to use for agent functionality + */ + provider?: AgentProviderType; + /** + * The model to use for agent functionality + */ + model?: string; + /** + * Custom instructions to provide to the agent + */ + instructions?: string; + /** + * Additional options to pass to the agent client + */ + options?: Record; +} +declare enum StagehandFunctionName { + ACT = "ACT", + EXTRACT = "EXTRACT", + OBSERVE = "OBSERVE", + AGENT = "AGENT" +} +interface HistoryEntry { + method: "act" | "extract" | "observe" | "navigate"; + parameters: unknown; + result: unknown; + timestamp: string; +} +/** + * Represents a path through a Zod schema from the root object down to a + * particular field. The `segments` array describes the chain of keys/indices. + * + * - **String** segments indicate object property names. + * - **Number** segments indicate array indices. + * + * For example, `["users", 0, "homepage"]` might describe reaching + * the `homepage` field in `schema.users[0].homepage`. + */ +interface ZodPathSegments { + /** + * The ordered list of keys/indices leading from the schema root + * to the targeted field. + */ + segments: Array; +} + +declare const defaultExtractSchema: z.ZodObject<{ + extraction: z.ZodString; +}, "strip", z.ZodTypeAny, { + extraction?: string; +}, { + extraction?: string; +}>; +declare const pageTextSchema: z.ZodObject<{ + page_text: z.ZodString; +}, "strip", z.ZodTypeAny, { + page_text?: string; +}, { + page_text?: string; +}>; +interface Page extends Omit { + act(action: string): Promise; + act(options: ActOptions): Promise; + act(observation: ObserveResult): Promise; + extract(instruction: string): Promise>; + extract(options: ExtractOptions): Promise>; + extract(): Promise>; + observe(): Promise; + observe(instruction: string): Promise; + observe(options?: ObserveOptions): Promise; + on: { + (event: "popup", listener: (page: Page) => unknown): Page; + } & Page$1["on"]; +} +type BrowserContext = BrowserContext$1; +type Browser = Browser$1; + +interface EnhancedContext extends Omit { + newPage(): Promise; + pages(): Page[]; +} +type EncodedId = `${number}-${number}`; + +interface StagehandAPIConstructorParams { + apiKey: string; + projectId: string; + logger: (message: LogLine) => void; +} +interface StartSessionParams { + modelName: string; + modelApiKey: string; + domSettleTimeoutMs: number; + verbose: number; + debugDom: boolean; + systemPrompt?: string; + browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams; + selfHeal?: boolean; + waitForCaptchaSolves?: boolean; + actionTimeoutMs?: number; + browserbaseSessionID?: string; +} +interface StartSessionResult { + sessionId: string; + available?: boolean; +} + +declare class PlaywrightCommandException extends Error { + constructor(message: string); +} +declare class PlaywrightCommandMethodNotSupportedException extends Error { + constructor(message: string); +} +interface GotoOptions { + timeout?: number; + waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"; + referer?: string; + frameId?: string; +} + +interface AgentAction { + type: string; + [key: string]: unknown; +} +interface AgentResult { + success: boolean; + message: string; + actions: AgentAction[]; + completed: boolean; + metadata?: Record; + usage?: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; +} +interface AgentOptions { + maxSteps?: number; + autoScreenshot?: boolean; + waitBetweenActions?: number; + context?: string; +} +interface AgentExecuteOptions extends AgentOptions { + instruction: string; +} + +declare class StagehandAPI { + private apiKey; + private projectId; + private sessionId?; + private modelApiKey; + private logger; + private fetchWithCookies; + constructor({ apiKey, projectId, logger }: StagehandAPIConstructorParams); + init({ modelName, modelApiKey, domSettleTimeoutMs, verbose, debugDom, systemPrompt, selfHeal, waitForCaptchaSolves, actionTimeoutMs, browserbaseSessionCreateParams, browserbaseSessionID, }: StartSessionParams): Promise; + act(options: ActOptions | ObserveResult): Promise; + extract(options: ExtractOptions): Promise>; + observe(options?: ObserveOptions): Promise; + goto(url: string, options?: GotoOptions): Promise; + agentExecute(agentConfig: AgentConfig, executeOptions: AgentExecuteOptions): Promise; + end(): Promise; + private execute; + private request; +} + +declare class StagehandContext { + private readonly stagehand; + private readonly intContext; + private pageMap; + private activeStagehandPage; + private readonly frameIdMap; + private constructor(); + private createStagehandPage; + static init(context: BrowserContext$1, stagehand: Stagehand): Promise; + get frameIdLookup(): ReadonlyMap; + registerFrameId(frameId: string, page: StagehandPage): void; + unregisterFrameId(frameId: string): void; + getStagehandPageByFrameId(frameId: string): StagehandPage | undefined; + get context(): EnhancedContext; + getStagehandPage(page: Page$1): Promise; + getStagehandPages(): Promise; + setActivePage(page: StagehandPage): void; + getActivePage(): StagehandPage | null; + private handleNewPlaywrightPage; + private attachFrameNavigatedListener; +} + +/** ensure we register the custom selector only once per process */ +declare class StagehandPage { + stagehand: Stagehand; + private rawPage; + private intPage; + private intContext; + private actHandler; + private extractHandler; + private observeHandler; + private llmClient; + private cdpClient; + private api; + private userProvidedInstructions?; + private waitForCaptchaSolves; + private initialized; + private isClosed; + private readonly cdpClients; + private fidOrdinals; + private rootFrameId; + get frameId(): string; + updateRootFrameId(newId: string): void; + constructor(page: Page$1, stagehand: Stagehand, context: StagehandContext, llmClient: LLMClient, userProvidedInstructions?: string, api?: StagehandAPI, waitForCaptchaSolves?: boolean); + ordinalForFrameId(fid: string | undefined): number; + encodeWithFrameId(fid: string | undefined, backendId: number): EncodedId; + resetFrameOrdinals(): void; + private ensureStagehandScript; + /** Register the custom selector engine that pierces open/closed shadow roots. */ + /** + * Waits for a captcha to be solved when using Browserbase environment. + * + * @param timeoutMs - Optional timeout in milliseconds. If provided, the promise will reject if the captcha solving hasn't started within the given time. + * @throws StagehandEnvironmentError if called in a LOCAL environment + * @throws CaptchaTimeoutError if the timeout is reached before captcha solving starts + * @returns Promise that resolves when the captcha is solved + */ + waitForCaptchaSolve(timeoutMs?: number): Promise; + init(): Promise; + get page(): Page; + get context(): EnhancedContext; + /** + * `_waitForSettledDom` waits until the DOM is settled, and therefore is + * ready for actions to be taken. + * + * **Definition of "settled"** + * • No in-flight network requests (except WebSocket / Server-Sent-Events). + * • That idle state lasts for at least **500 ms** (the "quiet-window"). + * + * **How it works** + * 1. Subscribes to CDP Network and Page events for the main target and all + * out-of-process iframes (via `Target.setAutoAttach { flatten:true }`). + * 2. Every time `Network.requestWillBeSent` fires, the request ID is added + * to an **`inflight`** `Set`. + * 3. When the request finishes—`loadingFinished`, `loadingFailed`, + * `requestServedFromCache`, or a *data:* response—the request ID is + * removed. + * 4. *Document* requests are also mapped **frameId → requestId**; when + * `Page.frameStoppedLoading` fires the corresponding Document request is + * removed immediately (covers iframes whose network events never close). + * 5. A **stalled-request sweep timer** runs every 500 ms. If a *Document* + * request has been open for ≥ 2 s it is forcibly removed; this prevents + * ad/analytics iframes from blocking the wait forever. + * 6. When `inflight` becomes empty the helper starts a 500 ms timer. + * If no new request appears before the timer fires, the promise + * resolves → **DOM is considered settled**. + * 7. A global guard (`timeoutMs` or `stagehand.domSettleTimeoutMs`, + * default ≈ 30 s) ensures we always resolve; if it fires we log how many + * requests were still outstanding. + * + * @param timeoutMs – Optional hard cap (ms). Defaults to + * `this.stagehand.domSettleTimeoutMs`. + */ + _waitForSettledDom(timeoutMs?: number): Promise; + act(actionOrOptions: string | ActOptions | ObserveResult): Promise; + extract(instructionOrOptions?: string | ExtractOptions): Promise>; + observe(instructionOrOptions?: string | ObserveOptions): Promise; + /** + * Get or create a CDP session for the given target. + * @param target The Page or (OOPIF) Frame you want to talk to. + */ + getCDPClient(target?: Page$1 | Frame): Promise; + /** + * Send a CDP command to the chosen DevTools target. + * + * @param method Any valid CDP method, e.g. `"DOM.getDocument"`. + * @param params Command parameters (optional). + * @param target A `Page` or OOPIF `Frame`. Defaults to the main page. + * + * @typeParam T Expected result shape (defaults to `unknown`). + */ + sendCDP(method: string, params?: Record, target?: Page$1 | Frame): Promise; + /** Enable a CDP domain (e.g. `"Network"` or `"DOM"`) on the chosen target. */ + enableCDP(domain: string, target?: Page$1 | Frame): Promise; + /** Disable a CDP domain on the chosen target. */ + disableCDP(domain: string, target?: Page$1 | Frame): Promise; +} + +interface BrowserResult { + env: "LOCAL" | "BROWSERBASE"; + browser?: Browser; + context: BrowserContext; + debugUrl?: string; + sessionUrl?: string; + contextPath?: string; + sessionId?: string; +} + +declare const operatorResponseSchema: z.ZodObject<{ + reasoning: z.ZodString; + method: z.ZodEnum<["act", "extract", "goto", "close", "wait", "navback", "refresh"]>; + parameters: z.ZodNullable; + taskComplete: z.ZodBoolean; +}, "strip", z.ZodTypeAny, { + method?: "close" | "goto" | "act" | "extract" | "wait" | "navback" | "refresh"; + reasoning?: string; + parameters?: string; + taskComplete?: boolean; +}, { + method?: "close" | "goto" | "act" | "extract" | "wait" | "navback" | "refresh"; + reasoning?: string; + parameters?: string; + taskComplete?: boolean; +}>; +type OperatorResponse = z.infer; +declare const operatorSummarySchema: z.ZodObject<{ + answer: z.ZodString; +}, "strip", z.ZodTypeAny, { + answer?: string; +}, { + answer?: string; +}>; +type OperatorSummary = z.infer; + +declare class StagehandError extends Error { + constructor(message: string); +} +declare class StagehandDefaultError extends StagehandError { + constructor(error?: unknown); +} +declare class StagehandEnvironmentError extends StagehandError { + constructor(currentEnvironment: string, requiredEnvironment: string, feature: string); +} +declare class MissingEnvironmentVariableError extends StagehandError { + constructor(missingEnvironmentVariable: string, feature: string); +} +declare class UnsupportedModelError extends StagehandError { + constructor(supportedModels: string[], feature?: string); +} +declare class UnsupportedModelProviderError extends StagehandError { + constructor(supportedProviders: string[], feature?: string); +} +declare class UnsupportedAISDKModelProviderError extends StagehandError { + constructor(provider: string, supportedProviders: string[]); +} +declare class InvalidAISDKModelFormatError extends StagehandError { + constructor(modelName: string); +} +declare class StagehandNotInitializedError extends StagehandError { + constructor(prop: string); +} +declare class BrowserbaseSessionNotFoundError extends StagehandError { + constructor(); +} +declare class CaptchaTimeoutError extends StagehandError { + constructor(); +} +declare class MissingLLMConfigurationError extends StagehandError { + constructor(); +} +declare class HandlerNotInitializedError extends StagehandError { + constructor(handlerType: string); +} +declare class StagehandInvalidArgumentError extends StagehandError { + constructor(message: string); +} +declare class StagehandElementNotFoundError extends StagehandError { + constructor(xpaths: string[]); +} +declare class AgentScreenshotProviderError extends StagehandError { + constructor(message: string); +} +declare class StagehandMissingArgumentError extends StagehandError { + constructor(message: string); +} +declare class CreateChatCompletionResponseError extends StagehandError { + constructor(message: string); +} +declare class StagehandEvalError extends StagehandError { + constructor(message: string); +} +declare class StagehandDomProcessError extends StagehandError { + constructor(message: string); +} +declare class StagehandClickError extends StagehandError { + constructor(message: string, selector: string); +} +declare class LLMResponseError extends StagehandError { + constructor(primitive: string, message: string); +} +declare class StagehandIframeError extends StagehandError { + constructor(frameUrl: string, message: string); +} +declare class ContentFrameNotFoundError extends StagehandError { + constructor(selector: string); +} +declare class XPathResolutionError extends StagehandError { + constructor(xpath: string); +} +declare class ExperimentalApiConflictError extends StagehandError { + constructor(); +} +declare class ExperimentalNotConfiguredError extends StagehandError { + constructor(featureName: string); +} +declare class ZodSchemaValidationError extends Error { + readonly received: unknown; + readonly issues: ReturnType; + constructor(received: unknown, issues: ReturnType); +} +declare class StagehandInitError extends StagehandError { + constructor(message: string); +} +declare class StagehandShadowRootMissingError extends StagehandError { + constructor(detail?: string); +} +declare class StagehandShadowSegmentEmptyError extends StagehandError { + constructor(); +} +declare class StagehandShadowSegmentNotFoundError extends StagehandError { + constructor(segment: string, hint?: string); +} + +declare class StagehandAPIError extends Error { + constructor(message: string); +} +declare class StagehandAPIUnauthorizedError extends StagehandAPIError { + constructor(message?: string); +} +declare class StagehandHttpError extends StagehandAPIError { + constructor(message: string); +} +declare class StagehandServerError extends StagehandAPIError { + constructor(message: string); +} +declare class StagehandResponseBodyError extends StagehandAPIError { + constructor(); +} +declare class StagehandResponseParseError extends StagehandAPIError { + constructor(message: string); +} + +declare class Stagehand { + private stagehandPage; + private stagehandContext; + browserbaseSessionID?: string; + readonly domSettleTimeoutMs: number; + readonly debugDom: boolean; + readonly headless: boolean; + verbose: 0 | 1 | 2; + llmProvider: LLMProvider; + enableCaching: boolean; + protected apiKey: string | undefined; + private projectId; + private externalLogger?; + private browserbaseSessionCreateParams?; + variables: { + [key: string]: unknown; + }; + private contextPath?; + llmClient: LLMClient; + readonly userProvidedInstructions?: string; + private usingAPI; + private modelName; + apiClient: StagehandAPI | undefined; + readonly waitForCaptchaSolves: boolean; + private localBrowserLaunchOptions?; + readonly selfHeal: boolean; + private cleanupCalled; + readonly actTimeoutMs: number; + readonly logInferenceToFile?: boolean; + private stagehandLogger; + private disablePino; + private modelClientOptions; + private _env; + private _browser; + private _isClosed; + private _history; + readonly experimental: boolean; + private _livePageProxy?; + private createLivePageProxy; + get history(): ReadonlyArray; + protected setActivePage(page: StagehandPage): void; + get page(): Page; + stagehandMetrics: StagehandMetrics; + get metrics(): StagehandMetrics; + get isClosed(): boolean; + updateMetrics(functionName: StagehandFunctionName, promptTokens: number, completionTokens: number, inferenceTimeMs: number): void; + private updateTotalMetrics; + constructor({ env, apiKey, projectId, verbose, llmProvider, llmClient, logger, browserbaseSessionCreateParams, domSettleTimeoutMs, enableCaching, browserbaseSessionID, modelName, modelClientOptions, systemPrompt, useAPI, localBrowserLaunchOptions, waitForCaptchaSolves, logInferenceToFile, selfHeal, disablePino, experimental, }?: ConstructorParams); + private registerSignalHandlers; + get logger(): (logLine: LogLine) => void; + get env(): "LOCAL" | "BROWSERBASE"; + get downloadsPath(): string; + get context(): EnhancedContext; + init(): Promise; + log(logObj: LogLine): void; + close(): Promise; + addToHistory(method: HistoryEntry["method"], parameters: ActOptions | ExtractOptions | ObserveOptions | { + url: string; + options: GotoOptions; + } | string, result?: unknown): void; + /** + * Create an agent instance that can be executed with different instructions + * @returns An agent instance with execute() and setViewport() methods + */ + agent(options?: AgentConfig): { + execute: (instructionOrOptions: string | AgentExecuteOptions$1) => Promise; + setScreenshotCollector?: (collector: unknown) => void; + }; +} + +export { type ActOptions, type ActResult, type ActionExecutionResult, type AgentAction$1 as AgentAction, type AgentClientOptions, type AgentConfig, type AgentExecuteOptions$1 as AgentExecuteOptions, type AgentExecuteParams, type AgentExecutionOptions, type AgentHandlerOptions, type AgentInstance, type AgentOptions$1 as AgentOptions, type AgentProviderType, type AgentResult$1 as AgentResult, AgentScreenshotProviderError, type AgentType, AnnotatedScreenshotText, type AnthropicContentBlock, type AnthropicJsonSchemaObject, type AnthropicMessage, type AnthropicTextBlock, type AnthropicToolResult, type AvailableModel, AvailableModelSchema, type Browser, type BrowserContext, type BrowserResult, BrowserbaseSessionNotFoundError, CaptchaTimeoutError, type ChatCompletionOptions, type ChatMessage, type ChatMessageContent, type ChatMessageImageContent, type ChatMessageTextContent, type ClientOptions, type ComputerCallItem, type ConstructorParams, ContentFrameNotFoundError, type CreateChatCompletionOptions, CreateChatCompletionResponseError, ExperimentalApiConflictError, ExperimentalNotConfiguredError, type ExtractOptions, type ExtractResult, type FunctionCallItem, type GotoOptions, HandlerNotInitializedError, type HistoryEntry, type InitResult, InvalidAISDKModelFormatError, LLMClient, type LLMResponse, LLMResponseError, LOG_LEVEL_NAMES, type LocalBrowserLaunchOptions, type LogLevel, type LogLine, type Logger, MissingEnvironmentVariableError, MissingLLMConfigurationError, type ModelProvider, type ObserveOptions, type ObserveResult, type OperatorResponse, type OperatorSummary, type Page, PlaywrightCommandException, PlaywrightCommandMethodNotSupportedException, type ResponseInputItem, type ResponseItem, Stagehand, StagehandAPIError, StagehandAPIUnauthorizedError, StagehandClickError, StagehandDefaultError, StagehandDomProcessError, StagehandElementNotFoundError, StagehandEnvironmentError, StagehandError, StagehandEvalError, StagehandFunctionName, StagehandHttpError, StagehandIframeError, StagehandInitError, StagehandInvalidArgumentError, type StagehandMetrics, StagehandMissingArgumentError, StagehandNotInitializedError, StagehandResponseBodyError, StagehandResponseParseError, StagehandServerError, StagehandShadowRootMissingError, StagehandShadowSegmentEmptyError, StagehandShadowSegmentNotFoundError, type ToolUseItem, UnsupportedAISDKModelProviderError, UnsupportedModelError, UnsupportedModelProviderError, XPathResolutionError, type ZodPathSegments, ZodSchemaValidationError, defaultExtractSchema, operatorResponseSchema, operatorSummarySchema, pageTextSchema }; diff --git a/sdk/stagehand-ts/dist/index.js b/sdk/stagehand-ts/dist/index.js new file mode 100644 index 0000000..c10d319 --- /dev/null +++ b/sdk/stagehand-ts/dist/index.js @@ -0,0 +1,23860 @@ +var __create = Object.create; +var __defProp = Object.defineProperty; +var __defProps = Object.defineProperties; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropDescs = Object.getOwnPropertyDescriptors; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getOwnPropSymbols = Object.getOwnPropertySymbols; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __propIsEnum = Object.prototype.propertyIsEnumerable; +var __reflectGet = Reflect.get; +var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __spreadValues = (a, b) => { + for (var prop in b || (b = {})) + if (__hasOwnProp.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + if (__getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(b)) { + if (__propIsEnum.call(b, prop)) + __defNormalProp(a, prop, b[prop]); + } + return a; +}; +var __spreadProps = (a, b) => __defProps(a, __getOwnPropDescs(b)); +var __objRest = (source, exclude) => { + var target = {}; + for (var prop in source) + if (__hasOwnProp.call(source, prop) && exclude.indexOf(prop) < 0) + target[prop] = source[prop]; + if (source != null && __getOwnPropSymbols) + for (var prop of __getOwnPropSymbols(source)) { + if (exclude.indexOf(prop) < 0 && __propIsEnum.call(source, prop)) + target[prop] = source[prop]; + } + return target; +}; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name14 in all) + __defProp(target, name14, { get: all[name14], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); +var __superGet = (cls, obj, key) => __reflectGet(__getProtoOf(cls), key, obj); +var __async = (__this, __arguments, generator) => { + return new Promise((resolve2, reject) => { + var fulfilled = (value) => { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + }; + var rejected = (value) => { + try { + step(generator.throw(value)); + } catch (e) { + reject(e); + } + }; + var step = (x) => x.done ? resolve2(x.value) : Promise.resolve(x.value).then(fulfilled, rejected); + step((generator = generator.apply(__this, __arguments)).next()); + }); +}; + +// node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js +var require_secure_json_parse = __commonJS({ + "node_modules/.pnpm/secure-json-parse@2.7.0/node_modules/secure-json-parse/index.js"(exports2, module2) { + "use strict"; + var hasBuffer = typeof Buffer !== "undefined"; + var suspectProtoRx = /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/; + var suspectConstructorRx = /"(?:c|\\u0063)(?:o|\\u006[Ff])(?:n|\\u006[Ee])(?:s|\\u0073)(?:t|\\u0074)(?:r|\\u0072)(?:u|\\u0075)(?:c|\\u0063)(?:t|\\u0074)(?:o|\\u006[Ff])(?:r|\\u0072)"\s*:/; + function _parse(text, reviver, options) { + if (options == null) { + if (reviver !== null && typeof reviver === "object") { + options = reviver; + reviver = void 0; + } + } + if (hasBuffer && Buffer.isBuffer(text)) { + text = text.toString(); + } + if (text && text.charCodeAt(0) === 65279) { + text = text.slice(1); + } + const obj = JSON.parse(text, reviver); + if (obj === null || typeof obj !== "object") { + return obj; + } + const protoAction = options && options.protoAction || "error"; + const constructorAction = options && options.constructorAction || "error"; + if (protoAction === "ignore" && constructorAction === "ignore") { + return obj; + } + if (protoAction !== "ignore" && constructorAction !== "ignore") { + if (suspectProtoRx.test(text) === false && suspectConstructorRx.test(text) === false) { + return obj; + } + } else if (protoAction !== "ignore" && constructorAction === "ignore") { + if (suspectProtoRx.test(text) === false) { + return obj; + } + } else { + if (suspectConstructorRx.test(text) === false) { + return obj; + } + } + return filter(obj, { protoAction, constructorAction, safe: options && options.safe }); + } + function filter(obj, { protoAction = "error", constructorAction = "error", safe } = {}) { + let next = [obj]; + while (next.length) { + const nodes = next; + next = []; + for (const node of nodes) { + if (protoAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "__proto__")) { + if (safe === true) { + return null; + } else if (protoAction === "error") { + throw new SyntaxError("Object contains forbidden prototype property"); + } + delete node.__proto__; + } + if (constructorAction !== "ignore" && Object.prototype.hasOwnProperty.call(node, "constructor") && Object.prototype.hasOwnProperty.call(node.constructor, "prototype")) { + if (safe === true) { + return null; + } else if (constructorAction === "error") { + throw new SyntaxError("Object contains forbidden prototype property"); + } + delete node.constructor; + } + for (const key in node) { + const value = node[key]; + if (value && typeof value === "object") { + next.push(value); + } + } + } + } + return obj; + } + function parse2(text, reviver, options) { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + try { + return _parse(text, reviver, options); + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + } + function safeParse(text, reviver) { + const stackTraceLimit = Error.stackTraceLimit; + Error.stackTraceLimit = 0; + try { + return _parse(text, reviver, { safe: true }); + } catch (_e) { + return null; + } finally { + Error.stackTraceLimit = stackTraceLimit; + } + } + module2.exports = parse2; + module2.exports.default = parse2; + module2.exports.parse = parse2; + module2.exports.safeParse = safeParse; + module2.exports.scan = filter; + } +}); + +// node_modules/.pnpm/partial-json@0.1.7/node_modules/partial-json/dist/options.js +var require_options = __commonJS({ + "node_modules/.pnpm/partial-json@0.1.7/node_modules/partial-json/dist/options.js"(exports2) { + "use strict"; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Allow = exports2.ALL = exports2.COLLECTION = exports2.ATOM = exports2.SPECIAL = exports2.INF = exports2._INFINITY = exports2.INFINITY = exports2.NAN = exports2.BOOL = exports2.NULL = exports2.OBJ = exports2.ARR = exports2.NUM = exports2.STR = void 0; + exports2.STR = 1; + exports2.NUM = 2; + exports2.ARR = 4; + exports2.OBJ = 8; + exports2.NULL = 16; + exports2.BOOL = 32; + exports2.NAN = 64; + exports2.INFINITY = 128; + exports2._INFINITY = 256; + exports2.INF = exports2.INFINITY | exports2._INFINITY; + exports2.SPECIAL = exports2.NULL | exports2.BOOL | exports2.INF | exports2.NAN; + exports2.ATOM = exports2.STR | exports2.NUM | exports2.SPECIAL; + exports2.COLLECTION = exports2.ARR | exports2.OBJ; + exports2.ALL = exports2.ATOM | exports2.COLLECTION; + exports2.Allow = { STR: exports2.STR, NUM: exports2.NUM, ARR: exports2.ARR, OBJ: exports2.OBJ, NULL: exports2.NULL, BOOL: exports2.BOOL, NAN: exports2.NAN, INFINITY: exports2.INFINITY, _INFINITY: exports2._INFINITY, INF: exports2.INF, SPECIAL: exports2.SPECIAL, ATOM: exports2.ATOM, COLLECTION: exports2.COLLECTION, ALL: exports2.ALL }; + exports2.default = exports2.Allow; + } +}); + +// node_modules/.pnpm/partial-json@0.1.7/node_modules/partial-json/dist/index.js +var require_dist = __commonJS({ + "node_modules/.pnpm/partial-json@0.1.7/node_modules/partial-json/dist/index.js"(exports2) { + "use strict"; + var __createBinding = exports2 && exports2.__createBinding || (Object.create ? function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { + return m[k]; + } }; + } + Object.defineProperty(o, k2, desc); + } : function(o, m, k, k2) { + if (k2 === void 0) k2 = k; + o[k2] = m[k]; + }); + var __exportStar = exports2 && exports2.__exportStar || function(m, exports3) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports3, p)) __createBinding(exports3, m, p); + }; + Object.defineProperty(exports2, "__esModule", { value: true }); + exports2.Allow = exports2.MalformedJSON = exports2.PartialJSON = exports2.parseJSON = exports2.parse = void 0; + var options_1 = require_options(); + Object.defineProperty(exports2, "Allow", { enumerable: true, get: function() { + return options_1.Allow; + } }); + __exportStar(require_options(), exports2); + var PartialJSON = class extends Error { + }; + exports2.PartialJSON = PartialJSON; + var MalformedJSON = class extends Error { + }; + exports2.MalformedJSON = MalformedJSON; + function parseJSON2(jsonString, allowPartial = options_1.Allow.ALL) { + if (typeof jsonString !== "string") { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); + } + exports2.parseJSON = parseJSON2; + var _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON("Unexpected end of input"); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === "{") + return parseObj(); + if (jsonString[index] === "[") + return parseArr(); + if (jsonString.substring(index, index + 4) === "null" || options_1.Allow.NULL & allow && length - index < 4 && "null".startsWith(jsonString.substring(index))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === "true" || options_1.Allow.BOOL & allow && length - index < 4 && "true".startsWith(jsonString.substring(index))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === "false" || options_1.Allow.BOOL & allow && length - index < 5 && "false".startsWith(jsonString.substring(index))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === "Infinity" || options_1.Allow.INFINITY & allow && length - index < 8 && "Infinity".startsWith(jsonString.substring(index))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === "-Infinity" || options_1.Allow._INFINITY & allow && 1 < length - index && length - index < 9 && "-Infinity".startsWith(jsonString.substring(index))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === "NaN" || options_1.Allow.NAN & allow && length - index < 3 && "NaN".startsWith(jsonString.substring(index))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; + while (index < length && (jsonString[index] !== '"' || escape && jsonString[index - 1] === "\\")) { + escape = jsonString[index] === "\\" ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } catch (e) { + throwMalformedError(String(e)); + } + } else if (options_1.Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } catch (e) { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("\\")) + '"'); + } + } + markPartialJSON("Unterminated string literal"); + }; + const parseObj = () => { + index++; + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== "}") { + skipBlank(); + if (index >= length && options_1.Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; + try { + const value = parseAny(); + obj[key] = value; + } catch (e) { + if (options_1.Allow.OBJ & allow) + return obj; + else + throw e; + } + skipBlank(); + if (jsonString[index] === ",") + index++; + } + } catch (e) { + if (options_1.Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; + return obj; + }; + const parseArr = () => { + index++; + const arr = []; + try { + while (jsonString[index] !== "]") { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ",") { + index++; + } + } + } catch (e) { + if (options_1.Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === "-") + throwMalformedError("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } catch (e) { + if (options_1.Allow.NUM & allow) + try { + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf("e"))); + } catch (e2) { + } + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === "-") + index++; + while (jsonString[index] && ",]}".indexOf(jsonString[index]) === -1) + index++; + if (index == length && !(options_1.Allow.NUM & allow)) + markPartialJSON("Unterminated number literal"); + try { + return JSON.parse(jsonString.substring(start, index)); + } catch (e) { + if (jsonString.substring(start, index) === "-") + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf("e"))); + } catch (e2) { + throwMalformedError(String(e2)); + } + } + }; + const skipBlank = () => { + while (index < length && " \n\r ".includes(jsonString[index])) { + index++; + } + }; + return parseAny(); + }; + var parse2 = parseJSON2; + exports2.parse = parse2; + } +}); + +// lib/index.ts +var index_exports = {}; +__export(index_exports, { + AgentScreenshotProviderError: () => AgentScreenshotProviderError, + AnnotatedScreenshotText: () => AnnotatedScreenshotText, + AvailableModelSchema: () => AvailableModelSchema, + BrowserbaseSessionNotFoundError: () => BrowserbaseSessionNotFoundError, + CaptchaTimeoutError: () => CaptchaTimeoutError, + ContentFrameNotFoundError: () => ContentFrameNotFoundError, + CreateChatCompletionResponseError: () => CreateChatCompletionResponseError, + ExperimentalApiConflictError: () => ExperimentalApiConflictError, + ExperimentalNotConfiguredError: () => ExperimentalNotConfiguredError, + HandlerNotInitializedError: () => HandlerNotInitializedError, + InvalidAISDKModelFormatError: () => InvalidAISDKModelFormatError, + LLMClient: () => LLMClient, + LLMResponseError: () => LLMResponseError, + LOG_LEVEL_NAMES: () => LOG_LEVEL_NAMES, + MissingEnvironmentVariableError: () => MissingEnvironmentVariableError, + MissingLLMConfigurationError: () => MissingLLMConfigurationError, + PlaywrightCommandException: () => PlaywrightCommandException, + PlaywrightCommandMethodNotSupportedException: () => PlaywrightCommandMethodNotSupportedException, + Stagehand: () => Stagehand3, + StagehandAPIError: () => StagehandAPIError, + StagehandAPIUnauthorizedError: () => StagehandAPIUnauthorizedError, + StagehandClickError: () => StagehandClickError, + StagehandDefaultError: () => StagehandDefaultError, + StagehandDomProcessError: () => StagehandDomProcessError, + StagehandElementNotFoundError: () => StagehandElementNotFoundError, + StagehandEnvironmentError: () => StagehandEnvironmentError, + StagehandError: () => StagehandError, + StagehandEvalError: () => StagehandEvalError, + StagehandFunctionName: () => StagehandFunctionName, + StagehandHttpError: () => StagehandHttpError, + StagehandIframeError: () => StagehandIframeError, + StagehandInitError: () => StagehandInitError, + StagehandInvalidArgumentError: () => StagehandInvalidArgumentError, + StagehandMissingArgumentError: () => StagehandMissingArgumentError, + StagehandNotInitializedError: () => StagehandNotInitializedError, + StagehandResponseBodyError: () => StagehandResponseBodyError, + StagehandResponseParseError: () => StagehandResponseParseError, + StagehandServerError: () => StagehandServerError, + StagehandShadowRootMissingError: () => StagehandShadowRootMissingError, + StagehandShadowSegmentEmptyError: () => StagehandShadowSegmentEmptyError, + StagehandShadowSegmentNotFoundError: () => StagehandShadowSegmentNotFoundError, + UnsupportedAISDKModelProviderError: () => UnsupportedAISDKModelProviderError, + UnsupportedModelError: () => UnsupportedModelError, + UnsupportedModelProviderError: () => UnsupportedModelProviderError, + XPathResolutionError: () => XPathResolutionError, + ZodSchemaValidationError: () => ZodSchemaValidationError, + defaultExtractSchema: () => defaultExtractSchema, + operatorResponseSchema: () => operatorResponseSchema, + operatorSummarySchema: () => operatorSummarySchema, + pageTextSchema: () => pageTextSchema +}); +module.exports = __toCommonJS(index_exports); +var import_sdk3 = require("@browserbasehq/sdk"); +var import_playwright3 = require("playwright"); +var import_dotenv = __toESM(require("dotenv")); +var import_fs2 = __toESM(require("fs")); +var import_os = __toESM(require("os")); +var import_path2 = __toESM(require("path")); + +// types/stagehand.ts +var StagehandFunctionName = /* @__PURE__ */ ((StagehandFunctionName2) => { + StagehandFunctionName2["ACT"] = "ACT"; + StagehandFunctionName2["EXTRACT"] = "EXTRACT"; + StagehandFunctionName2["OBSERVE"] = "OBSERVE"; + StagehandFunctionName2["AGENT"] = "AGENT"; + return StagehandFunctionName2; +})(StagehandFunctionName || {}); + +// types/page.ts +var import_v3 = require("zod/v3"); +var defaultExtractSchema = import_v3.z.object({ + extraction: import_v3.z.string() +}); +var pageTextSchema = import_v3.z.object({ + page_text: import_v3.z.string() +}); + +// types/playwright.ts +var PlaywrightCommandException = class extends Error { + constructor(message) { + super(message); + this.name = "PlaywrightCommandException"; + } +}; +var PlaywrightCommandMethodNotSupportedException = class extends Error { + constructor(message) { + super(message); + this.name = "PlaywrightCommandMethodNotSupportedException"; + } +}; + +// types/act.ts +var SupportedPlaywrightAction = /* @__PURE__ */ ((SupportedPlaywrightAction2) => { + SupportedPlaywrightAction2["CLICK"] = "click"; + SupportedPlaywrightAction2["FILL"] = "fill"; + SupportedPlaywrightAction2["TYPE"] = "type"; + SupportedPlaywrightAction2["PRESS"] = "press"; + SupportedPlaywrightAction2["SCROLL"] = "scrollTo"; + SupportedPlaywrightAction2["NEXT_CHUNK"] = "nextChunk"; + SupportedPlaywrightAction2["PREV_CHUNK"] = "prevChunk"; + SupportedPlaywrightAction2["SELECT_OPTION_FROM_DROPDOWN"] = "selectOptionFromDropdown"; + return SupportedPlaywrightAction2; +})(SupportedPlaywrightAction || {}); + +// lib/prompt.ts +function buildUserInstructionsString(userProvidedInstructions) { + if (!userProvidedInstructions) { + return ""; + } + return ` + +# Custom Instructions Provided by the User + +Please keep the user's instructions in mind when performing actions. If the user's instructions are not relevant to the current task, ignore them. + +User Instructions: +${userProvidedInstructions}`; +} +function buildExtractSystemPrompt(isUsingPrintExtractedDataTool = false, userProvidedInstructions) { + const baseContent = `You are extracting content on behalf of a user. + If a user asks you to extract a 'list' of information, or 'all' information, + YOU MUST EXTRACT ALL OF THE INFORMATION THAT THE USER REQUESTS. + + You will be given: +1. An instruction +2. `; + const contentDetail = `A list of DOM elements to extract from.`; + const instructions = ` +Print the exact text from the DOM elements with all symbols, characters, and endlines as is. +Print null or an empty string if no new information is found. + `.trim(); + const toolInstructions = isUsingPrintExtractedDataTool ? ` +ONLY print the content using the print_extracted_data tool provided. +ONLY print the content using the print_extracted_data tool provided. + `.trim() : ""; + const additionalInstructions = "If a user is attempting to extract links or URLs, you MUST respond with ONLY the IDs of the link elements. \nDo not attempt to extract links directly from the text unless absolutely necessary. "; + const userInstructions = buildUserInstructionsString( + userProvidedInstructions + ); + const content = `${baseContent}${contentDetail} + +${instructions} +${toolInstructions}${additionalInstructions ? ` + +${additionalInstructions}` : ""}${userInstructions ? ` + +${userInstructions}` : ""}`.replace(/\s+/g, " "); + return { + role: "system", + content + }; +} +function buildExtractUserPrompt(instruction, domElements, isUsingPrintExtractedDataTool = false) { + let content = `Instruction: ${instruction} +DOM: ${domElements}`; + if (isUsingPrintExtractedDataTool) { + content += ` +ONLY print the content using the print_extracted_data tool provided. +ONLY print the content using the print_extracted_data tool provided.`; + } + return { + role: "user", + content + }; +} +var metadataSystemPrompt = `You are an AI assistant tasked with evaluating the progress and completion status of an extraction task. +Analyze the extraction response and determine if the task is completed or if more information is needed. +Strictly abide by the following criteria: +1. Once the instruction has been satisfied by the current extraction response, ALWAYS set completion status to true and stop processing, regardless of remaining chunks. +2. Only set completion status to false if BOTH of these conditions are true: + - The instruction has not been satisfied yet + - There are still chunks left to process (chunksTotal > chunksSeen)`; +function buildMetadataSystemPrompt() { + return { + role: "system", + content: metadataSystemPrompt + }; +} +function buildMetadataPrompt(instruction, extractionResponse, chunksSeen, chunksTotal) { + return { + role: "user", + content: `Instruction: ${instruction} +Extracted content: ${JSON.stringify(extractionResponse, null, 2)} +chunksSeen: ${chunksSeen} +chunksTotal: ${chunksTotal}` + }; +} +function buildObserveSystemPrompt(userProvidedInstructions) { + const observeSystemPrompt = ` +You are helping the user automate the browser by finding elements based on what the user wants to observe in the page. + +You will be given: +1. a instruction of elements to observe +2. a hierarchical accessibility tree showing the semantic structure of the page. The tree is a hybrid of the DOM and the accessibility tree. + +Return an array of elements that match the instruction if they exist, otherwise return an empty array.`; + const content = observeSystemPrompt.replace(/\s+/g, " "); + return { + role: "system", + content: [content, buildUserInstructionsString(userProvidedInstructions)].filter(Boolean).join("\n\n") + }; +} +function buildObserveUserMessage(instruction, domElements) { + return { + role: "user", + content: `instruction: ${instruction} +Accessibility Tree: +${domElements}` + }; +} +function buildActObservePrompt(action, supportedActions, variables) { + let instruction = `Find the most relevant element to perform an action on given the following action: ${action}. + Provide an action for this element such as ${supportedActions.join(", ")}, or any other playwright locator method. Remember that to users, buttons and links look the same in most cases. + If the action is completely unrelated to a potential action to be taken on the page, return an empty array. + ONLY return one action. If multiple actions are relevant, return the most relevant one. + If the user is asking to scroll to a position on the page, e.g., 'halfway' or 0.75, etc, you must return the argument formatted as the correct percentage, e.g., '50%' or '75%', etc. + If the user is asking to scroll to the next chunk/previous chunk, choose the nextChunk/prevChunk method. No arguments are required here. + If the action implies a key press, e.g., 'press enter', 'press a', 'press space', etc., always choose the press method with the appropriate key as argument \u2014 e.g. 'a', 'Enter', 'Space'. Do not choose a click action on an on-screen keyboard. Capitalize the first character like 'Enter', 'Tab', 'Escape' only for special keys. + If the action implies choosing an option from a dropdown, AND the corresponding element is a 'select' element, choose the selectOptionFromDropdown method. The argument should be the text of the option to select. + If the action implies choosing an option from a dropdown, and the corresponding element is NOT a 'select' element, choose the click method.`; + if (variables && Object.keys(variables).length > 0) { + const variableNames = Object.keys(variables).map((key) => `%${key}%`).join(", "); + const variablesPrompt = `The following variables are available to use in the action: ${variableNames}. Fill the argument variables with the variable name.`; + instruction += ` ${variablesPrompt}`; + } + return instruction; +} +function buildOperatorSystemPrompt(goal) { + return { + role: "system", + content: `You are a general-purpose agent whose job is to accomplish the user's goal across multiple model calls by running actions on the page. + +You will be given a goal and a list of steps that have been taken so far. Your job is to determine if either the user's goal has been completed or if there are still steps that need to be taken. + +# Your current goal +${goal} + +# Important guidelines +1. Break down complex actions into individual atomic steps +2. For \`act\` commands, use only one action at a time, such as: + - Single click on a specific element + - Type into a single input field + - Select a single option +3. Avoid combining multiple actions in one instruction +4. If multiple actions are needed, they should be separate steps` + }; +} +function buildGoogleCUASystemPrompt() { + return { + role: "system", + content: `You are a general-purpose browser agent whose job is to accomplish the user's goal. +Today's date is ${(/* @__PURE__ */ new Date()).toLocaleDateString()}. +You have access to a search tool; however, in most cases you should operate within the page/url the user has provided. ONLY use the search tool if you're stuck or the task is impossible to complete within the current page. +You will be given a goal and a list of steps that have been taken so far. Avoid requesting the user for input as much as possible. Good luck! +` + }; +} + +// lib/version.ts +var STAGEHAND_VERSION = "2.4.2"; + +// types/stagehandErrors.ts +var StagehandError = class extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + } +}; +var StagehandDefaultError = class extends StagehandError { + constructor(error) { + if (error instanceof Error || error instanceof StagehandError) { + super( + ` +Hey! We're sorry you ran into an error. +Stagehand version: ${STAGEHAND_VERSION} +If you need help, please open a Github issue or reach out to us on Slack: https://stagehand.dev/slack + +Full error: +${error.message}` + ); + } + } +}; +var StagehandEnvironmentError = class extends StagehandError { + constructor(currentEnvironment, requiredEnvironment, feature) { + super( + `You seem to be setting the current environment to ${currentEnvironment}.Ensure the environment is set to ${requiredEnvironment} if you want to use ${feature}.` + ); + } +}; +var MissingEnvironmentVariableError = class extends StagehandError { + constructor(missingEnvironmentVariable, feature) { + super( + `${missingEnvironmentVariable} is required to use ${feature}.Please set ${missingEnvironmentVariable} in your environment.` + ); + } +}; +var UnsupportedModelError = class extends StagehandError { + constructor(supportedModels, feature) { + super( + feature ? `${feature} requires one of the following models: ${supportedModels}` : `please use one of the supported models: ${supportedModels}` + ); + } +}; +var UnsupportedModelProviderError = class extends StagehandError { + constructor(supportedProviders, feature) { + super( + feature ? `${feature} requires one of the following model providers: ${supportedProviders}` : `please use one of the supported model providers: ${supportedProviders}` + ); + } +}; +var UnsupportedAISDKModelProviderError = class extends StagehandError { + constructor(provider, supportedProviders) { + super( + `${provider} is not currently supported for aiSDK. please use one of the supported model providers: ${supportedProviders}` + ); + } +}; +var InvalidAISDKModelFormatError = class extends StagehandError { + constructor(modelName) { + super( + `${modelName} does not follow correct format for specifying aiSDK models. Please define your modelName as 'provider/model-name'. For example: \`modelName: 'openai/gpt-4o-mini'\`` + ); + } +}; +var StagehandNotInitializedError = class extends StagehandError { + constructor(prop) { + super( + `You seem to be calling \`${prop}\` on a page in an uninitialized \`Stagehand\` object. Ensure you are running \`await stagehand.init()\` on the Stagehand object before referencing the \`page\` object.` + ); + } +}; +var BrowserbaseSessionNotFoundError = class extends StagehandError { + constructor() { + super("No Browserbase session ID found"); + } +}; +var CaptchaTimeoutError = class extends StagehandError { + constructor() { + super("Captcha timeout"); + } +}; +var MissingLLMConfigurationError = class extends StagehandError { + constructor() { + super( + "No LLM API key or LLM Client configured. An LLM API key or a custom LLM Client is required to use act, extract, or observe." + ); + } +}; +var HandlerNotInitializedError = class extends StagehandError { + constructor(handlerType) { + super(`${handlerType} handler not initialized`); + } +}; +var StagehandInvalidArgumentError = class extends StagehandError { + constructor(message) { + super(`InvalidArgumentError: ${message}`); + } +}; +var StagehandElementNotFoundError = class extends StagehandError { + constructor(xpaths) { + super(`Could not find an element for the given xPath(s): ${xpaths}`); + } +}; +var AgentScreenshotProviderError = class extends StagehandError { + constructor(message) { + super(`ScreenshotProviderError: ${message}`); + } +}; +var StagehandMissingArgumentError = class extends StagehandError { + constructor(message) { + super(`MissingArgumentError: ${message}`); + } +}; +var CreateChatCompletionResponseError = class extends StagehandError { + constructor(message) { + super(`CreateChatCompletionResponseError: ${message}`); + } +}; +var StagehandEvalError = class extends StagehandError { + constructor(message) { + super(`StagehandEvalError: ${message}`); + } +}; +var StagehandDomProcessError = class extends StagehandError { + constructor(message) { + super(`Error Processing Dom: ${message}`); + } +}; +var StagehandClickError = class extends StagehandError { + constructor(message, selector) { + super( + `Error Clicking Element with selector: ${selector} Reason: ${message}` + ); + } +}; +var LLMResponseError = class extends StagehandError { + constructor(primitive, message) { + super(`${primitive} LLM response error: ${message}`); + } +}; +var StagehandIframeError = class extends StagehandError { + constructor(frameUrl, message) { + super( + `Unable to resolve frameId for iframe with URL: ${frameUrl} Full error: ${message}` + ); + } +}; +var ContentFrameNotFoundError = class extends StagehandError { + constructor(selector) { + super(`Unable to obtain a content frame for selector: ${selector}`); + } +}; +var XPathResolutionError = class extends StagehandError { + constructor(xpath) { + super(`XPath "${xpath}" does not resolve in the current page or frames`); + } +}; +var ExperimentalApiConflictError = class extends StagehandError { + constructor() { + super( + "`experimental` mode cannot be used together with the Stagehand API. To use experimental features, set experimental: true, and useApi: false in the stagehand constructor. To use the Stagehand API, set experimental: false and useApi: true in the stagehand constructor. " + ); + } +}; +var ExperimentalNotConfiguredError = class extends StagehandError { + constructor(featureName) { + super(`Feature "${featureName}" is an experimental feature, and cannot be configured when useAPI: true. + Please set experimental: true and useAPI: false in the stagehand constructor to use this feature. + If you wish to use the Stagehand API, please ensure ${featureName} is not defined in your function call, + and set experimental: false, useAPI: true in the Stagehand constructor. `); + } +}; +var ZodSchemaValidationError = class extends Error { + constructor(received, issues) { + super(`Zod schema validation failed + +\u2014 Received \u2014 +${JSON.stringify(received, null, 2)} + +\u2014 Issues \u2014 +${JSON.stringify(issues, null, 2)}`); + this.received = received; + this.issues = issues; + this.name = "ZodSchemaValidationError"; + } +}; +var StagehandInitError = class extends StagehandError { + constructor(message) { + super(message); + } +}; +var StagehandShadowRootMissingError = class extends StagehandError { + constructor(detail) { + super( + `No shadow root present on the resolved host` + (detail ? `: ${detail}` : "") + ); + } +}; +var StagehandShadowSegmentEmptyError = class extends StagehandError { + constructor() { + super(`Empty selector segment after shadow-DOM hop ("//")`); + } +}; +var StagehandShadowSegmentNotFoundError = class extends StagehandError { + constructor(segment, hint) { + super( + `Shadow segment '${segment}' matched no element inside shadow root` + (hint ? ` ${hint}` : "") + ); + } +}; + +// lib/handlers/handlerUtils/actHandlerUtils.ts +var IFRAME_STEP_RE = /^iframe(\[[^\]]+])?$/i; +function stepToCss(step) { + const m = step.match(/^([a-zA-Z*][\w-]*)(?:\[(\d+)])?$/); + if (!m) return step; + const [, tag, idxRaw] = m; + const idx = idxRaw ? Number(idxRaw) : null; + if (tag === "*") return idx ? `*:nth-child(${idx})` : `*`; + return idx ? `${tag}:nth-of-type(${idx})` : tag; +} +var buildDirect = (steps) => steps.map(stepToCss).join(" > "); +var buildDesc = (steps) => steps.map(stepToCss).join(" "); +function resolveShadowSegment(hostLoc, shadowSteps, attr = "data-__stagehand-id", timeout = 1500) { + return __async(this, null, function* () { + const direct = buildDirect(shadowSteps); + const desc = buildDesc(shadowSteps); + const { id, noRoot } = yield hostLoc.evaluate( + (host, { direct: direct2, desc: desc2, attr: attr2, timeout: timeout2 }) => { + var _a15, _b; + const backdoor = window.__stagehand__; + const root = (_b = host.shadowRoot) != null ? _b : (_a15 = backdoor == null ? void 0 : backdoor.getClosedRoot) == null ? void 0 : _a15.call(backdoor, host); + if (!root) return { id: null, noRoot: true }; + const tryFind = () => { + var _a16; + return (_a16 = root.querySelector(direct2)) != null ? _a16 : root.querySelector(desc2); + }; + return new Promise((resolve2) => { + const mark = (el) => { + let v = el.getAttribute(attr2); + if (!v) { + v = "sh_" + Math.random().toString(36).slice(2) + Date.now().toString(36); + el.setAttribute(attr2, v); + } + return { id: v, noRoot: false }; + }; + const first = tryFind(); + if (first) return resolve2(mark(first)); + const start = Date.now(); + const tick = () => { + const el = tryFind(); + if (el) return resolve2(mark(el)); + if (Date.now() - start >= timeout2) + return resolve2({ id: null, noRoot: false }); + setTimeout(tick, 50); + }; + tick(); + }); + }, + { direct, desc, attr, timeout } + ); + if (noRoot) { + throw new StagehandShadowRootMissingError( + `segment='${shadowSteps.join("/")}'` + ); + } + if (!id) { + throw new StagehandShadowSegmentNotFoundError(shadowSteps.join("/")); + } + return hostLoc.locator(`stagehand=${id}`); + }); +} +function deepLocatorWithShadow(root, xpath) { + return __async(this, null, function* () { + if (!xpath.startsWith("/")) xpath = "/" + xpath; + const tokens = xpath.split("/"); + let ctx = root; + let buffer = []; + let elementScoped = false; + const xp = () => elementScoped ? "xpath=./" : "xpath=/"; + const flushIntoFrame = () => { + if (!buffer.length) return; + ctx = ctx.frameLocator( + xp() + buffer.join("/") + ); + buffer = []; + elementScoped = false; + }; + const flushIntoLocator = () => { + if (!buffer.length) return; + ctx = ctx.locator( + xp() + buffer.join("/") + ); + buffer = []; + elementScoped = true; + }; + for (let i = 1; i < tokens.length; i++) { + const step = tokens[i]; + if (step === "") { + flushIntoLocator(); + const seg = []; + let j = i + 1; + for (; j < tokens.length; j++) { + const t = tokens[j]; + if (t === "" || IFRAME_STEP_RE.test(t)) break; + seg.push(t); + } + if (!seg.length) throw new StagehandShadowSegmentEmptyError(); + ctx = yield resolveShadowSegment(ctx, seg); + elementScoped = true; + i = j - 1; + continue; + } + buffer.push(step); + if (IFRAME_STEP_RE.test(step)) flushIntoFrame(); + } + if (buffer.length === 0) { + if (elementScoped) return ctx; + return ctx.locator("xpath=/"); + } + return ctx.locator( + xp() + buffer.join("/") + ); + }); +} +function deepLocator(root, xpath) { + if (!xpath.startsWith("/")) xpath = "/" + xpath; + const steps = xpath.split("/").filter(Boolean); + let ctx = root; + let buffer = []; + const flushIntoFrame = () => { + if (buffer.length === 0) return; + const selector = "xpath=/" + buffer.join("/"); + ctx = ctx.frameLocator(selector); + buffer = []; + }; + for (const step of steps) { + buffer.push(step); + if (IFRAME_STEP_RE.test(step)) { + flushIntoFrame(); + } + } + const finalSelector = "xpath=/" + buffer.join("/"); + return ctx.locator(finalSelector); +} +var methodHandlerMap = { + scrollIntoView: scrollElementIntoView, + scrollTo: scrollElementToPercentage, + scroll: scrollElementToPercentage, + "mouse.wheel": scrollElementToPercentage, + fill: fillOrType, + type: fillOrType, + press: pressKey, + click: clickElement, + nextChunk: scrollToNextChunk, + prevChunk: scrollToPreviousChunk, + selectOptionFromDropdown: selectOption +}; +function scrollToNextChunk(ctx) { + return __async(this, null, function* () { + const { locator, logger, xpath } = ctx; + logger({ + category: "action", + message: "scrolling to next chunk", + level: 2, + auxiliary: { + xpath: { value: xpath, type: "string" } + } + }); + try { + yield locator.evaluate( + (element) => { + var _a15, _b, _c; + const waitForScrollEnd = (el) => new Promise((resolve2) => { + var _a16; + let last = (_a16 = el.scrollTop) != null ? _a16 : 0; + const check = () => { + var _a17; + const cur = (_a17 = el.scrollTop) != null ? _a17 : 0; + if (cur === last) return resolve2(); + last = cur; + requestAnimationFrame(check); + }; + requestAnimationFrame(check); + }); + const tagName = element.tagName.toLowerCase(); + if (tagName === "html" || tagName === "body") { + const height2 = (_b = (_a15 = window.visualViewport) == null ? void 0 : _a15.height) != null ? _b : window.innerHeight; + window.scrollBy({ top: height2, left: 0, behavior: "smooth" }); + const scrollingRoot = (_c = document.scrollingElement) != null ? _c : document.documentElement; + return waitForScrollEnd(scrollingRoot); + } + const height = element.getBoundingClientRect().height; + element.scrollBy({ + top: height, + left: 0, + behavior: "smooth" + }); + return waitForScrollEnd(element); + }, + void 0, + { timeout: 1e4 } + ); + } catch (e) { + logger({ + category: "action", + message: "error scrolling to next chunk", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function scrollToPreviousChunk(ctx) { + return __async(this, null, function* () { + const { locator, logger, xpath } = ctx; + logger({ + category: "action", + message: "scrolling to previous chunk", + level: 2, + auxiliary: { + xpath: { value: xpath, type: "string" } + } + }); + try { + yield locator.evaluate( + (element) => { + var _a15, _b, _c; + const waitForScrollEnd = (el) => new Promise((resolve2) => { + var _a16; + let last = (_a16 = el.scrollTop) != null ? _a16 : 0; + const check = () => { + var _a17; + const cur = (_a17 = el.scrollTop) != null ? _a17 : 0; + if (cur === last) return resolve2(); + last = cur; + requestAnimationFrame(check); + }; + requestAnimationFrame(check); + }); + const tagName = element.tagName.toLowerCase(); + if (tagName === "html" || tagName === "body") { + const height2 = (_b = (_a15 = window.visualViewport) == null ? void 0 : _a15.height) != null ? _b : window.innerHeight; + window.scrollBy({ top: -height2, left: 0, behavior: "smooth" }); + const rootScrollingEl = (_c = document.scrollingElement) != null ? _c : document.documentElement; + return waitForScrollEnd(rootScrollingEl); + } + const height = element.getBoundingClientRect().height; + element.scrollBy({ + top: -height, + left: 0, + behavior: "smooth" + }); + return waitForScrollEnd(element); + }, + void 0, + { timeout: 1e4 } + ); + } catch (e) { + logger({ + category: "action", + message: "error scrolling to previous chunk", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function scrollElementIntoView(ctx) { + return __async(this, null, function* () { + const { locator, xpath, logger } = ctx; + logger({ + category: "action", + message: "scrolling element into view", + level: 2, + auxiliary: { + xpath: { value: xpath, type: "string" } + } + }); + try { + yield locator.evaluate((element) => { + element.scrollIntoView({ behavior: "smooth", block: "center" }); + }); + } catch (e) { + logger({ + category: "action", + message: "error scrolling element into view", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function scrollElementToPercentage(ctx) { + return __async(this, null, function* () { + const { args, xpath, logger, locator } = ctx; + logger({ + category: "action", + message: "scrolling element vertically to specified percentage", + level: 2, + auxiliary: { + xpath: { value: xpath, type: "string" }, + coordinate: { value: JSON.stringify(args), type: "string" } + } + }); + try { + const [yArg = "0%"] = args; + yield locator.evaluate( + (element, { yArg: yArg2 }) => { + function parsePercent(val) { + const cleaned = val.trim().replace("%", ""); + const num = parseFloat(cleaned); + return Number.isNaN(num) ? 0 : Math.max(0, Math.min(num, 100)); + } + const yPct = parsePercent(yArg2); + if (element.tagName.toLowerCase() === "html") { + const scrollHeight = document.body.scrollHeight; + const viewportHeight = window.innerHeight; + const scrollTop = (scrollHeight - viewportHeight) * (yPct / 100); + window.scrollTo({ + top: scrollTop, + left: window.scrollX, + behavior: "smooth" + }); + } else { + const scrollHeight = element.scrollHeight; + const clientHeight = element.clientHeight; + const scrollTop = (scrollHeight - clientHeight) * (yPct / 100); + element.scrollTo({ + top: scrollTop, + left: element.scrollLeft, + behavior: "smooth" + }); + } + }, + { yArg }, + { timeout: 1e4 } + ); + } catch (e) { + logger({ + category: "action", + message: "error scrolling element vertically to percentage", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" }, + args: { value: JSON.stringify(args), type: "object" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function fillOrType(ctx) { + return __async(this, null, function* () { + var _a15; + const { locator, xpath, args, logger } = ctx; + try { + yield locator.fill("", { force: true }); + const text = ((_a15 = args[0]) == null ? void 0 : _a15.toString()) || ""; + yield locator.fill(text, { force: true }); + } catch (e) { + logger({ + category: "action", + message: "error filling element", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function pressKey(ctx) { + return __async(this, null, function* () { + var _a15, _b, _c, _d; + const { + locator, + xpath, + args, + logger, + stagehandPage, + initialUrl, + domSettleTimeoutMs + } = ctx; + try { + const key = (_b = (_a15 = args[0]) == null ? void 0 : _a15.toString()) != null ? _b : ""; + yield locator.page().keyboard.press(key); + yield handlePossiblePageNavigation( + "press", + xpath, + initialUrl, + stagehandPage, + logger, + domSettleTimeoutMs + ); + } catch (e) { + logger({ + category: "action", + message: "error pressing key", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + key: { value: (_d = (_c = args[0]) == null ? void 0 : _c.toString()) != null ? _d : "unknown", type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function selectOption(ctx) { + return __async(this, null, function* () { + var _a15; + const { locator, xpath, args, logger } = ctx; + try { + const text = ((_a15 = args[0]) == null ? void 0 : _a15.toString()) || ""; + yield locator.selectOption(text, { timeout: 5e3 }); + } catch (e) { + logger({ + category: "action", + message: "error selecting option", + level: 0, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function clickElement(ctx) { + return __async(this, null, function* () { + const { + locator, + xpath, + args, + logger, + stagehandPage, + initialUrl, + domSettleTimeoutMs + } = ctx; + logger({ + category: "action", + message: "page URL before click", + level: 2, + auxiliary: { + url: { + value: stagehandPage.page.url(), + type: "string" + } + } + }); + try { + yield locator.click({ timeout: 3500 }); + } catch (e) { + logger({ + category: "action", + message: "Playwright click failed, falling back to JS click", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" }, + method: { value: "click", type: "string" }, + args: { value: JSON.stringify(args), type: "object" } + } + }); + try { + yield locator.evaluate((el) => el.click(), void 0, { + timeout: 3500 + }); + } catch (e2) { + logger({ + category: "action", + message: "error performing click (JS fallback)", + level: 0, + auxiliary: { + error: { value: e2.message, type: "string" }, + trace: { value: e2.stack, type: "string" }, + xpath: { value: xpath, type: "string" }, + method: { value: "click", type: "string" }, + args: { value: JSON.stringify(args), type: "object" } + } + }); + throw new StagehandClickError(xpath, e2.message); + } + } + yield handlePossiblePageNavigation( + "click", + xpath, + initialUrl, + stagehandPage, + logger, + domSettleTimeoutMs + ); + }); +} +function fallbackLocatorMethod(ctx) { + return __async(this, null, function* () { + const { locator, xpath, method, args, logger } = ctx; + logger({ + category: "action", + message: "page URL before action", + level: 2, + auxiliary: { + url: { value: locator.page().url(), type: "string" } + } + }); + try { + yield locator[method](...args.map((arg) => (arg == null ? void 0 : arg.toString()) || "")); + } catch (e) { + logger({ + category: "action", + message: "error performing method", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + xpath: { value: xpath, type: "string" }, + method: { value: method, type: "string" }, + args: { value: JSON.stringify(args), type: "object" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); +} +function handlePossiblePageNavigation(actionDescription, xpath, initialUrl, stagehandPage, logger, domSettleTimeoutMs) { + return __async(this, null, function* () { + logger({ + category: "action", + message: `${actionDescription}, checking for page navigation`, + level: 1, + auxiliary: { + xpath: { value: xpath, type: "string" } + } + }); + const newOpenedTab = yield Promise.race([ + new Promise((resolve2) => { + stagehandPage.context.once("page", (page) => resolve2(page)); + setTimeout(() => resolve2(null), 1500); + }) + ]); + logger({ + category: "action", + message: `${actionDescription} complete`, + level: 1, + auxiliary: { + newOpenedTab: { + value: newOpenedTab ? "opened a new tab" : "no new tabs opened", + type: "string" + } + } + }); + if (newOpenedTab && newOpenedTab.url() !== "about:blank") { + logger({ + category: "action", + message: "new page detected (new tab) with URL", + level: 1, + auxiliary: { + url: { value: newOpenedTab.url(), type: "string" } + } + }); + yield stagehandPage.page.waitForLoadState("domcontentloaded"); + } + try { + yield stagehandPage._waitForSettledDom(domSettleTimeoutMs); + } catch (e) { + logger({ + category: "action", + message: "wait for settled DOM timeout hit", + level: 1, + auxiliary: { + trace: { value: e.stack, type: "string" }, + message: { value: e.message, type: "string" } + } + }); + } + logger({ + category: "action", + message: "finished waiting for (possible) page navigation", + level: 1 + }); + if (stagehandPage.page.url() !== initialUrl) { + logger({ + category: "action", + message: "new page detected with URL", + level: 1, + auxiliary: { + url: { value: stagehandPage.page.url(), type: "string" } + } + }); + } + }); +} + +// lib/handlers/actHandler.ts +var StagehandActHandler = class { + constructor({ + logger, + stagehandPage, + selfHeal, + experimental + }) { + this.logger = logger; + this.stagehandPage = stagehandPage; + this.selfHeal = selfHeal; + this.experimental = experimental; + } + /** + * Perform an immediate Playwright action based on an ObserveResult object + * that was returned from `page.observe(...)`. + */ + actFromObserveResult(observe2, domSettleTimeoutMs) { + return __async(this, null, function* () { + var _a15; + this.logger({ + category: "action", + message: "Performing act from an ObserveResult", + level: 1, + auxiliary: { + observeResult: { + value: JSON.stringify(observe2), + type: "object" + } + } + }); + const method = observe2.method; + if (method === "not-supported") { + this.logger({ + category: "action", + message: "Cannot execute ObserveResult with unsupported method", + level: 1, + auxiliary: { + error: { + value: "NotSupportedError: The method requested in this ObserveResult is not supported by Stagehand.", + type: "string" + }, + trace: { + value: `Cannot execute act from ObserveResult with unsupported method: ${method}`, + type: "string" + } + } + }); + return { + success: false, + message: `Unable to perform action: The method '${method}' is not supported in ObserveResult. Please use a supported Playwright locator method.`, + action: observe2.description || `ObserveResult action (${method})` + }; + } + const args = (_a15 = observe2.arguments) != null ? _a15 : []; + const selector = observe2.selector.replace("xpath=", ""); + try { + yield this._performPlaywrightMethod( + method, + args, + selector, + domSettleTimeoutMs + ); + return { + success: true, + message: `Action [${method}] performed successfully on selector: ${selector}`, + action: observe2.description || `ObserveResult action (${method})` + }; + } catch (err) { + if (!this.selfHeal || err instanceof PlaywrightCommandMethodNotSupportedException) { + this.logger({ + category: "action", + message: "Error performing act from an ObserveResult", + level: 1, + auxiliary: { + error: { value: err.message, type: "string" }, + trace: { value: err.stack, type: "string" } + } + }); + return { + success: false, + message: `Failed to perform act: ${err.message}`, + action: observe2.description || `ObserveResult action (${method})` + }; + } + this.logger({ + category: "action", + message: "Error performing act from an ObserveResult. Reprocessing the page and trying again", + level: 1, + auxiliary: { + error: { value: err.message, type: "string" }, + trace: { value: err.stack, type: "string" }, + observeResult: { value: JSON.stringify(observe2), type: "object" } + } + }); + try { + const actCommand = observe2.description.toLowerCase().startsWith(method.toLowerCase()) ? observe2.description : method ? `${method} ${observe2.description}` : observe2.description; + const instruction = buildActObservePrompt( + actCommand, + Object.values(SupportedPlaywrightAction), + {} + ); + const observeResults = yield this.stagehandPage.observe({ + instruction + }); + if (observeResults.length === 0) { + return { + success: false, + message: `Failed to self heal act: No observe results found for action`, + action: actCommand + }; + } + const element = observeResults[0]; + yield this._performPlaywrightMethod( + // override previously provided method and arguments + observe2.method, + observe2.arguments, + // only update selector + element.selector, + domSettleTimeoutMs + ); + return { + success: true, + message: `Action [${element.method}] performed successfully on selector: ${element.selector}`, + action: observe2.description || `ObserveResult action (${method})` + }; + } catch (err2) { + this.logger({ + category: "action", + message: "Error performing act from an ObserveResult on fallback", + level: 1, + auxiliary: { + error: { value: err2.message, type: "string" }, + trace: { value: err2.stack, type: "string" } + } + }); + return { + success: false, + message: `Failed to perform act: ${err2.message}`, + action: observe2.description || `ObserveResult action (${method})` + }; + } + } + }); + } + /** + * Perform an act based on an instruction. + * This method will observe the page and then perform the act on the first element returned. + */ + observeAct(actionOrOptions, observeHandler, llmClient, requestId) { + return __async(this, null, function* () { + let action; + const observeOptions = {}; + if (typeof actionOrOptions === "object" && actionOrOptions !== null) { + if (!("action" in actionOrOptions)) { + throw new StagehandInvalidArgumentError( + "Invalid argument. Action options must have an `action` field." + ); + } + if (typeof actionOrOptions.action !== "string" || actionOrOptions.action.length === 0) { + throw new StagehandInvalidArgumentError( + "Invalid argument. No action provided." + ); + } + action = actionOrOptions.action; + if (actionOrOptions.modelName) + observeOptions.modelName = actionOrOptions.modelName; + if (actionOrOptions.modelClientOptions) + observeOptions.modelClientOptions = actionOrOptions.modelClientOptions; + } else { + throw new StagehandInvalidArgumentError( + "Invalid argument. Valid arguments are: a string, an ActOptions object with an `action` field not empty, or an ObserveResult with a `selector` and `method` field." + ); + } + const doObserveAndAct = () => __async(this, null, function* () { + const instruction = buildActObservePrompt( + action, + Object.values(SupportedPlaywrightAction), + actionOrOptions.variables + ); + const observeResults = yield observeHandler.observe({ + instruction, + llmClient, + requestId, + drawOverlay: false, + returnAction: true, + fromAct: true, + iframes: actionOrOptions == null ? void 0 : actionOrOptions.iframes + }); + if (observeResults.length === 0) { + return { + success: false, + message: `Failed to perform act: No observe results found for action`, + action + }; + } + const element = observeResults[0]; + if (actionOrOptions.variables) { + Object.keys(actionOrOptions.variables).forEach((key) => { + element.arguments = element.arguments.map( + (arg) => arg.replace(`%${key}%`, actionOrOptions.variables[key]) + ); + }); + } + return this.actFromObserveResult( + element, + actionOrOptions.domSettleTimeoutMs + ); + }); + if (!actionOrOptions.timeoutMs) { + return doObserveAndAct(); + } + const { timeoutMs } = actionOrOptions; + return yield Promise.race([ + doObserveAndAct(), + new Promise((resolve2) => { + setTimeout(() => { + resolve2({ + success: false, + message: `Action timed out after ${timeoutMs}ms`, + action + }); + }, timeoutMs); + }) + ]); + }); + } + _performPlaywrightMethod(method, args, rawXPath, domSettleTimeoutMs) { + return __async(this, null, function* () { + const xpath = rawXPath.replace(/^xpath=/i, "").trim(); + let locator; + if (this.experimental) { + locator = yield deepLocatorWithShadow(this.stagehandPage.page, xpath); + } else { + locator = deepLocator(this.stagehandPage.page, xpath); + } + const initialUrl = this.stagehandPage.page.url(); + this.logger({ + category: "action", + message: "performing playwright method", + level: 2, + auxiliary: { + xpath: { value: xpath, type: "string" }, + method: { value: method, type: "string" } + } + }); + const context = { + method, + locator, + xpath, + args, + logger: this.logger, + stagehandPage: this.stagehandPage, + initialUrl, + domSettleTimeoutMs + }; + try { + const methodFn = methodHandlerMap[method]; + if (methodFn) { + yield methodFn(context); + } else if (typeof locator[method] === "function") { + yield fallbackLocatorMethod(context); + } else { + this.logger({ + category: "action", + message: "chosen method is invalid", + level: 1, + auxiliary: { + method: { value: method, type: "string" } + } + }); + throw new PlaywrightCommandMethodNotSupportedException( + `Method ${method} not supported` + ); + } + yield this.stagehandPage._waitForSettledDom(domSettleTimeoutMs); + } catch (e) { + this.logger({ + category: "action", + message: "error performing method", + level: 1, + auxiliary: { + error: { value: e.message, type: "string" }, + trace: { value: e.stack, type: "string" }, + method: { value: method, type: "string" }, + xpath: { value: xpath, type: "string" }, + args: { value: JSON.stringify(args), type: "object" } + } + }); + throw new PlaywrightCommandException(e.message); + } + }); + } +}; + +// lib/handlers/extractHandler.ts +var import_v34 = require("zod/v3"); + +// lib/inference.ts +var import_v32 = require("zod/v3"); + +// lib/inferenceLogUtils.ts +var import_path = __toESM(require("path")); +var import_fs = __toESM(require("fs")); +function ensureInferenceSummaryDir() { + const inferenceDir = import_path.default.join(process.cwd(), "inference_summary"); + if (!import_fs.default.existsSync(inferenceDir)) { + import_fs.default.mkdirSync(inferenceDir, { recursive: true }); + } + return inferenceDir; +} +function appendSummary(inferenceType, entry) { + const summaryPath = getSummaryJsonPath(inferenceType); + const arrayKey = `${inferenceType}_summary`; + const existingData = readSummaryFile(inferenceType); + existingData[arrayKey].push(entry); + import_fs.default.writeFileSync(summaryPath, JSON.stringify(existingData, null, 2)); +} +function getTimestamp() { + return (/* @__PURE__ */ new Date()).toISOString().replace(/[^0-9T]/g, "").replace("T", "_"); +} +function writeTimestampedTxtFile(directory, prefix, data) { + const baseDir = ensureInferenceSummaryDir(); + const subDir = import_path.default.join(baseDir, directory); + if (!import_fs.default.existsSync(subDir)) { + import_fs.default.mkdirSync(subDir, { recursive: true }); + } + const timestamp = getTimestamp(); + const fileName = `${timestamp}_${prefix}.txt`; + const filePath = import_path.default.join(subDir, fileName); + import_fs.default.writeFileSync( + filePath, + JSON.stringify(data, null, 2).replace(/\\n/g, "\n") + ); + return { fileName, timestamp }; +} +function getSummaryJsonPath(inferenceType) { + const baseDir = ensureInferenceSummaryDir(); + const subDir = import_path.default.join(baseDir, `${inferenceType}_summary`); + if (!import_fs.default.existsSync(subDir)) { + import_fs.default.mkdirSync(subDir, { recursive: true }); + } + return import_path.default.join(subDir, `${inferenceType}_summary.json`); +} +function readSummaryFile(inferenceType) { + const summaryPath = getSummaryJsonPath(inferenceType); + const arrayKey = `${inferenceType}_summary`; + if (!import_fs.default.existsSync(summaryPath)) { + return { [arrayKey]: [] }; + } + try { + const raw = import_fs.default.readFileSync(summaryPath, "utf8"); + const parsed = JSON.parse(raw); + if (parsed && typeof parsed === "object" && Array.isArray(parsed[arrayKey])) { + return parsed; + } + } catch (e) { + } + return { [arrayKey]: [] }; +} + +// lib/inference.ts +function extract(_0) { + return __async(this, arguments, function* ({ + instruction, + domElements, + schema, + llmClient, + chunksSeen, + chunksTotal, + requestId, + logger, + userProvidedInstructions, + logInferenceToFile = false + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h; + const metadataSchema = import_v32.z.object({ + progress: import_v32.z.string().describe( + "progress of what has been extracted so far, as concise as possible" + ), + completed: import_v32.z.boolean().describe( + "true if the goal is now accomplished. Use this conservatively, only when sure that the goal has been completed." + ) + }); + const isUsingAnthropic = llmClient.type === "anthropic"; + const isGPT5 = llmClient.modelName.includes("gpt-5"); + const extractCallMessages = [ + buildExtractSystemPrompt(isUsingAnthropic, userProvidedInstructions), + buildExtractUserPrompt(instruction, domElements, isUsingAnthropic) + ]; + let extractCallFile = ""; + let extractCallTimestamp = ""; + if (logInferenceToFile) { + const { fileName, timestamp } = writeTimestampedTxtFile( + "extract_summary", + "extract_call", + { + requestId, + modelCall: "extract", + messages: extractCallMessages + } + ); + extractCallFile = fileName; + extractCallTimestamp = timestamp; + } + const extractStartTime = Date.now(); + const extractionResponse = yield llmClient.createChatCompletion({ + options: { + messages: extractCallMessages, + response_model: { + schema, + name: "Extraction" + }, + temperature: isGPT5 ? 1 : 0.1, + top_p: 1, + frequency_penalty: 0, + presence_penalty: 0, + requestId + }, + logger + }); + const extractEndTime = Date.now(); + const { data: extractedData, usage: extractUsage } = extractionResponse; + let extractResponseFile = ""; + if (logInferenceToFile) { + const { fileName } = writeTimestampedTxtFile( + "extract_summary", + "extract_response", + { + requestId, + modelResponse: "extract", + rawResponse: extractedData + } + ); + extractResponseFile = fileName; + appendSummary("extract", { + extract_inference_type: "extract", + timestamp: extractCallTimestamp, + LLM_input_file: extractCallFile, + LLM_output_file: extractResponseFile, + prompt_tokens: (_a15 = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _a15 : 0, + completion_tokens: (_b = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _b : 0, + inference_time_ms: extractEndTime - extractStartTime + }); + } + const metadataCallMessages = [ + buildMetadataSystemPrompt(), + buildMetadataPrompt(instruction, extractedData, chunksSeen, chunksTotal) + ]; + let metadataCallFile = ""; + let metadataCallTimestamp = ""; + if (logInferenceToFile) { + const { fileName, timestamp } = writeTimestampedTxtFile( + "extract_summary", + "metadata_call", + { + requestId, + modelCall: "metadata", + messages: metadataCallMessages + } + ); + metadataCallFile = fileName; + metadataCallTimestamp = timestamp; + } + const metadataStartTime = Date.now(); + const metadataResponse = yield llmClient.createChatCompletion({ + options: { + messages: metadataCallMessages, + response_model: { + name: "Metadata", + schema: metadataSchema + }, + temperature: isGPT5 ? 1 : 0.1, + top_p: 1, + frequency_penalty: 0, + presence_penalty: 0, + requestId + }, + logger + }); + const metadataEndTime = Date.now(); + const { + data: { + completed: metadataResponseCompleted, + progress: metadataResponseProgress + }, + usage: metadataResponseUsage + } = metadataResponse; + let metadataResponseFile = ""; + if (logInferenceToFile) { + const { fileName } = writeTimestampedTxtFile( + "extract_summary", + "metadata_response", + { + requestId, + modelResponse: "metadata", + completed: metadataResponseCompleted, + progress: metadataResponseProgress + } + ); + metadataResponseFile = fileName; + appendSummary("extract", { + extract_inference_type: "metadata", + timestamp: metadataCallTimestamp, + LLM_input_file: metadataCallFile, + LLM_output_file: metadataResponseFile, + prompt_tokens: (_c = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _c : 0, + completion_tokens: (_d = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _d : 0, + inference_time_ms: metadataEndTime - metadataStartTime + }); + } + const totalPromptTokens = ((_e = extractUsage == null ? void 0 : extractUsage.prompt_tokens) != null ? _e : 0) + ((_f = metadataResponseUsage == null ? void 0 : metadataResponseUsage.prompt_tokens) != null ? _f : 0); + const totalCompletionTokens = ((_g = extractUsage == null ? void 0 : extractUsage.completion_tokens) != null ? _g : 0) + ((_h = metadataResponseUsage == null ? void 0 : metadataResponseUsage.completion_tokens) != null ? _h : 0); + const totalInferenceTimeMs = extractEndTime - extractStartTime + (metadataEndTime - metadataStartTime); + return __spreadProps(__spreadValues({}, extractedData), { + metadata: { + completed: metadataResponseCompleted, + progress: metadataResponseProgress + }, + prompt_tokens: totalPromptTokens, + completion_tokens: totalCompletionTokens, + inference_time_ms: totalInferenceTimeMs + }); + }); +} +function observe(_0) { + return __async(this, arguments, function* ({ + instruction, + domElements, + llmClient, + requestId, + userProvidedInstructions, + logger, + returnAction = false, + logInferenceToFile = false, + fromAct + }) { + var _a15, _b, _c, _d; + const isGPT5 = llmClient.modelName.includes("gpt-5"); + const observeSchema = import_v32.z.object({ + elements: import_v32.z.array( + import_v32.z.object(__spreadValues({ + elementId: import_v32.z.string().describe( + "the ID string associated with the element. Never include surrounding square brackets. This field must follow the format of 'number-number'." + ), + description: import_v32.z.string().describe( + "a description of the accessible element and its purpose" + ) + }, returnAction ? { + method: import_v32.z.string().describe( + "the candidate method/action to interact with the element. Select one of the available Playwright interaction methods." + ), + arguments: import_v32.z.array( + import_v32.z.string().describe( + "the arguments to pass to the method. For example, for a click, the arguments are empty, but for a fill, the arguments are the value to fill in." + ) + ) + } : {})) + ).describe("an array of accessible elements that match the instruction") + }); + const messages = [ + buildObserveSystemPrompt(userProvidedInstructions), + buildObserveUserMessage(instruction, domElements) + ]; + const filePrefix = fromAct ? "act" : "observe"; + let callTimestamp = ""; + let callFile = ""; + if (logInferenceToFile) { + const { fileName, timestamp } = writeTimestampedTxtFile( + `${filePrefix}_summary`, + `${filePrefix}_call`, + { + requestId, + modelCall: filePrefix, + messages + } + ); + callFile = fileName; + callTimestamp = timestamp; + } + const start = Date.now(); + const rawResponse = yield llmClient.createChatCompletion({ + options: { + messages, + response_model: { + schema: observeSchema, + name: "Observation" + }, + temperature: isGPT5 ? 1 : 0.1, + top_p: 1, + frequency_penalty: 0, + presence_penalty: 0, + requestId + }, + logger + }); + const end = Date.now(); + const usageTimeMs = end - start; + const { data: observeData, usage: observeUsage } = rawResponse; + const promptTokens = (_a15 = observeUsage == null ? void 0 : observeUsage.prompt_tokens) != null ? _a15 : 0; + const completionTokens = (_b = observeUsage == null ? void 0 : observeUsage.completion_tokens) != null ? _b : 0; + let responseFile = ""; + if (logInferenceToFile) { + const { fileName: responseFileName } = writeTimestampedTxtFile( + `${filePrefix}_summary`, + `${filePrefix}_response`, + { + requestId, + modelResponse: filePrefix, + rawResponse: observeData + } + ); + responseFile = responseFileName; + appendSummary(filePrefix, { + [`${filePrefix}_inference_type`]: filePrefix, + timestamp: callTimestamp, + LLM_input_file: callFile, + LLM_output_file: responseFile, + prompt_tokens: promptTokens, + completion_tokens: completionTokens, + inference_time_ms: usageTimeMs + }); + } + const parsedElements = (_d = (_c = observeData.elements) == null ? void 0 : _c.map((el) => { + const base = { + elementId: el.elementId, + description: String(el.description) + }; + if (returnAction) { + return __spreadProps(__spreadValues({}, base), { + method: String(el.method), + arguments: el.arguments + }); + } + return base; + })) != null ? _d : []; + return { + elements: parsedElements, + prompt_tokens: promptTokens, + completion_tokens: completionTokens, + inference_time_ms: usageTimeMs + }; + }); +} + +// lib/utils.ts +var import_v33 = require("zod/v3"); +var import_genai = require("@google/genai"); + +// types/context.ts +var ID_PATTERN = /^\d+-\d+$/; + +// lib/utils.ts +function validateZodSchema(schema, data) { + const result = schema.safeParse(data); + if (result.success) { + return true; + } + throw new ZodSchemaValidationError(data, result.error.format()); +} +function drawObserveOverlay(page, results) { + return __async(this, null, function* () { + const xpathList = results.map((result) => result.selector); + const validXpaths = xpathList.filter((xpath) => xpath !== "xpath="); + yield page.evaluate((selectors) => { + selectors.forEach((selector) => { + let element; + if (selector.startsWith("xpath=")) { + const xpath = selector.substring(6); + element = document.evaluate( + xpath, + document, + null, + XPathResult.FIRST_ORDERED_NODE_TYPE, + null + ).singleNodeValue; + } else { + element = document.querySelector(selector); + } + if (element instanceof HTMLElement) { + const overlay = document.createElement("div"); + overlay.setAttribute("stagehandObserve", "true"); + const rect = element.getBoundingClientRect(); + overlay.style.position = "absolute"; + overlay.style.left = rect.left + "px"; + overlay.style.top = rect.top + "px"; + overlay.style.width = rect.width + "px"; + overlay.style.height = rect.height + "px"; + overlay.style.backgroundColor = "rgba(255, 255, 0, 0.3)"; + overlay.style.pointerEvents = "none"; + overlay.style.zIndex = "10000"; + document.body.appendChild(overlay); + } + }); + }, validXpaths); + }); +} +function clearOverlays(page) { + return __async(this, null, function* () { + yield page.evaluate(() => { + const elements = document.querySelectorAll('[stagehandObserve="true"]'); + elements.forEach((el) => { + const parent = el.parentNode; + while (el.firstChild) { + parent == null ? void 0 : parent.insertBefore(el.firstChild, el); + } + parent == null ? void 0 : parent.removeChild(el); + }); + }); + }); +} +function isRunningInBun() { + return typeof process !== "undefined" && typeof process.versions !== "undefined" && "bun" in process.versions; +} +function decorateGeminiSchema(geminiSchema, zodSchema) { + if (geminiSchema.nullable === void 0) { + geminiSchema.nullable = zodSchema.isOptional(); + } + if (zodSchema.description) { + geminiSchema.description = zodSchema.description; + } + return geminiSchema; +} +function toGeminiSchema(zodSchema) { + const zodType = getZodType(zodSchema); + switch (zodType) { + case "ZodArray": { + return decorateGeminiSchema( + { + type: import_genai.Type.ARRAY, + items: toGeminiSchema( + zodSchema.element + ) + }, + zodSchema + ); + } + case "ZodObject": { + const properties = {}; + const required = []; + Object.entries(zodSchema.shape).forEach( + ([key, value]) => { + properties[key] = toGeminiSchema(value); + if (getZodType(value) !== "ZodOptional") { + required.push(key); + } + } + ); + return decorateGeminiSchema( + { + type: import_genai.Type.OBJECT, + properties, + required: required.length > 0 ? required : void 0 + }, + zodSchema + ); + } + case "ZodString": + return decorateGeminiSchema( + { + type: import_genai.Type.STRING + }, + zodSchema + ); + case "ZodNumber": + return decorateGeminiSchema( + { + type: import_genai.Type.NUMBER + }, + zodSchema + ); + case "ZodBoolean": + return decorateGeminiSchema( + { + type: import_genai.Type.BOOLEAN + }, + zodSchema + ); + case "ZodEnum": + return decorateGeminiSchema( + { + type: import_genai.Type.STRING, + enum: zodSchema._def.values + }, + zodSchema + ); + case "ZodDefault": + case "ZodNullable": + case "ZodOptional": { + const innerSchema = toGeminiSchema(zodSchema._def.innerType); + return decorateGeminiSchema( + __spreadProps(__spreadValues({}, innerSchema), { + nullable: true + }), + zodSchema + ); + } + case "ZodLiteral": + return decorateGeminiSchema( + { + type: import_genai.Type.STRING, + enum: [zodSchema._def.value] + }, + zodSchema + ); + default: + return decorateGeminiSchema( + { + type: import_genai.Type.OBJECT, + nullable: true + }, + zodSchema + ); + } +} +function getZodType(schema) { + return schema._def.typeName; +} +function transformSchema(schema, currentPath) { + var _a15, _b; + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodString)) { + const hasUrlCheck = (_b = (_a15 = schema._def.checks) == null ? void 0 : _a15.some( + (check) => check.kind === "url" + )) != null ? _b : false; + if (hasUrlCheck) { + return [makeIdStringSchema(schema), [{ segments: [] }]]; + } + return [schema, []]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodObject)) { + const shape = schema._def.shape(); + const newShape = {}; + const urlPaths = []; + let changed = false; + const shapeKeys = Object.keys(shape); + for (const key of shapeKeys) { + const child = shape[key]; + const [transformedChild, childPaths] = transformSchema(child, [ + ...currentPath, + key + ]); + if (transformedChild !== child) { + changed = true; + } + newShape[key] = transformedChild; + if (childPaths.length > 0) { + for (const cp of childPaths) { + urlPaths.push({ segments: [key, ...cp.segments] }); + } + } + } + if (changed) { + return [import_v33.z.object(newShape), urlPaths]; + } + return [schema, urlPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodArray)) { + const itemType = schema._def.type; + const [transformedItem, childPaths] = transformSchema(itemType, [ + ...currentPath, + "*" + ]); + const changed = transformedItem !== itemType; + const arrayPaths = childPaths.map((cp) => ({ + segments: ["*", ...cp.segments] + })); + if (changed) { + return [import_v33.z.array(transformedItem), arrayPaths]; + } + return [schema, arrayPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodUnion)) { + const unionOptions = schema._def.options; + const newOptions = []; + let changed = false; + let allPaths = []; + unionOptions.forEach((option, idx) => { + const [newOption, childPaths] = transformSchema(option, [ + ...currentPath, + `union_${idx}` + ]); + if (newOption !== option) { + changed = true; + } + newOptions.push(newOption); + allPaths = [...allPaths, ...childPaths]; + }); + if (changed) { + return [ + import_v33.z.union(newOptions), + allPaths + ]; + } + return [schema, allPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodIntersection)) { + const leftType = schema._def.left; + const rightType = schema._def.right; + const [left, leftPaths] = transformSchema(leftType, [ + ...currentPath, + "intersection_left" + ]); + const [right, rightPaths] = transformSchema(rightType, [ + ...currentPath, + "intersection_right" + ]); + const changed = left !== leftType || right !== rightType; + const allPaths = [...leftPaths, ...rightPaths]; + if (changed) { + return [import_v33.z.intersection(left, right), allPaths]; + } + return [schema, allPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodOptional)) { + const innerType = schema._def.innerType; + const [inner, innerPaths] = transformSchema(innerType, currentPath); + if (inner !== innerType) { + return [import_v33.z.optional(inner), innerPaths]; + } + return [schema, innerPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodNullable)) { + const innerType = schema._def.innerType; + const [inner, innerPaths] = transformSchema(innerType, currentPath); + if (inner !== innerType) { + return [import_v33.z.nullable(inner), innerPaths]; + } + return [schema, innerPaths]; + } + if (isKind(schema, import_v33.ZodFirstPartyTypeKind.ZodEffects)) { + const baseSchema = schema._def.schema; + const [newBaseSchema, basePaths] = transformSchema(baseSchema, currentPath); + if (newBaseSchema !== baseSchema) { + return [import_v33.z.effect(newBaseSchema, schema._def.effect), basePaths]; + } + return [schema, basePaths]; + } + return [schema, []]; +} +function injectUrls(obj, path4, idToUrlMapping) { + var _a15; + if (path4.length === 0) return; + const [key, ...rest] = path4; + if (key === "*") { + if (Array.isArray(obj)) { + for (const item of obj) injectUrls(item, rest, idToUrlMapping); + } + return; + } + if (obj && typeof obj === "object") { + const record = obj; + if (path4.length === 1) { + const fieldValue = record[key]; + const id = typeof fieldValue === "number" ? String(fieldValue) : typeof fieldValue === "string" && ID_PATTERN.test(fieldValue) ? fieldValue : void 0; + if (id !== void 0) { + record[key] = (_a15 = idToUrlMapping[id]) != null ? _a15 : ""; + } + } else { + injectUrls(record[key], rest, idToUrlMapping); + } + } +} +function isKind(s, kind) { + return s._def.typeName === kind; +} +function makeIdStringSchema(orig) { + var _a15, _b, _c; + const userDesc = ( + // Zod ≥3.23 exposes .description directly; fall back to _def for older minor versions + (_c = (_b = orig.description) != null ? _b : (_a15 = orig._def) == null ? void 0 : _a15.description) != null ? _c : "" + ); + const base = `This field must be the element-ID in the form 'frameId-backendId' (e.g. "0-432").`; + const composed = userDesc.trim().length > 0 ? `${base} that follows this user-defined description: ${userDesc}` : base; + return import_v33.z.string().regex(ID_PATTERN).describe(composed); +} +var providerEnvVarMap = { + openai: "OPENAI_API_KEY", + anthropic: "ANTHROPIC_API_KEY", + google: "GEMINI_API_KEY", + groq: "GROQ_API_KEY", + cerebras: "CEREBRAS_API_KEY", + togetherai: "TOGETHER_AI_API_KEY", + mistral: "MISTRAL_API_KEY", + deepseek: "DEEPSEEK_API_KEY", + perplexity: "PERPLEXITY_API_KEY", + azure: "AZURE_API_KEY", + xai: "XAI_API_KEY", + google_legacy: "GOOGLE_API_KEY" +}; +function loadApiKeyFromEnv(provider, logger) { + if (!provider) { + return void 0; + } + const envVarName = providerEnvVarMap[provider]; + if (!envVarName) { + logger({ + category: "init", + message: `No known environment variable for provider '${provider}'`, + level: 0 + }); + return void 0; + } + const apiKeyFromEnv = process.env[envVarName]; + if (typeof apiKeyFromEnv === "string" && apiKeyFromEnv.length > 0) { + return apiKeyFromEnv; + } + logger({ + category: "init", + message: `API key for ${provider} not found in environment variable ${envVarName}`, + level: 0 + }); + return void 0; +} +function trimTrailingTextNode(path4) { + return path4 == null ? void 0 : path4.replace(/\/text\(\)(\[\d+\])?$/iu, ""); +} + +// lib/a11y/utils.ts +var IFRAME_STEP_RE2 = /iframe\[\d+]$/i; +var PUA_START = 57344; +var PUA_END = 63743; +var NBSP_CHARS = /* @__PURE__ */ new Set([160, 8239, 8199, 65279]); +var WORLD_NAME = "stagehand-world"; +function cleanText(input) { + let out = ""; + let prevWasSpace = false; + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + if (code >= PUA_START && code <= PUA_END) { + continue; + } + if (NBSP_CHARS.has(code)) { + if (!prevWasSpace) { + out += " "; + prevWasSpace = true; + } + continue; + } + out += input[i]; + prevWasSpace = input[i] === " "; + } + return out.trim(); +} +function formatSimplifiedTree(node, level = 0) { + var _a15, _b, _c; + const indent = " ".repeat(level); + const idLabel = (_a15 = node.encodedId) != null ? _a15 : node.nodeId; + const namePart = node.name ? `: ${cleanText(node.name)}` : ""; + const currentLine = `${indent}[${idLabel}] ${node.role}${namePart} +`; + const childrenLines = (_c = (_b = node.children) == null ? void 0 : _b.map((c) => formatSimplifiedTree(c, level + 1)).join("")) != null ? _c : ""; + return currentLine + childrenLines; +} +var lowerCache = /* @__PURE__ */ new Map(); +var lc = (raw) => { + let v = lowerCache.get(raw); + if (!v) { + v = raw.toLowerCase(); + lowerCache.set(raw, v); + } + return v; +}; +function buildBackendIdMaps(experimental, sp, targetFrame) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e; + let session; + if (!targetFrame || targetFrame === sp.page.mainFrame()) { + session = yield sp.getCDPClient(); + } else { + try { + session = yield sp.context.newCDPSession(targetFrame); + } catch (e) { + session = yield sp.getCDPClient(); + } + } + yield sp.enableCDP( + "DOM", + session === (yield sp.getCDPClient()) ? void 0 : targetFrame + ); + try { + const { root } = yield session.send("DOM.getDocument", { + depth: -1, + pierce: true + }); + let startNode = root; + let rootFid = targetFrame && (yield getCDPFrameId(sp, targetFrame)); + if (targetFrame && targetFrame !== sp.page.mainFrame() && session === (yield sp.getCDPClient())) { + const frameId = rootFid; + const { backendNodeId } = yield sp.sendCDP( + "DOM.getFrameOwner", + { frameId } + ); + let iframeNode; + const locate = (n) => { + var _a16, _b2, _c2, _d2; + if (experimental) { + if (n.backendNodeId === backendNodeId) { + iframeNode = n; + return true; + } + if ((_a16 = n.shadowRoots) == null ? void 0 : _a16.some(locate)) return true; + if ((_b2 = n.children) == null ? void 0 : _b2.some(locate)) return true; + if (n.contentDocument && locate(n.contentDocument)) return true; + return false; + } else { + if (n.backendNodeId === backendNodeId) return iframeNode = n, true; + return ((_d2 = (_c2 = n.children) == null ? void 0 : _c2.some(locate)) != null ? _d2 : false) || (n.contentDocument ? locate(n.contentDocument) : false); + } + }; + if (!locate(root) || !(iframeNode == null ? void 0 : iframeNode.contentDocument)) { + throw new Error("iframe element or its contentDocument not found"); + } + startNode = iframeNode.contentDocument; + rootFid = (_a15 = iframeNode.contentDocument.frameId) != null ? _a15 : frameId; + } + const tagNameMap = {}; + const xpathMap = {}; + const stack = [{ node: startNode, path: "", fid: rootFid }]; + const seen = /* @__PURE__ */ new Set(); + const joinStep = (base, step) => base.endsWith("//") ? `${base}${step}` : `${base}/${step}`; + while (stack.length) { + const { node, path: path4, fid } = stack.pop(); + if (!node.backendNodeId) continue; + const enc = sp.encodeWithFrameId(fid, node.backendNodeId); + if (seen.has(enc)) continue; + seen.add(enc); + tagNameMap[enc] = lc(String(node.nodeName)); + xpathMap[enc] = path4; + if (lc(node.nodeName) === "iframe" && node.contentDocument) { + const childFid = (_b = node.contentDocument.frameId) != null ? _b : fid; + stack.push({ node: node.contentDocument, path: "", fid: childFid }); + } + if (((_c = node.shadowRoots) == null ? void 0 : _c.length) && experimental) { + for (const shadowRoot of node.shadowRoots) { + stack.push({ + node: shadowRoot, + path: `${path4}//`, + fid + }); + } + } + const kids = (_d = node.children) != null ? _d : []; + if (kids.length) { + const segs = []; + const ctr = {}; + for (const child of kids) { + const tag = lc(String(child.nodeName)); + const key = `${child.nodeType}:${tag}`; + const idx = ctr[key] = ((_e = ctr[key]) != null ? _e : 0) + 1; + if (child.nodeType === 3) { + segs.push(`text()[${idx}]`); + } else if (child.nodeType === 8) { + segs.push(`comment()[${idx}]`); + } else { + segs.push( + tag.includes(":") ? `*[name()='${tag}'][${idx}]` : `${tag}[${idx}]` + ); + } + } + for (let i = kids.length - 1; i >= 0; i--) { + stack.push({ + node: kids[i], + path: joinStep(path4, segs[i]), + fid + }); + } + } + } + return { tagNameMap, xpathMap }; + } finally { + yield sp.disableCDP( + "DOM", + session === (yield sp.getCDPClient()) ? void 0 : targetFrame + ); + } + }); +} +function cleanStructuralNodes(node, tagNameMap, logger) { + return __async(this, null, function* () { + var _a15; + if (+node.nodeId < 0) return null; + if (!((_a15 = node.children) == null ? void 0 : _a15.length)) { + return node.role === "generic" || node.role === "none" ? null : node; + } + const cleanedChildren = (yield Promise.all( + node.children.map((c) => cleanStructuralNodes(c, tagNameMap, logger)) + )).filter(Boolean); + if (node.role === "generic" || node.role === "none") { + if (cleanedChildren.length === 1) { + return cleanedChildren[0]; + } else if (cleanedChildren.length === 0) { + return null; + } + if (cleanedChildren.length === 0) return null; + } + if ((node.role === "generic" || node.role === "none") && node.encodedId !== void 0) { + const tagName = tagNameMap[node.encodedId]; + if (tagName) node.role = tagName; + } + if (node.role === "combobox" && node.encodedId !== void 0 && tagNameMap[node.encodedId] === "select") { + node.role = "select"; + } + const pruned = removeRedundantStaticTextChildren(node, cleanedChildren); + if (!pruned.length && (node.role === "generic" || node.role === "none")) { + return null; + } + return __spreadProps(__spreadValues({}, node), { children: pruned }); + }); +} +function buildHierarchicalTree(nodes, tagNameMap, logger, xpathMap) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e; + const idToUrl = {}; + const nodeMap = /* @__PURE__ */ new Map(); + const iframeList = []; + const isInteractive = (n) => n.role !== "none" && n.role !== "generic" && n.role !== "InlineTextBox"; + const backendToIds = /* @__PURE__ */ new Map(); + for (const enc of Object.keys(tagNameMap)) { + const [, backend] = enc.split("-"); + const list = (_a15 = backendToIds.get(+backend)) != null ? _a15 : []; + list.push(enc); + backendToIds.set(+backend, list); + } + for (const node of nodes) { + if (+node.nodeId < 0) continue; + const url = extractUrlFromAXNode(node); + const keep = ((_b = node.name) == null ? void 0 : _b.trim()) || ((_c = node.childIds) == null ? void 0 : _c.length) || isInteractive(node); + if (!keep) continue; + let encodedId; + if (node.backendDOMNodeId !== void 0) { + const matches = (_d = backendToIds.get(node.backendDOMNodeId)) != null ? _d : []; + if (matches.length === 1) encodedId = matches[0]; + } + if (url && encodedId) idToUrl[encodedId] = url; + nodeMap.set(node.nodeId, __spreadValues(__spreadValues(__spreadValues(__spreadValues({ + encodedId, + role: node.role, + nodeId: node.nodeId + }, node.name && { name: node.name }), node.description && { description: node.description }), node.value && { value: node.value }), node.backendDOMNodeId !== void 0 && { + backendDOMNodeId: node.backendDOMNodeId + })); + } + for (const node of nodes) { + if (node.role === "Iframe") + iframeList.push({ role: node.role, nodeId: node.nodeId }); + if (!node.parentId) continue; + const parent = nodeMap.get(node.parentId); + const current = nodeMap.get(node.nodeId); + if (parent && current) ((_e = parent.children) != null ? _e : parent.children = []).push(current); + } + const roots = nodes.filter((n) => !n.parentId && nodeMap.has(n.nodeId)).map((n) => nodeMap.get(n.nodeId)); + const cleanedRoots = (yield Promise.all( + roots.map((n) => cleanStructuralNodes(n, tagNameMap, logger)) + )).filter(Boolean); + const simplified = cleanedRoots.map(formatSimplifiedTree).join("\n"); + return { + tree: cleanedRoots, + simplified, + iframes: iframeList, + idToUrl, + xpathMap + }; + }); +} +function getCDPFrameId(sp, frame) { + return __async(this, null, function* () { + if (!frame || frame === sp.page.mainFrame()) return void 0; + const rootResp = yield sp.sendCDP("Page.getFrameTree"); + const { frameTree: root } = rootResp; + const targetUrl = frame.url(); + let depth = 0; + for (let p = frame.parentFrame(); p; p = p.parentFrame()) depth++; + const withFragment = (f) => { + var _a15; + return f.url + ((_a15 = f.urlFragment) != null ? _a15 : ""); + }; + const findByUrlDepth = (node, lvl = 0) => { + var _a15; + if (lvl === depth && withFragment(node.frame) === targetUrl) + return node.frame.id; + for (const child of (_a15 = node.childFrames) != null ? _a15 : []) { + const id = findByUrlDepth(child, lvl + 1); + if (id) return id; + } + return void 0; + }; + const sameProcId = findByUrlDepth(root); + if (sameProcId) return sameProcId; + try { + const sess = yield sp.context.newCDPSession(frame); + const ownResp = yield sess.send("Page.getFrameTree"); + const { frameTree } = ownResp; + return frameTree.frame.id; + } catch (err) { + throw new StagehandIframeError(targetUrl, String(err)); + } + }); +} +function getAccessibilityTree(experimental, stagehandPage, logger, selector, targetFrame) { + return __async(this, null, function* () { + const { tagNameMap, xpathMap } = yield buildBackendIdMaps( + experimental, + stagehandPage, + targetFrame + ); + yield stagehandPage.enableCDP("Accessibility", targetFrame); + try { + let params = {}; + let sessionFrame = targetFrame; + if (targetFrame && targetFrame !== stagehandPage.page.mainFrame()) { + let isOopif = true; + try { + yield stagehandPage.context.newCDPSession(targetFrame); + } catch (e) { + isOopif = false; + } + if (!isOopif) { + const frameId = yield getCDPFrameId(stagehandPage, targetFrame); + logger({ + message: `same-proc iframe: frameId=${frameId}. Using existing CDP session.`, + level: 1 + }); + if (frameId) params = { frameId }; + sessionFrame = void 0; + } else { + logger({ message: `OOPIF iframe: starting new CDP session`, level: 1 }); + params = {}; + sessionFrame = targetFrame; + } + } + const { nodes: fullNodes } = yield stagehandPage.sendCDP("Accessibility.getFullAXTree", params, sessionFrame); + const scrollableIds = yield findScrollableElementIds( + stagehandPage, + targetFrame + ); + let nodes = fullNodes; + if (selector) { + nodes = yield filterAXTreeByXPath( + stagehandPage, + fullNodes, + selector, + targetFrame + ); + } + const start = Date.now(); + const tree = yield buildHierarchicalTree( + decorateRoles(nodes, scrollableIds), + tagNameMap, + logger, + xpathMap + ); + logger({ + category: "observation", + message: `got accessibility tree in ${Date.now() - start} ms`, + level: 1 + }); + return tree; + } finally { + yield stagehandPage.disableCDP("Accessibility", targetFrame); + } + }); +} +function filterAXTreeByXPath(page, full, xpath, targetFrame) { + return __async(this, null, function* () { + var _a15; + const objectId = yield resolveObjectIdForXPath(page, xpath, targetFrame); + const { node } = yield page.sendCDP( + "DOM.describeNode", + { objectId }, + targetFrame + ); + if (!(node == null ? void 0 : node.backendNodeId)) { + throw new StagehandDomProcessError( + `Unable to resolve backendNodeId for "${xpath}"` + ); + } + const target = full.find((n) => n.backendDOMNodeId === node.backendNodeId); + const keep = /* @__PURE__ */ new Set([target.nodeId]); + const queue = [target]; + while (queue.length) { + const cur = queue.shift(); + for (const id of (_a15 = cur.childIds) != null ? _a15 : []) { + if (keep.has(id)) continue; + keep.add(id); + const child = full.find((n) => n.nodeId === id); + if (child) queue.push(child); + } + } + return full.filter((n) => keep.has(n.nodeId)).map( + (n) => n.nodeId === target.nodeId ? __spreadProps(__spreadValues({}, n), { parentId: void 0 }) : n + ); + }); +} +function decorateRoles(nodes, scrollables) { + return nodes.map((n) => { + var _a15, _b, _c, _d, _e; + let role = (_b = (_a15 = n.role) == null ? void 0 : _a15.value) != null ? _b : ""; + if (scrollables.has(n.backendDOMNodeId)) { + role = role && role !== "generic" && role !== "none" ? `scrollable, ${role}` : "scrollable"; + } + return { + role, + name: (_c = n.name) == null ? void 0 : _c.value, + description: (_d = n.description) == null ? void 0 : _d.value, + value: (_e = n.value) == null ? void 0 : _e.value, + nodeId: n.nodeId, + backendDOMNodeId: n.backendDOMNodeId, + parentId: n.parentId, + childIds: n.childIds, + properties: n.properties + }; + }); +} +function getFrameRootBackendNodeId(sp, frame) { + return __async(this, null, function* () { + if (!frame || frame === sp.page.mainFrame()) { + return null; + } + try { + const cdp = yield sp.page.context().newCDPSession(sp.page); + const fid = yield getCDPFrameId(sp, frame); + if (!fid) { + return null; + } + const { backendNodeId } = yield cdp.send("DOM.getFrameOwner", { + frameId: fid + }); + return backendNodeId != null ? backendNodeId : null; + } catch (error) { + sp.stagehand.logger({ + category: "a11y", + message: `Error getting frame root backend node id: ${String(error)}`, + level: 0 + }); + return null; + } + }); +} +function getFrameRootXpathWithShadow(frame) { + return __async(this, null, function* () { + if (!frame) { + return "/"; + } + const handle = yield frame.frameElement(); + return handle.evaluate((node) => { + function stepFor(el2) { + const tag = el2.tagName.toLowerCase(); + let i = 1; + for (let sib = el2.previousElementSibling; sib; sib = sib.previousElementSibling) { + if (sib.tagName.toLowerCase() === tag) i++; + } + return `${tag}[${i}]`; + } + const segs = []; + let el = node; + while (el) { + segs.unshift(stepFor(el)); + if (el.parentElement) { + el = el.parentElement; + continue; + } + const root = el.getRootNode(); + if (root.host) { + segs.unshift(""); + el = root.host; + continue; + } + break; + } + return "/" + segs.join("/"); + }); + }); +} +function getFrameRootXpath(frame) { + return __async(this, null, function* () { + if (!frame) { + return "/"; + } + const handle = yield frame.frameElement(); + return handle.evaluate((node) => { + const pos = (el) => { + let i = 1; + for (let sib = el.previousElementSibling; sib; sib = sib.previousElementSibling) + if (sib.tagName === el.tagName) i += 1; + return i; + }; + const segs = []; + for (let el = node; el; el = el.parentElement) + segs.unshift(`${el.tagName.toLowerCase()}[${pos(el)}]`); + return `/${segs.join("/")}`; + }); + }); +} +function injectSubtrees(tree, idToTree) { + var _a15, _b; + const uniqueByBackend = (backendId) => { + let found; + let hit = 0; + for (const enc of idToTree.keys()) { + const [, b] = enc.split("-"); + if (+b === backendId) { + if (++hit > 1) return; + found = enc; + } + } + return hit === 1 ? found : void 0; + }; + const stack = [{ lines: tree.split("\n"), idx: 0, indent: "" }]; + const out = []; + const visited = /* @__PURE__ */ new Set(); + while (stack.length) { + const top = stack[stack.length - 1]; + if (top.idx >= top.lines.length) { + stack.pop(); + continue; + } + const raw = top.lines[top.idx++]; + const line = top.indent + raw; + out.push(line); + const m = /^\s*\[([^\]]+)]/.exec(raw); + if (!m) continue; + const label = m[1]; + let enc; + let child; + if (idToTree.has(label)) { + enc = label; + child = idToTree.get(enc); + } else { + let backendId; + const dashMatch = ID_PATTERN.exec(label); + if (dashMatch) { + backendId = +dashMatch[0].split("-")[1]; + } else if (/^\d+$/.test(label)) { + backendId = +label; + } + if (backendId !== void 0) { + const alt = uniqueByBackend(backendId); + if (alt) { + enc = alt; + child = idToTree.get(alt); + } + } + } + if (!enc || !child || visited.has(enc)) continue; + visited.add(enc); + stack.push({ + lines: child.split("\n"), + idx: 0, + indent: ((_b = (_a15 = line.match(/^\s*/)) == null ? void 0 : _a15[0]) != null ? _b : "") + " " + }); + } + return out.join("\n"); +} +function getAccessibilityTreeWithFrames(experimental, stagehandPage, logger, rootXPath) { + return __async(this, null, function* () { + var _a15, _b; + const main = stagehandPage.page.mainFrame(); + let targetFrames; + let innerXPath; + if (rootXPath == null ? void 0 : rootXPath.trim()) { + const { frames, rest } = yield resolveFrameChain( + stagehandPage, + rootXPath.trim() + ); + targetFrames = frames.length ? frames : void 0; + innerXPath = rest; + } + const mainOnlyFilter = !!innerXPath && !targetFrames; + const snapshots = []; + const frameStack = [main]; + while (frameStack.length) { + const frame = frameStack.pop(); + frame.childFrames().forEach((c) => frameStack.push(c)); + if (targetFrames && !targetFrames.includes(frame)) continue; + if (!targetFrames && frame !== main && innerXPath) continue; + const selector = targetFrames ? frame === targetFrames.at(-1) ? innerXPath : void 0 : frame === main ? innerXPath : void 0; + try { + const res = yield getAccessibilityTree( + experimental, + stagehandPage, + logger, + selector, + frame + ); + const backendId = frame === main ? null : yield getFrameRootBackendNodeId(stagehandPage, frame); + let frameXpath; + if (experimental) { + frameXpath = frame === main ? "/" : yield getFrameRootXpathWithShadow(frame); + } else { + frameXpath = frame === main ? "/" : yield getFrameRootXpath(frame); + } + const frameId = yield getCDPFrameId(stagehandPage, frame); + snapshots.push({ + frame, + tree: res.simplified.trimEnd(), + xpathMap: res.xpathMap, + urlMap: res.idToUrl, + frameXpath, + backendNodeId: backendId, + parentFrame: frame.parentFrame(), + frameId + }); + if (mainOnlyFilter) break; + } catch (err) { + logger({ + category: "observation", + message: `\u26A0\uFE0F failed to get AX tree for ${frame === main ? "main frame" : `iframe (${frame.url()})`}`, + level: 1, + auxiliary: { error: { value: String(err), type: "string" } } + }); + } + } + const combinedXpathMap = {}; + const combinedUrlMap = {}; + const seg = /* @__PURE__ */ new Map(); + for (const s of snapshots) seg.set(s.frame, s.frameXpath); + function fullPrefix(f) { + var _a16; + if (!f || f === main) return ""; + const parent = f.parentFrame(); + const above = fullPrefix(parent); + const hop = (_a16 = seg.get(f)) != null ? _a16 : ""; + return hop === "/" ? above : above ? `${above.replace(/\/$/, "")}/${hop.replace(/^\//, "")}` : hop; + } + for (const snap of snapshots) { + const prefix = snap.frameXpath === "/" ? "" : `${fullPrefix(snap.parentFrame)}${snap.frameXpath}`; + for (const [enc, local] of Object.entries(snap.xpathMap)) { + combinedXpathMap[enc] = local === "" ? prefix || "/" : prefix ? `${prefix.replace(/\/$/, "")}/${local.replace(/^\//, "")}` : local; + } + Object.assign(combinedUrlMap, snap.urlMap); + } + const idToTree = /* @__PURE__ */ new Map(); + for (const { backendNodeId, frameId, tree } of snapshots) + if (backendNodeId !== null && frameId !== void 0) + idToTree.set( + stagehandPage.encodeWithFrameId(frameId, backendNodeId), + tree + ); + const rootSnap = snapshots.find((s) => s.frameXpath === "/"); + const combinedTree = rootSnap ? injectSubtrees(rootSnap.tree, idToTree) : (_b = (_a15 = snapshots[0]) == null ? void 0 : _a15.tree) != null ? _b : ""; + return { combinedTree, combinedXpathMap, combinedUrlMap }; + }); +} +function findScrollableElementIds(stagehandPage, targetFrame) { + return __async(this, null, function* () { + const xpaths = targetFrame ? yield targetFrame.evaluate(() => window.getScrollableElementXpaths()) : yield stagehandPage.page.evaluate( + () => window.getScrollableElementXpaths() + ); + const backendIds = /* @__PURE__ */ new Set(); + for (const xpath of xpaths) { + if (!xpath) continue; + const objectId = yield resolveObjectIdForXPath( + stagehandPage, + xpath, + targetFrame + ); + if (objectId) { + const { node } = yield stagehandPage.sendCDP("DOM.describeNode", { objectId }, targetFrame); + if (node == null ? void 0 : node.backendNodeId) backendIds.add(node.backendNodeId); + } + } + return backendIds; + }); +} +function resolveObjectIdForXPath(page, xpath, targetFrame) { + return __async(this, null, function* () { + const contextId = yield getFrameExecutionContextId(page, targetFrame); + const { result } = yield page.sendCDP( + "Runtime.evaluate", + __spreadValues({ + expression: ` + (() => { + const res = document.evaluate( + ${JSON.stringify(xpath)}, + document, + null, + XPathResult.FIRST_ORDERED_NODE_TYPE, + null + ); + return res.singleNodeValue; + })(); + `, + returnByValue: false + }, contextId !== void 0 ? { contextId } : {}), + targetFrame + ); + if (!(result == null ? void 0 : result.objectId)) throw new StagehandElementNotFoundError([xpath]); + return result.objectId; + }); +} +function getFrameExecutionContextId(stagehandPage, frame) { + return __async(this, null, function* () { + if (!frame || frame === stagehandPage.page.mainFrame()) { + return void 0; + } + const frameId = yield getCDPFrameId(stagehandPage, frame); + const { executionContextId } = yield stagehandPage.sendCDP( + "Page.createIsolatedWorld", + { + frameId, + worldName: WORLD_NAME, + grantUniversalAccess: true + }, + frame + ); + return executionContextId; + }); +} +function normaliseSpaces(s) { + let out = ""; + let inWs = false; + for (let i = 0; i < s.length; i++) { + const ch = s.charCodeAt(i); + const isWs = ch === 32 || ch === 9 || ch === 10 || ch === 13; + if (isWs) { + if (!inWs) { + out += " "; + inWs = true; + } + } else { + out += s[i]; + inWs = false; + } + } + return out; +} +function removeRedundantStaticTextChildren(parent, children) { + if (!parent.name) return children; + const parentNorm = normaliseSpaces(parent.name).trim(); + let combinedText = ""; + for (const child of children) { + if (child.role === "StaticText" && child.name) { + combinedText += normaliseSpaces(child.name).trim(); + } + } + if (combinedText === parentNorm) { + return children.filter((c) => c.role !== "StaticText"); + } + return children; +} +function extractUrlFromAXNode(axNode) { + if (!axNode.properties) return void 0; + const urlProp = axNode.properties.find((prop) => prop.name === "url"); + if (urlProp && urlProp.value && typeof urlProp.value.value === "string") { + return urlProp.value.value.trim(); + } + return void 0; +} +function resolveFrameChain(sp, absPath) { + return __async(this, null, function* () { + let path4 = absPath.startsWith("/") ? absPath : "/" + absPath; + let ctxFrame = void 0; + const chain = []; + while (true) { + try { + yield resolveObjectIdForXPath(sp, path4, ctxFrame); + return { frames: chain, rest: path4 }; + } catch (e) { + } + const steps = path4.split("/").filter(Boolean); + const buf = []; + for (let i = 0; i < steps.length; i++) { + buf.push(steps[i]); + if (IFRAME_STEP_RE2.test(steps[i])) { + const selector = "xpath=/" + buf.join("/"); + const handle = (ctxFrame != null ? ctxFrame : sp.page.mainFrame()).locator(selector); + const frame = yield handle.elementHandle().then((h) => h == null ? void 0 : h.contentFrame()); + if (!frame) throw new ContentFrameNotFoundError(selector); + chain.push(frame); + ctxFrame = frame; + path4 = "/" + steps.slice(i + 1).join("/"); + break; + } + if (i === steps.length - 1) { + throw new XPathResolutionError(absPath); + } + } + } + }); +} + +// lib/handlers/extractHandler.ts +var StagehandExtractHandler = class { + constructor({ + stagehand, + logger, + stagehandPage, + userProvidedInstructions, + experimental + }) { + this.stagehand = stagehand; + this.logger = logger; + this.stagehandPage = stagehandPage; + this.userProvidedInstructions = userProvidedInstructions; + this.experimental = experimental; + } + extract() { + return __async(this, arguments, function* ({ + instruction, + schema, + content = {}, + llmClient, + requestId, + domSettleTimeoutMs, + useTextExtract, + selector, + iframes + } = {}) { + const noArgsCalled = !instruction && !schema && !llmClient && !selector; + if (noArgsCalled) { + this.logger({ + category: "extraction", + message: "Extracting the entire page text.", + level: 1 + }); + return this.extractPageText(); + } + if (useTextExtract !== void 0) { + this.logger({ + category: "extraction", + message: "Warning: the `useTextExtract` parameter has no effect in this version of Stagehand and will be removed in future versions.", + level: 1 + }); + } + return this.domExtract({ + instruction, + schema, + content, + llmClient, + requestId, + domSettleTimeoutMs, + selector, + iframes + }); + }); + } + extractPageText(domSettleTimeoutMs) { + return __async(this, null, function* () { + yield this.stagehandPage._waitForSettledDom(domSettleTimeoutMs); + const tree = yield getAccessibilityTree( + this.experimental, + this.stagehandPage, + this.logger + ); + this.logger({ + category: "extraction", + message: "Getting accessibility tree data", + level: 1 + }); + const outputString = tree.simplified; + const result = { page_text: outputString }; + return pageTextSchema.parse(result); + }); + } + domExtract(_0) { + return __async(this, arguments, function* ({ + instruction, + schema, + llmClient, + requestId, + domSettleTimeoutMs, + selector, + iframes + }) { + var _a15; + this.logger({ + category: "extraction", + message: "starting extraction using a11y tree", + level: 1, + auxiliary: { + instruction: { + value: instruction, + type: "string" + } + } + }); + yield this.stagehandPage._waitForSettledDom(domSettleTimeoutMs); + const targetXpath = (_a15 = selector == null ? void 0 : selector.replace(/^xpath=/, "")) != null ? _a15 : ""; + const { + combinedTree: outputString, + combinedUrlMap: idToUrlMapping, + discoveredIframes + } = yield iframes ? getAccessibilityTreeWithFrames( + this.experimental, + this.stagehandPage, + this.logger, + targetXpath + ).then(({ combinedTree, combinedUrlMap }) => ({ + combinedTree, + combinedUrlMap, + combinedXpathMap: {}, + discoveredIframes: [] + })) : getAccessibilityTree( + this.experimental, + this.stagehandPage, + this.logger, + targetXpath + ).then(({ simplified, idToUrl, iframes: frameNodes }) => ({ + combinedTree: simplified, + combinedUrlMap: idToUrl, + combinedXpathMap: {}, + discoveredIframes: frameNodes + })); + this.logger({ + category: "extraction", + message: "Got accessibility tree data", + level: 1 + }); + if (discoveredIframes !== void 0 && discoveredIframes.length > 0) { + this.logger({ + category: "extraction", + message: `Warning: found ${discoveredIframes.length} iframe(s) on the page. If you wish to interact with iframe content, please make sure you are setting iframes: true`, + level: 1 + }); + } + const [transformedSchema, urlFieldPaths] = transformUrlStringsToNumericIds(schema); + const extractionResponse = yield extract({ + instruction, + domElements: outputString, + schema: transformedSchema, + chunksSeen: 1, + chunksTotal: 1, + llmClient, + requestId, + userProvidedInstructions: this.userProvidedInstructions, + logger: this.logger, + logInferenceToFile: this.stagehand.logInferenceToFile + }); + const _b = extractionResponse, { + metadata: { completed }, + prompt_tokens: promptTokens, + completion_tokens: completionTokens, + inference_time_ms: inferenceTimeMs + } = _b, output = __objRest(_b, [ + "metadata", + "prompt_tokens", + "completion_tokens", + "inference_time_ms" + ]); + this.stagehand.updateMetrics( + "EXTRACT" /* EXTRACT */, + promptTokens, + completionTokens, + inferenceTimeMs + ); + this.logger({ + category: "extraction", + message: "received extraction response", + auxiliary: { + extraction_response: { + value: JSON.stringify(extractionResponse), + type: "object" + } + } + }); + if (completed) { + this.logger({ + category: "extraction", + message: "extraction completed successfully", + level: 1, + auxiliary: { + extraction_response: { + value: JSON.stringify(extractionResponse), + type: "object" + } + } + }); + } else { + this.logger({ + category: "extraction", + message: "extraction incomplete after processing all data", + level: 1, + auxiliary: { + extraction_response: { + value: JSON.stringify(extractionResponse), + type: "object" + } + } + }); + } + for (const { segments } of urlFieldPaths) { + injectUrls(output, segments, idToUrlMapping); + } + return output; + }); + } +}; +function transformUrlStringsToNumericIds(schema) { + const shape = schema._def.shape(); + const newShape = {}; + const urlPaths = []; + let changed = false; + for (const [key, value] of Object.entries(shape)) { + const [childTransformed, childPaths] = transformSchema(value, [key]); + newShape[key] = childTransformed; + if (childTransformed !== value) { + changed = true; + } + if (childPaths.length > 0) { + childPaths.forEach((cp) => { + urlPaths.push({ segments: [key, ...cp.segments] }); + }); + } + } + const finalSchema = changed ? import_v34.z.object(newShape) : schema; + return [finalSchema, urlPaths]; +} + +// lib/handlers/observeHandler.ts +var StagehandObserveHandler = class { + constructor({ + stagehand, + logger, + stagehandPage, + userProvidedInstructions, + experimental + }) { + this.stagehand = stagehand; + this.logger = logger; + this.stagehandPage = stagehandPage; + this.userProvidedInstructions = userProvidedInstructions; + this.experimental = experimental; + } + observe(_0) { + return __async(this, arguments, function* ({ + instruction, + llmClient, + requestId, + returnAction, + onlyVisible, + drawOverlay, + fromAct, + iframes + }) { + if (!instruction) { + instruction = `Find elements that can be used for any future actions in the page. These may be navigation links, related pages, section/subsection links, buttons, or other interactive elements. Be comprehensive: if there are multiple elements that may be relevant for future actions, return all of them.`; + } + this.logger({ + category: "observation", + message: "starting observation", + level: 1, + auxiliary: { + instruction: { + value: instruction, + type: "string" + } + } + }); + if (onlyVisible !== void 0) { + this.logger({ + category: "observation", + message: "Warning: the `onlyVisible` parameter has no effect in this version of Stagehand and will be removed in future versions.", + level: 1 + }); + } + yield this.stagehandPage._waitForSettledDom(); + this.logger({ + category: "observation", + message: "Getting accessibility tree data", + level: 1 + }); + const { combinedTree, combinedXpathMap, discoveredIframes } = yield iframes ? getAccessibilityTreeWithFrames( + this.experimental, + this.stagehandPage, + this.logger + ).then(({ combinedTree: combinedTree2, combinedXpathMap: combinedXpathMap2 }) => ({ + combinedTree: combinedTree2, + combinedXpathMap: combinedXpathMap2, + discoveredIframes: [] + })) : getAccessibilityTree( + this.experimental, + this.stagehandPage, + this.logger + ).then(({ simplified, xpathMap, idToUrl, iframes: frameNodes }) => ({ + combinedTree: simplified, + combinedXpathMap: xpathMap, + combinedUrlMap: idToUrl, + discoveredIframes: frameNodes + })); + const observationResponse = yield observe({ + instruction, + domElements: combinedTree, + llmClient, + requestId, + userProvidedInstructions: this.userProvidedInstructions, + logger: this.logger, + returnAction, + logInferenceToFile: this.stagehand.logInferenceToFile, + fromAct + }); + const { + prompt_tokens = 0, + completion_tokens = 0, + inference_time_ms = 0 + } = observationResponse; + this.stagehand.updateMetrics( + fromAct ? "ACT" /* ACT */ : "OBSERVE" /* OBSERVE */, + prompt_tokens, + completion_tokens, + inference_time_ms + ); + if (discoveredIframes.length > 0) { + this.logger({ + category: "observation", + message: `Warning: found ${discoveredIframes.length} iframe(s) on the page. If you wish to interact with iframe content, please make sure you are setting iframes: true`, + level: 1 + }); + discoveredIframes.forEach((iframe) => { + observationResponse.elements.push({ + elementId: this.stagehandPage.encodeWithFrameId( + void 0, + Number(iframe.nodeId) + ), + description: "an iframe", + method: "not-supported", + arguments: [] + }); + }); + } + const elementsWithSelectors = (yield Promise.all( + observationResponse.elements.map((element) => __async(this, null, function* () { + const _a15 = element, { elementId } = _a15, rest = __objRest(_a15, ["elementId"]); + this.logger({ + category: "observation", + message: "Getting xpath for element", + level: 1, + auxiliary: { + elementId: { + value: elementId.toString(), + type: "string" + } + } + }); + if (elementId.includes("-")) { + const lookUpIndex = elementId; + const xpath = combinedXpathMap[lookUpIndex]; + const trimmedXpath = trimTrailingTextNode(xpath); + if (!trimmedXpath || trimmedXpath === "") { + this.logger({ + category: "observation", + message: `Empty xpath returned for element`, + auxiliary: { + observeResult: { + value: JSON.stringify(element), + type: "object" + } + }, + level: 1 + }); + return void 0; + } + return __spreadProps(__spreadValues({}, rest), { + selector: `xpath=${trimmedXpath}` + // Provisioning or future use if we want to use direct CDP + // backendNodeId: elementId, + }); + } else { + this.logger({ + category: "observation", + message: `Element is inside a shadow DOM: ${elementId}`, + level: 0 + }); + return { + description: "an element inside a shadow DOM", + method: "not-supported", + arguments: [], + selector: "not-supported" + }; + } + })) + )).filter((e) => e !== void 0); + this.logger({ + category: "observation", + message: "found elements", + level: 1, + auxiliary: { + elements: { + value: JSON.stringify(elementsWithSelectors), + type: "object" + } + } + }); + if (drawOverlay) { + yield drawObserveOverlay(this.stagehandPage.page, elementsWithSelectors); + } + return elementsWithSelectors; + }); + } +}; + +// types/stagehandApiErrors.ts +var StagehandAPIError = class extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + } +}; +var StagehandAPIUnauthorizedError = class extends StagehandAPIError { + constructor(message) { + super(message || "Unauthorized request"); + } +}; +var StagehandHttpError = class extends StagehandAPIError { + constructor(message) { + super(message); + } +}; +var StagehandServerError = class extends StagehandAPIError { + constructor(message) { + super(message); + } +}; +var StagehandResponseBodyError = class extends StagehandAPIError { + constructor() { + super("Response body is null"); + } +}; +var StagehandResponseParseError = class extends StagehandAPIError { + constructor(message) { + super(message); + } +}; + +// lib/dom/build/scriptContent.ts +var scriptContent = '(() => {\n // lib/dom/elementCheckUtils.ts\n function isElementNode(node) {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n function isTextNode(node) {\n return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n }\n\n // lib/dom/xpathUtils.ts\n function getParentElement(node) {\n return isElementNode(node) ? node.parentElement : node.parentNode;\n }\n function getCombinations(attributes, size) {\n const results = [];\n function helper(start, combo) {\n if (combo.length === size) {\n results.push([...combo]);\n return;\n }\n for (let i = start; i < attributes.length; i++) {\n combo.push(attributes[i]);\n helper(i + 1, combo);\n combo.pop();\n }\n }\n helper(0, []);\n return results;\n }\n function isXPathFirstResultElement(xpath, target) {\n try {\n const result = document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n return result.snapshotItem(0) === target;\n } catch (error) {\n console.warn(`Invalid XPath expression: ${xpath}`, error);\n return false;\n }\n }\n function escapeXPathString(value) {\n if (value.includes("\'")) {\n if (value.includes(\'"\')) {\n return "concat(" + value.split(/(\'+)/).map((part) => {\n if (part === "\'") {\n return `"\'"`;\n } else if (part.startsWith("\'") && part.endsWith("\'")) {\n return `"${part}"`;\n } else {\n return `\'${part}\'`;\n }\n }).join(",") + ")";\n } else {\n return `"${value}"`;\n }\n } else {\n return `\'${value}\'`;\n }\n }\n async function generateXPathsForElement(element) {\n if (!element) return [];\n const [complexXPath, standardXPath, idBasedXPath] = await Promise.all([\n generateComplexXPath(element),\n generateStandardXPath(element),\n generatedIdBasedXPath(element)\n ]);\n return [standardXPath, ...idBasedXPath ? [idBasedXPath] : [], complexXPath];\n }\n async function generateComplexXPath(element) {\n const parts = [];\n let currentElement = element;\n while (currentElement && (isTextNode(currentElement) || isElementNode(currentElement))) {\n if (isElementNode(currentElement)) {\n const el = currentElement;\n let selector = el.tagName.toLowerCase();\n const attributePriority = [\n "data-qa",\n "data-component",\n "data-role",\n "role",\n "aria-role",\n "type",\n "name",\n "aria-label",\n "placeholder",\n "title",\n "alt"\n ];\n const attributes = attributePriority.map((attr) => {\n let value = el.getAttribute(attr);\n if (attr === "href-full" && value) {\n value = el.getAttribute("href");\n }\n return value ? { attr: attr === "href-full" ? "href" : attr, value } : null;\n }).filter((attr) => attr !== null);\n let uniqueSelector = "";\n for (let i = 1; i <= attributes.length; i++) {\n const combinations = getCombinations(attributes, i);\n for (const combo of combinations) {\n const conditions = combo.map((a) => `@${a.attr}=${escapeXPathString(a.value)}`).join(" and ");\n const xpath2 = `//${selector}[${conditions}]`;\n if (isXPathFirstResultElement(xpath2, el)) {\n uniqueSelector = xpath2;\n break;\n }\n }\n if (uniqueSelector) break;\n }\n if (uniqueSelector) {\n parts.unshift(uniqueSelector.replace("//", ""));\n break;\n } else {\n const parent = getParentElement(el);\n if (parent) {\n const siblings = Array.from(parent.children).filter(\n (sibling) => sibling.tagName === el.tagName\n );\n const index = siblings.indexOf(el) + 1;\n selector += siblings.length > 1 ? `[${index}]` : "";\n }\n parts.unshift(selector);\n }\n }\n currentElement = getParentElement(currentElement);\n }\n const xpath = "//" + parts.join("/");\n return xpath;\n }\n async function generateStandardXPath(element) {\n const parts = [];\n while (element && (isTextNode(element) || isElementNode(element))) {\n let index = 0;\n let hasSameTypeSiblings = false;\n const siblings = element.parentElement ? Array.from(element.parentElement.childNodes) : [];\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.nodeType === element.nodeType && sibling.nodeName === element.nodeName) {\n index = index + 1;\n hasSameTypeSiblings = true;\n if (sibling.isSameNode(element)) {\n break;\n }\n }\n }\n if (element.nodeName !== "#text") {\n const tagName = element.nodeName.toLowerCase();\n const pathIndex = hasSameTypeSiblings ? `[${index}]` : "";\n parts.unshift(`${tagName}${pathIndex}`);\n }\n element = element.parentElement;\n }\n return parts.length ? `/${parts.join("/")}` : "";\n }\n async function generatedIdBasedXPath(element) {\n if (isElementNode(element) && element.id) {\n return `//*[@id=\'${element.id}\']`;\n }\n return null;\n }\n\n // types/stagehandErrors.ts\n var StagehandError = class extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n };\n var StagehandDomProcessError = class extends StagehandError {\n constructor(message) {\n super(`Error Processing Dom: ${message}`);\n }\n };\n\n // lib/dom/utils.ts\n function canElementScroll(elem) {\n if (typeof elem.scrollTo !== "function") {\n console.warn("canElementScroll: .scrollTo is not a function.");\n return false;\n }\n try {\n const originalTop = elem.scrollTop;\n elem.scrollTo({\n top: originalTop + 100,\n left: 0,\n behavior: "instant"\n });\n if (elem.scrollTop === originalTop) {\n throw new StagehandDomProcessError("scrollTop did not change");\n }\n elem.scrollTo({\n top: originalTop,\n left: 0,\n behavior: "instant"\n });\n return true;\n } catch (error) {\n console.warn("canElementScroll error:", error.message || error);\n return false;\n }\n }\n function getNodeFromXpath(xpath) {\n return document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null\n ).singleNodeValue;\n }\n function waitForElementScrollEnd(element, idleMs = 100) {\n return new Promise((resolve) => {\n let scrollEndTimer;\n const handleScroll = () => {\n clearTimeout(scrollEndTimer);\n scrollEndTimer = window.setTimeout(() => {\n element.removeEventListener("scroll", handleScroll);\n resolve();\n }, idleMs);\n };\n element.addEventListener("scroll", handleScroll, { passive: true });\n handleScroll();\n });\n }\n\n // lib/dom/process.ts\n function getScrollableElements(topN) {\n const docEl = document.documentElement;\n const scrollableElements = [docEl];\n const allElements = document.querySelectorAll("*");\n for (const elem of allElements) {\n const style = window.getComputedStyle(elem);\n const overflowY = style.overflowY;\n const isPotentiallyScrollable = overflowY === "auto" || overflowY === "scroll" || overflowY === "overlay";\n if (isPotentiallyScrollable) {\n const candidateScrollDiff = elem.scrollHeight - elem.clientHeight;\n if (candidateScrollDiff > 0 && canElementScroll(elem)) {\n scrollableElements.push(elem);\n }\n }\n }\n scrollableElements.sort((a, b) => b.scrollHeight - a.scrollHeight);\n if (topN !== void 0) {\n return scrollableElements.slice(0, topN);\n }\n return scrollableElements;\n }\n async function getScrollableElementXpaths(topN) {\n const scrollableElems = getScrollableElements(topN);\n const xpaths = [];\n for (const elem of scrollableElems) {\n const allXPaths = await generateXPathsForElement(elem);\n const firstXPath = allXPaths?.[0] || "";\n xpaths.push(firstXPath);\n }\n return xpaths;\n }\n (() => {\n const closedRoots = /* @__PURE__ */ new WeakMap();\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function(init) {\n const root = nativeAttachShadow.call(this, init);\n if (init.mode === "closed") closedRoots.set(this, root);\n return root;\n };\n const backdoor = {\n getClosedRoot: (host) => closedRoots.get(host),\n queryClosed: (host, selector) => {\n const root = closedRoots.get(host);\n return root ? Array.from(root.querySelectorAll(selector)) : [];\n },\n xpathClosed: (host, xp) => {\n const root = closedRoots.get(host);\n if (!root) return [];\n const it = document.evaluate(\n xp,\n root,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n const out = [];\n for (let i = 0; i < it.snapshotLength; ++i) {\n const n = it.snapshotItem(i);\n if (n) out.push(n);\n }\n return out;\n }\n };\n if (!("__stagehand__" in window)) {\n Object.defineProperty(window, "__stagehand__", {\n value: backdoor,\n enumerable: false,\n writable: false,\n configurable: false\n });\n }\n })();\n window.getScrollableElementXpaths = getScrollableElementXpaths;\n window.getNodeFromXpath = getNodeFromXpath;\n window.waitForElementScrollEnd = waitForElementScrollEnd;\n})();\n'; + +// lib/StagehandPage.ts +function getCurrentRootFrameId(session) { + return __async(this, null, function* () { + const { frameTree } = yield session.send( + "Page.getFrameTree" + ); + return frameTree.frame.id; + }); +} +var StagehandPage = class _StagehandPage { + constructor(page, stagehand, context, llmClient, userProvidedInstructions, api, waitForCaptchaSolves) { + this.cdpClient = null; + this.initialized = false; + this.isClosed = false; + this.cdpClients = /* @__PURE__ */ new WeakMap(); + this.fidOrdinals = /* @__PURE__ */ new Map([ + [void 0, 0] + ]); + if (stagehand.experimental && api) { + throw new ExperimentalApiConflictError(); + } + this.rawPage = page; + this.intPage = new Proxy(page, { + get: (target, prop) => { + if (!this.initialized && (prop === "act" || prop === "extract" || prop === "observe" || prop === "on")) { + return () => { + throw new StagehandNotInitializedError(String(prop)); + }; + } + const value = target[prop]; + if (typeof value === "function" && prop !== "on") { + return (...args) => value.apply(target, args); + } + return value; + } + }); + this.stagehand = stagehand; + this.intContext = context; + this.llmClient = llmClient; + this.api = api; + this.userProvidedInstructions = userProvidedInstructions; + this.waitForCaptchaSolves = waitForCaptchaSolves != null ? waitForCaptchaSolves : false; + if (this.llmClient) { + this.actHandler = new StagehandActHandler({ + logger: this.stagehand.logger, + stagehandPage: this, + selfHeal: this.stagehand.selfHeal, + experimental: this.stagehand.experimental + }); + this.extractHandler = new StagehandExtractHandler({ + stagehand: this.stagehand, + logger: this.stagehand.logger, + stagehandPage: this, + userProvidedInstructions, + experimental: this.stagehand.experimental + }); + this.observeHandler = new StagehandObserveHandler({ + stagehand: this.stagehand, + logger: this.stagehand.logger, + stagehandPage: this, + userProvidedInstructions, + experimental: this.stagehand.experimental + }); + } + } + get frameId() { + return this.rootFrameId; + } + updateRootFrameId(newId) { + this.rootFrameId = newId; + } + ordinalForFrameId(fid) { + if (fid === void 0) return 0; + const cached = this.fidOrdinals.get(fid); + if (cached !== void 0) return cached; + const next = this.fidOrdinals.size; + this.fidOrdinals.set(fid, next); + return next; + } + encodeWithFrameId(fid, backendId) { + return `${this.ordinalForFrameId(fid)}-${backendId}`; + } + resetFrameOrdinals() { + this.fidOrdinals = /* @__PURE__ */ new Map([[void 0, 0]]); + } + ensureStagehandScript() { + return __async(this, null, function* () { + try { + const injected = yield this.rawPage.evaluate( + () => !!window.__stagehandInjected + ); + if (injected) return; + const guardedScript = `if (!window.__stagehandInjected) { window.__stagehandInjected = true; ${scriptContent} }`; + yield this.rawPage.addInitScript({ content: guardedScript }); + yield this.rawPage.evaluate(guardedScript); + } catch (err) { + if (!this.stagehand.isClosed) { + this.stagehand.log({ + category: "dom", + message: "Failed to inject Stagehand helper script", + level: 1, + auxiliary: { + error: { value: err.message, type: "string" }, + trace: { value: err.stack, type: "string" } + } + }); + throw err; + } + } + }); + } + /** Register the custom selector engine that pierces open/closed shadow roots. */ + // private async ensureStagehandSelectorEngine(): Promise { + // if (stagehandSelectorRegistered) return; + // stagehandSelectorRegistered = true; + // await selectors.register("stagehand", () => { + // type Backdoor = { + // getClosedRoot?: (host: Element) => ShadowRoot | undefined; + // }; + // function parseSelector(input: string): { name: string; value: string } { + // // Accept either: "abc123" → uses DEFAULT_ATTR + // // or explicitly: "data-__stagehand-id=abc123" + // const raw = input.trim(); + // const eq = raw.indexOf("="); + // if (eq === -1) { + // return { + // name: "data-__stagehand-id", + // value: raw.replace(/^["']|["']$/g, ""), + // }; + // } + // const name = raw.slice(0, eq).trim(); + // const value = raw + // .slice(eq + 1) + // .trim() + // .replace(/^["']|["']$/g, ""); + // return { name, value }; + // } + // function pushChildren(node: Node, stack: Node[]): void { + // if (node.nodeType === Node.DOCUMENT_NODE) { + // const de = (node as Document).documentElement; + // if (de) stack.push(de); + // return; + // } + // if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + // const frag = node as DocumentFragment; + // const hc = frag.children as HTMLCollection | undefined; + // if (hc && hc.length) { + // for (let i = hc.length - 1; i >= 0; i--) + // stack.push(hc[i] as Element); + // } else { + // const cn = frag.childNodes; + // for (let i = cn.length - 1; i >= 0; i--) stack.push(cn[i]); + // } + // return; + // } + // if (node.nodeType === Node.ELEMENT_NODE) { + // const el = node as Element; + // for (let i = el.children.length - 1; i >= 0; i--) + // stack.push(el.children[i]); + // } + // } + // function* traverseAllTrees( + // start: Node, + // ): Generator { + // const backdoor = window.__stagehand__ as Backdoor | undefined; + // const stack: Node[] = []; + // if (start.nodeType === Node.DOCUMENT_NODE) { + // const de = (start as Document).documentElement; + // if (de) stack.push(de); + // } else { + // stack.push(start); + // } + // while (stack.length) { + // const node = stack.pop()!; + // if (node.nodeType === Node.ELEMENT_NODE) { + // const el = node as Element; + // yield el; + // // open shadow + // const open = el.shadowRoot as ShadowRoot | null; + // if (open) stack.push(open); + // // closed shadow via backdoor + // const closed = backdoor?.getClosedRoot?.(el); + // if (closed) stack.push(closed); + // } + // pushChildren(node, stack); + // } + // } + // return { + // query(root: Node, selector: string): Element | null { + // const { name, value } = parseSelector(selector); + // for (const el of traverseAllTrees(root)) { + // if (el.getAttribute(name) === value) return el; + // } + // return null; + // }, + // queryAll(root: Node, selector: string): Element[] { + // const { name, value } = parseSelector(selector); + // const out: Element[] = []; + // for (const el of traverseAllTrees(root)) { + // if (el.getAttribute(name) === value) out.push(el); + // } + // return out; + // }, + // }; + // }); + // } + /** + * Waits for a captcha to be solved when using Browserbase environment. + * + * @param timeoutMs - Optional timeout in milliseconds. If provided, the promise will reject if the captcha solving hasn't started within the given time. + * @throws StagehandEnvironmentError if called in a LOCAL environment + * @throws CaptchaTimeoutError if the timeout is reached before captcha solving starts + * @returns Promise that resolves when the captcha is solved + */ + waitForCaptchaSolve(timeoutMs) { + return __async(this, null, function* () { + if (this.stagehand.env === "LOCAL") { + throw new StagehandEnvironmentError( + this.stagehand.env, + "BROWSERBASE", + "waitForCaptcha method" + ); + } + this.stagehand.log({ + category: "captcha", + message: "Waiting for captcha", + level: 1 + }); + return new Promise((resolve2, reject) => { + let started = false; + let timeoutId; + if (timeoutMs) { + timeoutId = setTimeout(() => { + if (!started) { + reject(new CaptchaTimeoutError()); + } + }, timeoutMs); + } + this.intPage.on("console", (msg) => { + if (msg.text() === "browserbase-solving-finished") { + this.stagehand.log({ + category: "captcha", + message: "Captcha solving finished", + level: 1 + }); + if (timeoutId) clearTimeout(timeoutId); + resolve2(); + } else if (msg.text() === "browserbase-solving-started") { + started = true; + this.stagehand.log({ + category: "captcha", + message: "Captcha solving started", + level: 1 + }); + } + }); + }); + }); + } + init() { + return __async(this, null, function* () { + try { + const page = this.rawPage; + const stagehand = this.stagehand; + const handler = { + get: (target, prop) => { + const value = target[prop]; + if (prop === "evaluate" || prop === "evaluateHandle" || prop === "$eval" || prop === "$$eval") { + return (...args) => __async(this, null, function* () { + yield this.ensureStagehandScript(); + return value.apply( + target, + args + ); + }); + } + if (prop === "act" || prop === "extract" || prop === "observe") { + if (!this.llmClient) { + return () => { + throw new MissingLLMConfigurationError(); + }; + } + const method = this[prop]; + return (options) => method.call(this, options); + } + if (prop === "screenshot" && this.stagehand.env === "BROWSERBASE") { + return (..._0) => __async(this, [..._0], function* (options = {}) { + const cdpOptions = { + format: options.type === "jpeg" ? "jpeg" : "png", + quality: options.quality, + clip: options.clip, + omitBackground: options.omitBackground, + fromSurface: true + }; + if (options.fullPage) { + cdpOptions.captureBeyondViewport = true; + } + const data = yield this.sendCDP( + "Page.captureScreenshot", + cdpOptions + ); + const buffer = Buffer.from(data.data, "base64"); + return buffer; + }); + } + if (prop === "goto") { + const rawGoto = Object.getPrototypeOf(target).goto.bind(target); + return (url, options) => __async(this, null, function* () { + try { + const result = this.api ? yield this.api.goto(url, __spreadProps(__spreadValues({}, options), { + frameId: this.rootFrameId + })) : yield rawGoto(url, options); + this.stagehand.addToHistory( + "navigate", + { url, options }, + result + ); + if (this.waitForCaptchaSolves) { + try { + yield this.waitForCaptchaSolve(1e3); + } catch (e) { + } + } + if (this.stagehand.debugDom) { + this.stagehand.log({ + category: "deprecation", + message: "Warning: debugDom is not supported in this version of Stagehand", + level: 1 + }); + } + yield target.waitForLoadState("domcontentloaded"); + yield this._waitForSettledDom(); + return result; + } catch (error) { + this.stagehand.log({ + category: "navigation", + message: `Failed to navigate to ${url}`, + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + url: { + value: url, + type: "string" + } + } + }); + throw error; + } + }); + } + if (prop === "on") { + return (event, listener) => { + if (event === "popup") { + return this.context.on("page", (page2) => __async(this, null, function* () { + const newContext = yield StagehandContext.init( + page2.context(), + stagehand + ); + const newStagehandPage = new _StagehandPage( + page2, + stagehand, + newContext, + this.llmClient + ); + yield newStagehandPage.init(); + listener(newStagehandPage.page); + })); + } + this.intContext.setActivePage(this); + return target.on(event, listener); + }; + } + if (typeof value === "function") { + return (...args) => value.apply(target, args); + } + return value; + } + }; + const session = yield this.getCDPClient(this.rawPage); + yield session.send("Page.enable"); + const rootId = yield getCurrentRootFrameId(session); + this.updateRootFrameId(rootId); + this.intContext.registerFrameId(rootId, this); + this.intPage = new Proxy(page, handler); + this.initialized = true; + return this; + } catch (err) { + this.stagehand.log({ + category: "init", + message: `Error initializing stagehand page: ${err}`, + level: 0 + }); + throw err; + } + }); + } + get page() { + return this.intPage; + } + get context() { + return this.intContext.context; + } + /** + * `_waitForSettledDom` waits until the DOM is settled, and therefore is + * ready for actions to be taken. + * + * **Definition of "settled"** + * • No in-flight network requests (except WebSocket / Server-Sent-Events). + * • That idle state lasts for at least **500 ms** (the "quiet-window"). + * + * **How it works** + * 1. Subscribes to CDP Network and Page events for the main target and all + * out-of-process iframes (via `Target.setAutoAttach { flatten:true }`). + * 2. Every time `Network.requestWillBeSent` fires, the request ID is added + * to an **`inflight`** `Set`. + * 3. When the request finishes—`loadingFinished`, `loadingFailed`, + * `requestServedFromCache`, or a *data:* response—the request ID is + * removed. + * 4. *Document* requests are also mapped **frameId → requestId**; when + * `Page.frameStoppedLoading` fires the corresponding Document request is + * removed immediately (covers iframes whose network events never close). + * 5. A **stalled-request sweep timer** runs every 500 ms. If a *Document* + * request has been open for ≥ 2 s it is forcibly removed; this prevents + * ad/analytics iframes from blocking the wait forever. + * 6. When `inflight` becomes empty the helper starts a 500 ms timer. + * If no new request appears before the timer fires, the promise + * resolves → **DOM is considered settled**. + * 7. A global guard (`timeoutMs` or `stagehand.domSettleTimeoutMs`, + * default ≈ 30 s) ensures we always resolve; if it fires we log how many + * requests were still outstanding. + * + * @param timeoutMs – Optional hard cap (ms). Defaults to + * `this.stagehand.domSettleTimeoutMs`. + */ + _waitForSettledDom(timeoutMs) { + return __async(this, null, function* () { + const timeout = timeoutMs != null ? timeoutMs : this.stagehand.domSettleTimeoutMs; + const client = yield this.getCDPClient(); + const hasDoc = !!(yield this.page.title().catch(() => false)); + if (!hasDoc) yield this.page.waitForLoadState("domcontentloaded"); + yield client.send("Network.enable"); + yield client.send("Page.enable"); + yield client.send("Target.setAutoAttach", { + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, + filter: [ + { type: "worker", exclude: true }, + { type: "shared_worker", exclude: true } + ] + }); + return new Promise((resolve2) => { + const inflight = /* @__PURE__ */ new Set(); + const meta = /* @__PURE__ */ new Map(); + const docByFrame = /* @__PURE__ */ new Map(); + let quietTimer = null; + let stalledRequestSweepTimer = null; + const clearQuiet = () => { + if (quietTimer) { + clearTimeout(quietTimer); + quietTimer = null; + } + }; + const maybeQuiet = () => { + if (inflight.size === 0 && !quietTimer) + quietTimer = setTimeout(() => resolveDone(), 500); + }; + const finishReq = (id) => { + if (!inflight.delete(id)) return; + meta.delete(id); + for (const [fid, rid] of docByFrame) + if (rid === id) docByFrame.delete(fid); + clearQuiet(); + maybeQuiet(); + }; + const onRequest = (p) => { + if (p.type === "WebSocket" || p.type === "EventSource") return; + inflight.add(p.requestId); + meta.set(p.requestId, { url: p.request.url, start: Date.now() }); + if (p.type === "Document" && p.frameId) + docByFrame.set(p.frameId, p.requestId); + clearQuiet(); + }; + const onFinish = (p) => finishReq(p.requestId); + const onCached = (p) => finishReq(p.requestId); + const onDataUrl = (p) => p.response.url.startsWith("data:") && finishReq(p.requestId); + const onFrameStop = (f) => { + const id = docByFrame.get(f.frameId); + if (id) finishReq(id); + }; + client.on("Network.requestWillBeSent", onRequest); + client.on("Network.loadingFinished", onFinish); + client.on("Network.loadingFailed", onFinish); + client.on("Network.requestServedFromCache", onCached); + client.on("Network.responseReceived", onDataUrl); + client.on("Page.frameStoppedLoading", onFrameStop); + stalledRequestSweepTimer = setInterval(() => { + const now = Date.now(); + for (const [id, m] of meta) { + if (now - m.start > 2e3) { + inflight.delete(id); + meta.delete(id); + this.stagehand.log({ + category: "dom", + message: "\u23F3 forcing completion of stalled iframe document", + level: 2, + auxiliary: { + url: { + value: m.url.slice(0, 120), + type: "string" + } + } + }); + } + } + maybeQuiet(); + }, 500); + maybeQuiet(); + const guard = setTimeout(() => { + if (inflight.size) + this.stagehand.log({ + category: "dom", + message: "\u26A0\uFE0F DOM-settle timeout reached \u2013 network requests still pending", + level: 2, + auxiliary: { + count: { + value: inflight.size.toString(), + type: "integer" + } + } + }); + resolveDone(); + }, timeout); + const resolveDone = () => { + client.off("Network.requestWillBeSent", onRequest); + client.off("Network.loadingFinished", onFinish); + client.off("Network.loadingFailed", onFinish); + client.off("Network.requestServedFromCache", onCached); + client.off("Network.responseReceived", onDataUrl); + client.off("Page.frameStoppedLoading", onFrameStop); + if (quietTimer) clearTimeout(quietTimer); + if (stalledRequestSweepTimer) clearInterval(stalledRequestSweepTimer); + clearTimeout(guard); + resolve2(); + }; + }); + }); + } + act(actionOrOptions) { + return __async(this, null, function* () { + try { + if (!this.actHandler) { + throw new HandlerNotInitializedError("Act"); + } + yield clearOverlays(this.page); + if (typeof actionOrOptions === "object" && actionOrOptions !== null) { + if ("selector" in actionOrOptions && "method" in actionOrOptions) { + const observeResult = actionOrOptions; + if (this.api) { + const result2 = yield this.api.act(__spreadProps(__spreadValues({}, observeResult), { + frameId: this.rootFrameId + })); + this.stagehand.addToHistory("act", observeResult, result2); + return result2; + } + return this.actHandler.actFromObserveResult(observeResult); + } else { + if (!("action" in actionOrOptions)) { + throw new StagehandError( + "Invalid argument. Valid arguments are: a string, an ActOptions object, or an ObserveResult WITH 'selector' and 'method' fields." + ); + } + } + } else if (typeof actionOrOptions === "string") { + actionOrOptions = { action: actionOrOptions }; + } else { + throw new StagehandError( + "Invalid argument: you may have called act with an empty ObserveResult.\nValid arguments are: a string, an ActOptions object, or an ObserveResult WITH 'selector' and 'method' fields." + ); + } + const { action, modelName, modelClientOptions } = actionOrOptions; + if (this.api) { + const opts = __spreadProps(__spreadValues({}, actionOrOptions), { frameId: this.rootFrameId }); + const result2 = yield this.api.act(opts); + this.stagehand.addToHistory("act", actionOrOptions, result2); + return result2; + } + const requestId = Math.random().toString(36).substring(2); + const llmClient = modelName ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) : this.llmClient; + this.stagehand.log({ + category: "act", + message: "running act", + level: 1, + auxiliary: { + action: { + value: action, + type: "string" + }, + requestId: { + value: requestId, + type: "string" + }, + modelName: { + value: llmClient.modelName, + type: "string" + } + } + }); + const result = yield this.actHandler.observeAct( + actionOrOptions, + this.observeHandler, + llmClient, + requestId + ); + this.stagehand.addToHistory("act", actionOrOptions, result); + return result; + } catch (err) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + }); + } + extract(instructionOrOptions) { + return __async(this, null, function* () { + try { + if (!this.extractHandler) { + throw new HandlerNotInitializedError("Extract"); + } + yield clearOverlays(this.page); + if (!instructionOrOptions) { + let result2; + if (this.api) { + result2 = yield this.api.extract({ frameId: this.rootFrameId }); + } else { + result2 = yield this.extractHandler.extract(); + } + this.stagehand.addToHistory("extract", instructionOrOptions, result2); + return result2; + } + const options = typeof instructionOrOptions === "string" ? { + instruction: instructionOrOptions, + schema: defaultExtractSchema + } : instructionOrOptions.schema ? instructionOrOptions : __spreadProps(__spreadValues({}, instructionOrOptions), { + schema: defaultExtractSchema + }); + const { + instruction, + schema, + modelName, + modelClientOptions, + domSettleTimeoutMs, + useTextExtract, + selector, + iframes + } = options; + if (this.api) { + const opts = __spreadProps(__spreadValues({}, options), { frameId: this.rootFrameId }); + const result2 = yield this.api.extract(opts); + this.stagehand.addToHistory("extract", instructionOrOptions, result2); + return result2; + } + const requestId = Math.random().toString(36).substring(2); + const llmClient = modelName ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) : this.llmClient; + this.stagehand.log({ + category: "extract", + message: "running extract", + level: 1, + auxiliary: { + instruction: { + value: instruction, + type: "string" + }, + requestId: { + value: requestId, + type: "string" + }, + modelName: { + value: llmClient.modelName, + type: "string" + } + } + }); + const result = yield this.extractHandler.extract({ + instruction, + schema, + llmClient, + requestId, + domSettleTimeoutMs, + useTextExtract, + selector, + iframes + }).catch((e) => { + this.stagehand.log({ + category: "extract", + message: "error extracting", + level: 1, + auxiliary: { + error: { + value: e.message, + type: "string" + }, + trace: { + value: e.stack, + type: "string" + } + } + }); + if (this.stagehand.enableCaching) { + this.stagehand.llmProvider.cleanRequestCache(requestId); + } + throw e; + }); + this.stagehand.addToHistory("extract", instructionOrOptions, result); + return result; + } catch (err) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + }); + } + observe(instructionOrOptions) { + return __async(this, null, function* () { + try { + if (!this.observeHandler) { + throw new HandlerNotInitializedError("Observe"); + } + yield clearOverlays(this.page); + const options = typeof instructionOrOptions === "string" ? { instruction: instructionOrOptions } : instructionOrOptions || {}; + const { + instruction, + modelName, + modelClientOptions, + domSettleTimeoutMs, + returnAction = true, + onlyVisible, + drawOverlay, + iframes + } = options; + if (this.api) { + const opts = __spreadProps(__spreadValues({}, options), { frameId: this.rootFrameId }); + const result2 = yield this.api.observe(opts); + this.stagehand.addToHistory("observe", instructionOrOptions, result2); + return result2; + } + const requestId = Math.random().toString(36).substring(2); + const llmClient = modelName ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) : this.llmClient; + this.stagehand.log({ + category: "observe", + message: "running observe", + level: 1, + auxiliary: __spreadValues({ + instruction: { + value: instruction, + type: "string" + }, + requestId: { + value: requestId, + type: "string" + }, + modelName: { + value: llmClient.modelName, + type: "string" + } + }, onlyVisible !== void 0 && { + onlyVisible: { + value: onlyVisible ? "true" : "false", + type: "boolean" + } + }) + }); + const result = yield this.observeHandler.observe({ + instruction, + llmClient, + requestId, + domSettleTimeoutMs, + returnAction, + onlyVisible, + drawOverlay, + iframes + }).catch((e) => { + this.stagehand.log({ + category: "observe", + message: "error observing", + level: 1, + auxiliary: { + error: { + value: e.message, + type: "string" + }, + trace: { + value: e.stack, + type: "string" + }, + requestId: { + value: requestId, + type: "string" + }, + instruction: { + value: instruction, + type: "string" + } + } + }); + if (this.stagehand.enableCaching) { + this.stagehand.llmProvider.cleanRequestCache(requestId); + } + throw e; + }); + this.stagehand.addToHistory("observe", instructionOrOptions, result); + return result; + } catch (err) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + }); + } + /** + * Get or create a CDP session for the given target. + * @param target The Page or (OOPIF) Frame you want to talk to. + */ + getCDPClient() { + return __async(this, arguments, function* (target = this.page) { + var _a15; + if (this.isClosed) { + throw new Error("Cannot create CDP session: page is closed"); + } + const cached = this.cdpClients.get(target); + if (cached) return cached; + try { + if (!target || target._closed) { + throw new Error("Target page or frame is closed"); + } + const session = yield this.context.newCDPSession(target); + this.cdpClients.set(target, session); + return session; + } catch (err) { + const msg = (_a15 = err.message) != null ? _a15 : ""; + if (msg.includes("No target with given id found") || msg.includes("Target page, context or browser has been closed") || msg.includes("Protocol error")) { + this.isClosed = true; + throw new Error(`CDP session creation failed: ${msg}`); + } + if (msg.includes("does not have a separate CDP session")) { + const rootSession = yield this.getCDPClient(this.page); + this.cdpClients.set(target, rootSession); + return rootSession; + } + throw err; + } + }); + } + /** + * Send a CDP command to the chosen DevTools target. + * + * @param method Any valid CDP method, e.g. `"DOM.getDocument"`. + * @param params Command parameters (optional). + * @param target A `Page` or OOPIF `Frame`. Defaults to the main page. + * + * @typeParam T Expected result shape (defaults to `unknown`). + */ + sendCDP(_0) { + return __async(this, arguments, function* (method, params = {}, target) { + var _a15; + try { + const client = yield this.getCDPClient(target != null ? target : this.page); + return client.send( + method, + params + ); + } catch (err) { + const msg = (_a15 = err.message) != null ? _a15 : ""; + if (msg.includes("CDP session creation failed") || msg.includes("page is closed")) { + throw new Error(`CDP command failed: ${method} - ${msg}`); + } + throw err; + } + }); + } + /** Enable a CDP domain (e.g. `"Network"` or `"DOM"`) on the chosen target. */ + enableCDP(domain, target) { + return __async(this, null, function* () { + yield this.sendCDP(`${domain}.enable`, {}, target); + }); + } + /** Disable a CDP domain on the chosen target. */ + disableCDP(domain, target) { + return __async(this, null, function* () { + yield this.sendCDP(`${domain}.disable`, {}, target); + }); + } +}; + +// lib/StagehandContext.ts +var StagehandContext = class _StagehandContext { + constructor(context, stagehand) { + this.activeStagehandPage = null; + this.frameIdMap = /* @__PURE__ */ new Map(); + this.stagehand = stagehand; + this.pageMap = /* @__PURE__ */ new WeakMap(); + this.intContext = new Proxy(context, { + get: (target, prop) => { + if (prop === "newPage") { + return () => __async(this, null, function* () { + const pwPage = yield target.newPage(); + const stagehandPage = yield this.createStagehandPage(pwPage); + yield this.attachFrameNavigatedListener(pwPage); + this.setActivePage(stagehandPage); + return stagehandPage.page; + }); + } + if (prop === "pages") { + return () => { + const pwPages = target.pages(); + return pwPages.map((pwPage) => { + let stagehandPage = this.pageMap.get(pwPage); + if (!stagehandPage) { + stagehandPage = new StagehandPage( + pwPage, + this.stagehand, + this, + this.stagehand.llmClient, + this.stagehand.userProvidedInstructions, + this.stagehand.apiClient, + this.stagehand.waitForCaptchaSolves + ); + this.pageMap.set(pwPage, stagehandPage); + } + return stagehandPage.page; + }); + }; + } + return target[prop]; + } + }); + } + createStagehandPage(page) { + return __async(this, null, function* () { + const stagehandPage = yield new StagehandPage( + page, + this.stagehand, + this, + this.stagehand.llmClient, + this.stagehand.userProvidedInstructions, + this.stagehand.apiClient, + this.stagehand.waitForCaptchaSolves + ).init(); + this.pageMap.set(page, stagehandPage); + return stagehandPage; + }); + } + static init(context, stagehand) { + return __async(this, null, function* () { + const instance = new _StagehandContext(context, stagehand); + context.on("page", (pwPage) => __async(null, null, function* () { + yield instance.handleNewPlaywrightPage(pwPage); + instance.attachFrameNavigatedListener(pwPage).catch( + (err) => stagehand.logger({ + category: "cdp", + message: `Failed to attach frameNavigated listener: ${err}`, + level: 0 + }) + ).finally( + () => instance.handleNewPlaywrightPage(pwPage).catch( + (err) => stagehand.logger({ + category: "context", + message: `Failed to initialise new page: ${err}`, + level: 0 + }) + ) + ); + })); + const existingPages = context.pages(); + for (const page of existingPages) { + const stagehandPage = yield instance.createStagehandPage(page); + yield instance.attachFrameNavigatedListener(page); + if (!instance.activeStagehandPage) { + instance.setActivePage(stagehandPage); + } + } + return instance; + }); + } + get frameIdLookup() { + return this.frameIdMap; + } + registerFrameId(frameId, page) { + this.frameIdMap.set(frameId, page); + } + unregisterFrameId(frameId) { + this.frameIdMap.delete(frameId); + } + getStagehandPageByFrameId(frameId) { + return this.frameIdMap.get(frameId); + } + get context() { + return this.intContext; + } + getStagehandPage(page) { + return __async(this, null, function* () { + let stagehandPage = this.pageMap.get(page); + if (!stagehandPage) { + stagehandPage = yield this.createStagehandPage(page); + } + this.setActivePage(stagehandPage); + return stagehandPage; + }); + } + getStagehandPages() { + return __async(this, null, function* () { + const pwPages = this.intContext.pages(); + return Promise.all( + pwPages.map((page) => this.getStagehandPage(page)) + ); + }); + } + setActivePage(page) { + this.activeStagehandPage = page; + this.stagehand["setActivePage"](page); + } + getActivePage() { + return this.activeStagehandPage; + } + handleNewPlaywrightPage(pwPage) { + return __async(this, null, function* () { + let stagehandPage = this.pageMap.get(pwPage); + if (!stagehandPage) { + stagehandPage = yield this.createStagehandPage(pwPage); + } + this.setActivePage(stagehandPage); + }); + } + attachFrameNavigatedListener(pwPage) { + return __async(this, null, function* () { + const shPage = this.pageMap.get(pwPage); + if (!shPage) return; + try { + const session = yield this.intContext.newCDPSession(pwPage); + yield session.send("Page.enable"); + pwPage.once("close", () => { + if (shPage.frameId) this.unregisterFrameId(shPage.frameId); + }); + session.on( + "Page.frameNavigated", + (evt) => { + if (evt.frame.parentId) return; + if (evt.frame.id === shPage.frameId) return; + const oldId = shPage.frameId; + if (oldId) this.unregisterFrameId(oldId); + this.registerFrameId(evt.frame.id, shPage); + shPage.updateRootFrameId(evt.frame.id); + } + ); + } catch (error) { + this.stagehand.logger({ + category: "context", + message: `Failed to attach frameNavigated listener: ${error}`, + level: 0 + }); + } + }); + } +}; + +// lib/api.ts +var import_zod_to_json_schema = __toESM(require("zod-to-json-schema")); +var import_fetch_cookie = __toESM(require("fetch-cookie")); +var StagehandAPI = class { + constructor({ apiKey, projectId, logger }) { + this.apiKey = apiKey; + this.projectId = projectId; + this.logger = logger; + this.fetchWithCookies = (0, import_fetch_cookie.default)(fetch); + } + init(_0) { + return __async(this, arguments, function* ({ + modelName, + modelApiKey, + domSettleTimeoutMs, + verbose, + debugDom, + systemPrompt, + selfHeal, + waitForCaptchaSolves, + actionTimeoutMs, + browserbaseSessionCreateParams, + browserbaseSessionID + }) { + var _a15; + if (!modelApiKey) { + throw new StagehandAPIError("modelApiKey is required"); + } + this.modelApiKey = modelApiKey; + const region = browserbaseSessionCreateParams == null ? void 0 : browserbaseSessionCreateParams.region; + if (region && region !== "us-west-2") { + return { sessionId: browserbaseSessionID != null ? browserbaseSessionID : null, available: false }; + } + const sessionResponse = yield this.request("/sessions/start", { + method: "POST", + body: JSON.stringify({ + modelName, + domSettleTimeoutMs, + verbose, + debugDom, + systemPrompt, + selfHeal, + waitForCaptchaSolves, + actionTimeoutMs, + browserbaseSessionCreateParams, + browserbaseSessionID + }) + }); + if (sessionResponse.status === 401) { + throw new StagehandAPIUnauthorizedError( + "Unauthorized. Ensure you provided a valid API key and that it is whitelisted." + ); + } else if (sessionResponse.status !== 200) { + console.log(yield sessionResponse.text()); + throw new StagehandHttpError(`Unknown error: ${sessionResponse.status}`); + } + const sessionResponseBody = yield sessionResponse.json(); + if (sessionResponseBody.success === false) { + throw new StagehandAPIError(sessionResponseBody.message); + } + this.sessionId = sessionResponseBody.data.sessionId; + if (!((_a15 = sessionResponseBody.data) == null ? void 0 : _a15.available) && browserbaseSessionID) { + sessionResponseBody.data.sessionId = browserbaseSessionID; + } + return sessionResponseBody.data; + }); + } + act(options) { + return __async(this, null, function* () { + return this.execute({ + method: "act", + args: __spreadValues({}, options) + }); + }); + } + extract(options) { + return __async(this, null, function* () { + if (!options.schema) { + return this.execute({ + method: "extract", + args: __spreadValues({}, options) + }); + } + const parsedSchema = (0, import_zod_to_json_schema.default)(options.schema); + return this.execute({ + method: "extract", + args: __spreadProps(__spreadValues({}, options), { schemaDefinition: parsedSchema }) + }); + }); + } + observe(options) { + return __async(this, null, function* () { + return this.execute({ + method: "observe", + args: __spreadValues({}, options) + }); + }); + } + goto(url, options) { + return __async(this, null, function* () { + return this.execute({ + method: "navigate", + args: { url, options } + }); + }); + } + agentExecute(agentConfig, executeOptions) { + return __async(this, null, function* () { + return this.execute({ + method: "agentExecute", + args: { agentConfig, executeOptions } + }); + }); + } + end() { + return __async(this, null, function* () { + const url = `/sessions/${this.sessionId}/end`; + const response = yield this.request(url, { + method: "POST" + }); + return response; + }); + } + execute(_0) { + return __async(this, arguments, function* ({ + method, + args, + params + }) { + const urlParams = new URLSearchParams(params); + const queryString = urlParams.toString(); + const url = `/sessions/${this.sessionId}/${method}${queryString ? `?${queryString}` : ""}`; + const response = yield this.request(url, { + method: "POST", + body: JSON.stringify(args) + }); + if (!response.ok) { + const errorBody = yield response.text(); + throw new StagehandHttpError( + `HTTP error! status: ${response.status}, body: ${errorBody}` + ); + } + if (!response.body) { + throw new StagehandResponseBodyError(); + } + const reader = response.body.getReader(); + const decoder = new TextDecoder(); + let buffer = ""; + while (true) { + const { value, done } = yield reader.read(); + if (done && !buffer) { + return null; + } + buffer += decoder.decode(value, { stream: true }); + const lines = buffer.split("\n\n"); + buffer = lines.pop() || ""; + for (const line of lines) { + if (!line.startsWith("data: ")) continue; + try { + const eventData = JSON.parse(line.slice(6)); + if (eventData.type === "system") { + if (eventData.data.status === "error") { + throw new StagehandServerError(eventData.data.error); + } + if (eventData.data.status === "finished") { + return eventData.data.result; + } + } else if (eventData.type === "log") { + this.logger(eventData.data.message); + } + } catch (e) { + console.error("Error parsing event data:", e); + throw new StagehandResponseParseError( + "Failed to parse server response" + ); + } + } + if (done) break; + } + }); + } + request(_0) { + return __async(this, arguments, function* (path4, options = {}) { + var _a15; + const defaultHeaders = { + "x-bb-api-key": this.apiKey, + "x-bb-project-id": this.projectId, + "x-bb-session-id": this.sessionId, + // we want real-time logs, so we stream the response + "x-stream-response": "true", + "x-model-api-key": this.modelApiKey, + "x-sent-at": (/* @__PURE__ */ new Date()).toISOString(), + "x-language": "typescript", + "x-sdk-version": STAGEHAND_VERSION + }; + if (options.method === "POST" && options.body) { + defaultHeaders["Content-Type"] = "application/json"; + } + const response = yield this.fetchWithCookies( + `${(_a15 = process.env.STAGEHAND_API_URL) != null ? _a15 : "https://api.stagehand.browserbase.com/v1"}${path4}`, + __spreadProps(__spreadValues({}, options), { + headers: __spreadValues(__spreadValues({}, defaultHeaders), options.headers) + }) + ); + return response; + }); + } +}; + +// lib/cache/BaseCache.ts +var fs2 = __toESM(require("fs")); +var path2 = __toESM(require("path")); +var crypto = __toESM(require("crypto")); +var BaseCache = class { + constructor(logger, cacheDir = path2.join(process.cwd(), "tmp", ".cache"), cacheFile = "cache.json") { + this.CACHE_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1e3; + // 1 week in milliseconds + this.CLEANUP_PROBABILITY = 0.01; + this.LOCK_TIMEOUT_MS = 1e3; + this.lockAcquired = false; + this.lockAcquireFailures = 0; + // Added for request ID tracking + this.requestIdToUsedHashes = {}; + this.logger = logger; + this.cacheDir = cacheDir; + this.cacheFile = path2.join(cacheDir, cacheFile); + this.lockFile = path2.join(cacheDir, "cache.lock"); + this.ensureCacheDirectory(); + this.setupProcessHandlers(); + } + setupProcessHandlers() { + const releaseLockAndExit = () => { + this.releaseLock(); + process.exit(); + }; + process.on("exit", releaseLockAndExit); + process.on("SIGINT", releaseLockAndExit); + process.on("SIGTERM", releaseLockAndExit); + process.on("uncaughtException", (err) => { + this.logger({ + category: "base_cache", + message: "uncaught exception", + level: 2, + auxiliary: { + error: { + value: err.message, + type: "string" + }, + trace: { + value: err.stack, + type: "string" + } + } + }); + if (this.lockAcquired) { + releaseLockAndExit(); + } + }); + } + ensureCacheDirectory() { + if (!fs2.existsSync(this.cacheDir)) { + fs2.mkdirSync(this.cacheDir, { recursive: true }); + this.logger({ + category: "base_cache", + message: "created cache directory", + level: 1, + auxiliary: { + cacheDir: { + value: this.cacheDir, + type: "string" + } + } + }); + } + } + createHash(data) { + const hash = crypto.createHash("sha256"); + return hash.update(JSON.stringify(data)).digest("hex"); + } + sleep(ms) { + return new Promise((resolve2) => setTimeout(resolve2, ms)); + } + acquireLock() { + return __async(this, null, function* () { + const startTime = Date.now(); + while (Date.now() - startTime < this.LOCK_TIMEOUT_MS) { + try { + if (fs2.existsSync(this.lockFile)) { + const lockAge = Date.now() - fs2.statSync(this.lockFile).mtimeMs; + if (lockAge > this.LOCK_TIMEOUT_MS) { + fs2.unlinkSync(this.lockFile); + this.logger({ + category: "base_cache", + message: "Stale lock file removed", + level: 1 + }); + } + } + fs2.writeFileSync(this.lockFile, process.pid.toString(), { flag: "wx" }); + this.lockAcquireFailures = 0; + this.lockAcquired = true; + this.logger({ + category: "base_cache", + message: "Lock acquired", + level: 1 + }); + return true; + } catch (e) { + this.logger({ + category: "base_cache", + message: "error acquiring lock", + level: 2, + auxiliary: { + trace: { + value: e.stack, + type: "string" + }, + message: { + value: e.message, + type: "string" + } + } + }); + yield this.sleep(5); + } + } + this.logger({ + category: "base_cache", + message: "Failed to acquire lock after timeout", + level: 2 + }); + this.lockAcquireFailures++; + if (this.lockAcquireFailures >= 3) { + this.logger({ + category: "base_cache", + message: "Failed to acquire lock 3 times in a row. Releasing lock manually.", + level: 1 + }); + this.releaseLock(); + } + return false; + }); + } + releaseLock() { + try { + if (fs2.existsSync(this.lockFile)) { + fs2.unlinkSync(this.lockFile); + this.logger({ + category: "base_cache", + message: "Lock released", + level: 1 + }); + } + this.lockAcquired = false; + } catch (error) { + this.logger({ + category: "base_cache", + message: "error releasing lock", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + } + } + /** + * Cleans up stale cache entries that exceed the maximum age. + */ + cleanupStaleEntries() { + return __async(this, null, function* () { + if (!(yield this.acquireLock())) { + this.logger({ + category: "llm_cache", + message: "failed to acquire lock for cleanup", + level: 2 + }); + return; + } + try { + const cache = this.readCache(); + const now = Date.now(); + let entriesRemoved = 0; + for (const [hash, entry] of Object.entries(cache)) { + if (now - entry.timestamp > this.CACHE_MAX_AGE_MS) { + delete cache[hash]; + entriesRemoved++; + } + } + if (entriesRemoved > 0) { + this.writeCache(cache); + this.logger({ + category: "llm_cache", + message: "cleaned up stale cache entries", + level: 1, + auxiliary: { + entriesRemoved: { + value: entriesRemoved.toString(), + type: "integer" + } + } + }); + } + } catch (error) { + this.logger({ + category: "llm_cache", + message: "error during cache cleanup", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + } finally { + this.releaseLock(); + } + }); + } + readCache() { + if (fs2.existsSync(this.cacheFile)) { + try { + const data = fs2.readFileSync(this.cacheFile, "utf-8"); + return JSON.parse(data); + } catch (error) { + this.logger({ + category: "base_cache", + message: "error reading cache file. resetting cache.", + level: 1, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + this.resetCache(); + return {}; + } + } + return {}; + } + writeCache(cache) { + try { + fs2.writeFileSync(this.cacheFile, JSON.stringify(cache, null, 2)); + this.logger({ + category: "base_cache", + message: "Cache written to file", + level: 1 + }); + } catch (error) { + this.logger({ + category: "base_cache", + message: "error writing cache file", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + } finally { + this.releaseLock(); + } + } + /** + * Retrieves data from the cache based on the provided options. + * @param hashObj - The options used to generate the cache key. + * @param requestId - The identifier for the current request. + * @returns The cached data if available, otherwise null. + */ + get(hashObj, requestId) { + return __async(this, null, function* () { + if (!(yield this.acquireLock())) { + this.logger({ + category: "base_cache", + message: "Failed to acquire lock for getting cache", + level: 2 + }); + return null; + } + try { + const hash = this.createHash(hashObj); + const cache = this.readCache(); + if (cache[hash]) { + this.trackRequestIdUsage(requestId, hash); + return cache[hash].data; + } + return null; + } catch (error) { + this.logger({ + category: "base_cache", + message: "error getting cache. resetting cache.", + level: 1, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + this.resetCache(); + return null; + } finally { + this.releaseLock(); + } + }); + } + /** + * Stores data in the cache based on the provided options and requestId. + * @param hashObj - The options used to generate the cache key. + * @param data - The data to be cached. + * @param requestId - The identifier for the cache entry. + */ + set(hashObj, data, requestId) { + return __async(this, null, function* () { + if (!(yield this.acquireLock())) { + this.logger({ + category: "base_cache", + message: "Failed to acquire lock for setting cache", + level: 2 + }); + return; + } + try { + const hash = this.createHash(hashObj); + const cache = this.readCache(); + cache[hash] = { + data, + timestamp: Date.now(), + requestId + }; + this.writeCache(cache); + this.trackRequestIdUsage(requestId, hash); + } catch (error) { + this.logger({ + category: "base_cache", + message: "error setting cache. resetting cache.", + level: 1, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + this.resetCache(); + } finally { + this.releaseLock(); + if (Math.random() < this.CLEANUP_PROBABILITY) { + this.cleanupStaleEntries(); + } + } + }); + } + delete(hashObj) { + return __async(this, null, function* () { + if (!(yield this.acquireLock())) { + this.logger({ + category: "base_cache", + message: "Failed to acquire lock for removing cache entry", + level: 2 + }); + return; + } + try { + const hash = this.createHash(hashObj); + const cache = this.readCache(); + if (cache[hash]) { + delete cache[hash]; + this.writeCache(cache); + } else { + this.logger({ + category: "base_cache", + message: "Cache entry not found to delete", + level: 1 + }); + } + } catch (error) { + this.logger({ + category: "base_cache", + message: "error removing cache entry", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + } finally { + this.releaseLock(); + } + }); + } + /** + * Tracks the usage of a hash with a specific requestId. + * @param requestId - The identifier for the current request. + * @param hash - The cache key hash. + */ + trackRequestIdUsage(requestId, hash) { + var _a15, _b; + (_b = (_a15 = this.requestIdToUsedHashes)[requestId]) != null ? _b : _a15[requestId] = []; + this.requestIdToUsedHashes[requestId].push(hash); + } + /** + * Deletes all cache entries associated with a specific requestId. + * @param requestId - The identifier for the request whose cache entries should be deleted. + */ + deleteCacheForRequestId(requestId) { + return __async(this, null, function* () { + var _a15; + if (!(yield this.acquireLock())) { + this.logger({ + category: "base_cache", + message: "Failed to acquire lock for deleting cache", + level: 2 + }); + return; + } + try { + const cache = this.readCache(); + const hashes = (_a15 = this.requestIdToUsedHashes[requestId]) != null ? _a15 : []; + let entriesRemoved = 0; + for (const hash of hashes) { + if (cache[hash]) { + delete cache[hash]; + entriesRemoved++; + } + } + if (entriesRemoved > 0) { + this.writeCache(cache); + } else { + this.logger({ + category: "base_cache", + message: "no cache entries found for requestId", + level: 1, + auxiliary: { + requestId: { + value: requestId, + type: "string" + } + } + }); + } + delete this.requestIdToUsedHashes[requestId]; + } catch (error) { + this.logger({ + category: "base_cache", + message: "error deleting cache for requestId", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + }, + requestId: { + value: requestId, + type: "string" + } + } + }); + } finally { + this.releaseLock(); + } + }); + } + /** + * Resets the entire cache by clearing the cache file. + */ + resetCache() { + try { + fs2.writeFileSync(this.cacheFile, "{}"); + this.requestIdToUsedHashes = {}; + } catch (error) { + this.logger({ + category: "base_cache", + message: "error resetting cache", + level: 2, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + } finally { + this.releaseLock(); + } + } +}; + +// lib/cache/LLMCache.ts +var LLMCache = class _LLMCache extends BaseCache { + constructor(logger, cacheDir, cacheFile) { + super(logger, cacheDir, cacheFile || "llm_calls.json"); + } + /** + * Overrides the get method to track used hashes by requestId. + * @param options - The options used to generate the cache key. + * @param requestId - The identifier for the current request. + * @returns The cached data if available, otherwise null. + */ + get(options, requestId) { + return __async(this, null, function* () { + const data = yield __superGet(_LLMCache.prototype, this, "get").call(this, options, requestId); + return data; + }); + } + /** + * Overrides the set method to include cache cleanup logic. + * @param options - The options used to generate the cache key. + * @param data - The data to be cached. + * @param requestId - The identifier for the current request. + */ + set(options, data, requestId) { + return __async(this, null, function* () { + yield __superGet(_LLMCache.prototype, this, "set").call(this, options, data, requestId); + this.logger({ + category: "llm_cache", + message: "Cache miss - saved new response", + level: 1 + }); + }); + } +}; + +// lib/llm/aisdk.ts +var import_ai2 = require("ai"); + +// lib/llm/LLMClient.ts +var import_ai = require("ai"); +var AnnotatedScreenshotText = "This is a screenshot of the current page state with the elements annotated on it. Each element id is annotated with a number to the top left of it. Duplicate annotations at the same location are under each other vertically."; +var LLMClient = class { + constructor(modelName, userProvidedInstructions) { + this.generateObject = import_ai.generateObject; + this.generateText = import_ai.generateText; + this.streamText = import_ai.streamText; + this.streamObject = import_ai.streamObject; + this.generateImage = import_ai.experimental_generateImage; + this.embed = import_ai.embed; + this.embedMany = import_ai.embedMany; + this.transcribe = import_ai.experimental_transcribe; + this.generateSpeech = import_ai.experimental_generateSpeech; + this.modelName = modelName; + this.userProvidedInstructions = userProvidedInstructions; + } +}; + +// lib/llm/aisdk.ts +var AISdkClient = class extends LLMClient { + constructor({ + model, + logger, + enableCaching = false, + cache + }) { + super(model.modelId); + this.type = "aisdk"; + this.model = model; + this.logger = logger; + this.cache = cache; + this.enableCaching = enableCaching; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + options + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r, _s, _t; + (_a15 = this.logger) == null ? void 0 : _a15.call(this, { + category: "aisdk", + message: "creating chat completion", + level: 2, + auxiliary: { + options: { + value: JSON.stringify(__spreadProps(__spreadValues({}, options), { image: void 0 })), + type: "object" + }, + modelName: { + value: this.model.modelId, + type: "string" + } + } + }); + const cacheOptions = { + model: this.model.modelId, + messages: options.messages, + response_model: options.response_model + }; + if (this.enableCaching && this.cache) { + const cachedResponse = yield this.cache.get( + cacheOptions, + options.requestId + ); + if (cachedResponse) { + (_b = this.logger) == null ? void 0 : _b.call(this, { + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + cachedResponse: { + value: JSON.stringify(cachedResponse), + type: "object" + } + } + }); + return cachedResponse; + } else { + (_c = this.logger) == null ? void 0 : _c.call(this, { + category: "llm_cache", + message: "LLM cache miss - no cached response found", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + } + } + }); + } + } + const formattedMessages = options.messages.map((message) => { + if (Array.isArray(message.content)) { + if (message.role === "system") { + const systemMessage = { + role: "system", + content: message.content.map((c) => "text" in c ? c.text : "").join("\n") + }; + return systemMessage; + } + const contentParts = message.content.map((content) => { + if ("image_url" in content) { + const imageContent = { + type: "image", + image: content.image_url.url + }; + return imageContent; + } else { + const textContent = { + type: "text", + text: content.text + }; + return textContent; + } + }); + if (message.role === "user") { + const userMessage = { + role: "user", + content: contentParts + }; + return userMessage; + } else { + const textOnlyParts = contentParts.map((part) => ({ + type: "text", + text: part.type === "image" ? "[Image]" : part.text + })); + const assistantMessage = { + role: "assistant", + content: textOnlyParts + }; + return assistantMessage; + } + } + return { + role: message.role, + content: message.content + }; + }); + let objectResponse; + const isGPT5 = this.model.modelId.includes("gpt-5"); + if (options.response_model) { + try { + objectResponse = yield (0, import_ai2.generateObject)({ + model: this.model, + messages: formattedMessages, + schema: options.response_model.schema, + temperature: options.temperature, + providerOptions: isGPT5 ? { + openai: { + textVerbosity: "low", + // Making these the default for gpt-5 for now + reasoningEffort: "minimal" + } + } : void 0 + }); + } catch (err) { + if (import_ai2.NoObjectGeneratedError.isInstance(err)) { + (_i = this.logger) == null ? void 0 : _i.call(this, { + category: "AISDK error", + message: err.message, + level: 0, + auxiliary: { + cause: { + value: JSON.stringify((_d = err.cause) != null ? _d : {}), + type: "object" + }, + text: { + value: (_e = err.text) != null ? _e : "", + type: "string" + }, + response: { + value: JSON.stringify((_f = err.response) != null ? _f : {}), + type: "object" + }, + usage: { + value: JSON.stringify((_g = err.usage) != null ? _g : {}), + type: "object" + }, + finishReason: { + value: (_h = err.finishReason) != null ? _h : "unknown", + type: "string" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + throw err; + } + throw err; + } + const result2 = { + data: objectResponse.object, + usage: { + prompt_tokens: (_j = objectResponse.usage.promptTokens) != null ? _j : 0, + completion_tokens: (_k = objectResponse.usage.completionTokens) != null ? _k : 0, + total_tokens: (_l = objectResponse.usage.totalTokens) != null ? _l : 0 + } + }; + if (this.enableCaching) { + (_m = this.logger) == null ? void 0 : _m.call(this, { + category: "llm_cache", + message: "caching response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + }, + response: { + value: JSON.stringify(result2), + type: "object" + } + } + }); + this.cache.set(cacheOptions, result2, options.requestId); + } + (_n = this.logger) == null ? void 0 : _n.call(this, { + category: "aisdk", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(objectResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + return result2; + } + const tools = {}; + for (const rawTool of (_o = options.tools) != null ? _o : []) { + tools[rawTool.name] = { + description: rawTool.description, + parameters: rawTool.parameters + }; + } + const textResponse = yield (0, import_ai2.generateText)({ + model: this.model, + messages: formattedMessages, + temperature: options.temperature, + tools + }); + const result = { + data: textResponse.text, + usage: { + prompt_tokens: (_p = textResponse.usage.promptTokens) != null ? _p : 0, + completion_tokens: (_q = textResponse.usage.completionTokens) != null ? _q : 0, + total_tokens: (_r = textResponse.usage.totalTokens) != null ? _r : 0 + } + }; + if (this.enableCaching) { + (_s = this.logger) == null ? void 0 : _s.call(this, { + category: "llm_cache", + message: "caching response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + }, + response: { + value: JSON.stringify(result), + type: "object" + } + } + }); + this.cache.set(cacheOptions, result, options.requestId); + } + (_t = this.logger) == null ? void 0 : _t.call(this, { + category: "aisdk", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(textResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + return result; + }); + } +}; + +// lib/llm/AnthropicClient.ts +var import_sdk = __toESM(require("@anthropic-ai/sdk")); +var import_zod_to_json_schema2 = require("zod-to-json-schema"); +var AnthropicClient = class extends LLMClient { + constructor({ + enableCaching = false, + cache, + modelName, + clientOptions, + userProvidedInstructions + }) { + super(modelName); + this.type = "anthropic"; + this.client = new import_sdk.default(clientOptions); + this.cache = cache; + this.enableCaching = enableCaching; + this.modelName = modelName; + this.clientOptions = clientOptions; + this.userProvidedInstructions = userProvidedInstructions; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + options, + retries, + logger + }) { + var _a15, _b; + const optionsWithoutImage = __spreadValues({}, options); + delete optionsWithoutImage.image; + logger({ + category: "anthropic", + message: "creating chat completion", + level: 2, + auxiliary: { + options: { + value: JSON.stringify(optionsWithoutImage), + type: "object" + } + } + }); + const cacheOptions = { + model: this.modelName, + messages: options.messages, + temperature: options.temperature, + image: options.image, + response_model: options.response_model, + tools: options.tools, + retries + }; + if (this.enableCaching) { + const cachedResponse = yield this.cache.get( + cacheOptions, + options.requestId + ); + if (cachedResponse) { + logger({ + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { + cachedResponse: { + value: JSON.stringify(cachedResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + } + } + }); + return cachedResponse; + } else { + logger({ + category: "llm_cache", + message: "LLM cache miss - no cached response found", + level: 1, + auxiliary: { + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + } + } + const systemMessage = options.messages.find((msg) => { + if (msg.role === "system") { + if (typeof msg.content === "string") { + return true; + } else if (Array.isArray(msg.content)) { + return msg.content.every((content) => content.type !== "image_url"); + } + } + return false; + }); + const userMessages = options.messages.filter( + (msg) => msg.role !== "system" + ); + const formattedMessages = userMessages.map((msg) => { + if (typeof msg.content === "string") { + return { + role: msg.role, + // ensure its not checking for system types + content: msg.content + }; + } else { + return { + role: msg.role, + content: msg.content.map((content) => { + if ("image_url" in content) { + const formattedContent = { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: content.image_url.url + } + }; + return formattedContent; + } else { + return { type: "text", text: content.text }; + } + }) + }; + } + }); + if (options.image) { + const screenshotMessage = { + role: "user", + content: [ + { + type: "image", + source: { + type: "base64", + media_type: "image/jpeg", + data: options.image.buffer.toString("base64") + } + } + ] + }; + if (options.image.description && Array.isArray(screenshotMessage.content)) { + screenshotMessage.content.push({ + type: "text", + text: options.image.description + }); + } + formattedMessages.push(screenshotMessage); + } + let anthropicTools2 = (_a15 = options.tools) == null ? void 0 : _a15.map((tool) => { + return { + name: tool.name, + description: tool.description, + input_schema: { + type: "object", + properties: tool.parameters.properties, + required: tool.parameters.required + } + }; + }); + let toolDefinition; + if (options.response_model) { + const jsonSchema = (0, import_zod_to_json_schema2.zodToJsonSchema)(options.response_model.schema); + const { properties: schemaProperties, required: schemaRequired } = extractSchemaProperties(jsonSchema); + toolDefinition = { + name: "print_extracted_data", + description: "Prints the extracted data based on the provided schema.", + input_schema: { + type: "object", + properties: schemaProperties, + required: schemaRequired + } + }; + } + if (toolDefinition) { + anthropicTools2 = anthropicTools2 != null ? anthropicTools2 : []; + anthropicTools2.push(toolDefinition); + } + const response = yield this.client.messages.create({ + model: this.modelName, + max_tokens: options.maxTokens || 8192, + messages: formattedMessages, + tools: anthropicTools2, + system: systemMessage ? systemMessage.content : void 0, + temperature: options.temperature + }); + logger({ + category: "anthropic", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(response), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + const usageData = { + prompt_tokens: response.usage.input_tokens, + completion_tokens: response.usage.output_tokens, + total_tokens: response.usage.input_tokens + response.usage.output_tokens + }; + const transformedResponse = { + id: response.id, + object: "chat.completion", + created: Date.now(), + model: response.model, + choices: [ + { + index: 0, + message: { + role: "assistant", + content: ((_b = response.content.find((c) => c.type === "text")) == null ? void 0 : _b.text) || null, + tool_calls: response.content.filter((c) => c.type === "tool_use").map((toolUse) => ({ + id: toolUse.id, + type: "function", + function: { + name: toolUse.name, + arguments: JSON.stringify(toolUse.input) + } + })) + }, + finish_reason: response.stop_reason + } + ], + usage: usageData + }; + logger({ + category: "anthropic", + message: "transformed response", + level: 2, + auxiliary: { + transformedResponse: { + value: JSON.stringify(transformedResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + if (options.response_model) { + const toolUse = response.content.find((c) => c.type === "tool_use"); + if (toolUse && "input" in toolUse) { + const result = toolUse.input; + const finalParsedResponse = { + data: result, + usage: usageData + }; + if (this.enableCaching) { + this.cache.set(cacheOptions, finalParsedResponse, options.requestId); + } + return finalParsedResponse; + } else { + if (!retries || retries < 5) { + return this.createChatCompletion({ + options, + logger, + retries: (retries != null ? retries : 0) + 1 + }); + } + logger({ + category: "anthropic", + message: "error creating chat completion", + level: 0, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + } + } + }); + throw new CreateChatCompletionResponseError( + "No tool use with input in response" + ); + } + } + if (this.enableCaching) { + this.cache.set(cacheOptions, transformedResponse, options.requestId); + logger({ + category: "anthropic", + message: "cached response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + transformedResponse: { + value: JSON.stringify(transformedResponse), + type: "object" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + } + } + }); + } + return transformedResponse; + }); + } +}; +var extractSchemaProperties = (jsonSchema) => { + var _a15; + const schemaRoot = ((_a15 = jsonSchema.definitions) == null ? void 0 : _a15.MySchema) || jsonSchema; + return { + properties: schemaRoot.properties, + required: schemaRoot.required + }; +}; + +// lib/llm/CerebrasClient.ts +var import_openai = __toESM(require("openai")); +var import_zod_to_json_schema3 = require("zod-to-json-schema"); +var CerebrasClient = class extends LLMClient { + constructor({ + enableCaching = false, + cache, + modelName, + clientOptions, + userProvidedInstructions + }) { + super(modelName, userProvidedInstructions); + this.type = "cerebras"; + this.hasVision = false; + this.client = new import_openai.default(__spreadValues({ + baseURL: "https://api.cerebras.ai/v1", + apiKey: (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.CEREBRAS_API_KEY + }, clientOptions)); + this.cache = cache; + this.enableCaching = enableCaching; + this.modelName = modelName; + this.clientOptions = clientOptions; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + options, + retries, + logger + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; + const optionsWithoutImage = __spreadValues({}, options); + delete optionsWithoutImage.image; + logger({ + category: "cerebras", + message: "creating chat completion", + level: 2, + auxiliary: { + options: { + value: JSON.stringify(optionsWithoutImage), + type: "object" + } + } + }); + const cacheOptions = { + model: this.modelName.split("cerebras-")[1], + messages: options.messages, + temperature: options.temperature, + response_model: options.response_model, + tools: options.tools, + retries + }; + if (this.enableCaching) { + const cachedResponse = yield this.cache.get( + cacheOptions, + options.requestId + ); + if (cachedResponse) { + logger({ + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { + cachedResponse: { + value: JSON.stringify(cachedResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + } + } + }); + return cachedResponse; + } + } + const formattedMessages = options.messages.map((msg) => { + const baseMessage = { + content: typeof msg.content === "string" ? msg.content : Array.isArray(msg.content) && msg.content.length > 0 && "text" in msg.content[0] ? msg.content[0].text : "" + }; + if (msg.role === "system") { + return __spreadProps(__spreadValues({}, baseMessage), { role: "system" }); + } else if (msg.role === "assistant") { + return __spreadProps(__spreadValues({}, baseMessage), { role: "assistant" }); + } else { + return __spreadProps(__spreadValues({}, baseMessage), { role: "user" }); + } + }); + let tools = (_a15 = options.tools) == null ? void 0 : _a15.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: { + type: "object", + properties: tool.parameters.properties, + required: tool.parameters.required + } + } + })); + if (options.response_model) { + const jsonSchema = (0, import_zod_to_json_schema3.zodToJsonSchema)(options.response_model.schema); + const schemaProperties = jsonSchema.properties || {}; + const schemaRequired = jsonSchema.required || []; + const responseTool = { + type: "function", + function: { + name: "print_extracted_data", + description: "Prints the extracted data based on the provided schema.", + parameters: { + type: "object", + properties: schemaProperties, + required: schemaRequired + } + } + }; + tools = tools ? [...tools, responseTool] : [responseTool]; + } + try { + const apiResponse = yield this.client.chat.completions.create({ + model: this.modelName.split("cerebras-")[1], + messages: [ + ...formattedMessages, + // Add explicit instruction to return JSON if we have a response model + ...options.response_model ? [ + { + role: "system", + content: `IMPORTANT: Your response must be valid JSON that matches this schema: ${JSON.stringify( + options.response_model.schema + )}` + } + ] : [] + ], + temperature: options.temperature || 0.7, + max_tokens: options.maxTokens, + tools, + tool_choice: options.tool_choice || "auto" + }); + const response = { + id: apiResponse.id, + object: "chat.completion", + created: Date.now(), + model: this.modelName.split("cerebras-")[1], + choices: [ + { + index: 0, + message: { + role: "assistant", + content: ((_c = (_b = apiResponse.choices[0]) == null ? void 0 : _b.message) == null ? void 0 : _c.content) || null, + tool_calls: ((_e = (_d = apiResponse.choices[0]) == null ? void 0 : _d.message) == null ? void 0 : _e.tool_calls) || [] + }, + finish_reason: ((_f = apiResponse.choices[0]) == null ? void 0 : _f.finish_reason) || "stop" + } + ], + usage: { + prompt_tokens: ((_g = apiResponse.usage) == null ? void 0 : _g.prompt_tokens) || 0, + completion_tokens: ((_h = apiResponse.usage) == null ? void 0 : _h.completion_tokens) || 0, + total_tokens: ((_i = apiResponse.usage) == null ? void 0 : _i.total_tokens) || 0 + } + }; + logger({ + category: "cerebras", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(response), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + if (!options.response_model) { + if (this.enableCaching) { + yield this.cache.set(cacheOptions, response, options.requestId); + } + return response; + } + const toolCall = (_l = (_k = (_j = response.choices[0]) == null ? void 0 : _j.message) == null ? void 0 : _k.tool_calls) == null ? void 0 : _l[0]; + if ((_m = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _m.arguments) { + try { + const result = JSON.parse(toolCall.function.arguments); + const finalResponse = { + data: result, + usage: response.usage + }; + if (this.enableCaching) { + yield this.cache.set( + cacheOptions, + finalResponse, + options.requestId + ); + } + return finalResponse; + } catch (e) { + logger({ + category: "cerebras", + message: "failed to parse tool call arguments as JSON, retrying", + level: 0, + auxiliary: { + error: { + value: e.message, + type: "string" + } + } + }); + } + } + const content = (_o = (_n = response.choices[0]) == null ? void 0 : _n.message) == null ? void 0 : _o.content; + if (content) { + try { + const jsonMatch = content.match(/\{[\s\S]*\}/); + if (jsonMatch) { + const result = JSON.parse(jsonMatch[0]); + const finalResponse = { + data: result, + usage: response.usage + }; + if (this.enableCaching) { + yield this.cache.set( + cacheOptions, + finalResponse, + options.requestId + ); + } + return finalResponse; + } + } catch (e) { + logger({ + category: "cerebras", + message: "failed to parse content as JSON", + level: 0, + auxiliary: { + error: { + value: e.message, + type: "string" + } + } + }); + } + } + if (!retries || retries < 5) { + return this.createChatCompletion({ + options, + logger, + retries: (retries != null ? retries : 0) + 1 + }); + } + throw new CreateChatCompletionResponseError("Invalid response schema"); + } catch (error) { + logger({ + category: "cerebras", + message: "error creating chat completion", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + throw error; + } + }); + } +}; + +// lib/llm/GoogleClient.ts +var import_genai2 = require("@google/genai"); +var import_zod_to_json_schema4 = __toESM(require("zod-to-json-schema")); +var roleMap = { + user: "user", + assistant: "model", + system: "user" + // Gemini API prefers system instructions either via system_instruction or at the start of 'user' content +}; +var safetySettings = [ + { + category: import_genai2.HarmCategory.HARM_CATEGORY_HARASSMENT, + threshold: import_genai2.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE + }, + { + category: import_genai2.HarmCategory.HARM_CATEGORY_HATE_SPEECH, + threshold: import_genai2.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE + }, + { + category: import_genai2.HarmCategory.HARM_CATEGORY_SEXUALLY_EXPLICIT, + threshold: import_genai2.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE + }, + { + category: import_genai2.HarmCategory.HARM_CATEGORY_DANGEROUS_CONTENT, + threshold: import_genai2.HarmBlockThreshold.BLOCK_MEDIUM_AND_ABOVE + } +]; +var GoogleClient = class extends LLMClient { + constructor({ + logger, + // Added logger based on other clients + enableCaching = false, + cache, + modelName, + clientOptions + }) { + super(modelName); + this.type = "google"; + if (!(clientOptions == null ? void 0 : clientOptions.apiKey)) { + clientOptions.apiKey = loadApiKeyFromEnv("google_legacy", logger); + } + this.clientOptions = clientOptions; + this.client = new import_genai2.GoogleGenAI({ apiKey: clientOptions.apiKey }); + this.cache = cache; + this.enableCaching = enableCaching; + this.modelName = modelName; + this.logger = logger; + this.hasVision = modelName.includes("vision") || modelName.includes("gemini-1.5"); + } + // Helper to convert project's ChatMessage[] to Gemini's Content[] + formatMessages(messages, image) { + const contents = []; + let systemInstruction = null; + messages.forEach((msg, index) => { + const role = roleMap[msg.role]; + if (!role) { + this.logger({ + category: "google", + message: `WARNING: Unsupported role: ${msg.role}`, + level: 1 + }); + return; + } + if (msg.role === "system") { + if (typeof msg.content === "string") { + systemInstruction = (systemInstruction ? systemInstruction + "\n\n" : "") + msg.content; + } + return; + } + const parts = []; + if (Array.isArray(msg.content)) { + msg.content.forEach((partContent) => { + var _a15; + if (partContent.type === "text") { + parts.push({ text: partContent.text }); + } else if (partContent.type === "image_url") { + if ("image_url" in partContent && ((_a15 = partContent.image_url) == null ? void 0 : _a15.url)) { + const base64Data = partContent.image_url.url.split(",")[1]; + const mimeTypeMatch = partContent.image_url.url.match( + /^data:(image\/\w+);base64,/ + ); + if (base64Data && mimeTypeMatch) { + parts.push({ + inlineData: { mimeType: mimeTypeMatch[1], data: base64Data } + }); + } else { + this.logger({ + category: "google", + message: "WARNING: Could not parse image data URI format", + level: 1 + }); + } + } + } + }); + } else if (typeof msg.content === "string") { + parts.push({ text: msg.content }); + } + if (image && index === messages.length - 1 && msg.role === "user") { + const imageDesc = image.description || AnnotatedScreenshotText; + parts.push({ text: imageDesc }); + parts.push({ + inlineData: { + mimeType: "image/jpeg", + // Assuming JPEG, adjust if needed + data: image.buffer.toString("base64") + } + }); + } + if (systemInstruction && contents.length === 0 && role === "user") { + const firstPartText = parts.find((p) => "text" in p); + if (firstPartText && "text" in firstPartText) { + firstPartText.text = `${systemInstruction} + +${firstPartText.text}`; + } else { + parts.unshift({ text: systemInstruction }); + } + systemInstruction = null; + } + if (parts.length > 0) { + contents.push({ role, parts }); + } + }); + if (systemInstruction) { + contents.unshift({ role: "user", parts: [{ text: systemInstruction }] }); + } + return contents; + } + // Helper to convert LLMTool[] to Gemini's Tool[] + formatTools(tools) { + if (!tools || tools.length === 0) { + return void 0; + } + return [ + { + functionDeclarations: tools.map((tool) => { + let parameters = void 0; + if (tool.parameters) { + parameters = { + type: import_genai2.Type.OBJECT, + properties: tool.parameters.properties, + required: tool.parameters.required + }; + } + return { + name: tool.name, + description: tool.description, + parameters + }; + }) + } + ]; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + // Ensure LLMResponse is compatible + options, + logger, + retries = 3 + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i; + const { + image, + requestId, + response_model, + tools, + temperature, + top_p, + maxTokens + } = options; + const cacheKeyOptions = { + model: this.modelName, + messages: options.messages, + temperature, + top_p, + // frequency_penalty and presence_penalty are not directly supported in Gemini API + image: image ? { description: image.description, bufferLength: image.buffer.length } : void 0, + // Use buffer length for caching key stability + response_model: response_model ? { + name: response_model.name, + schema: JSON.stringify((0, import_zod_to_json_schema4.default)(response_model.schema)) + } : void 0, + tools, + maxTokens + }; + if (this.enableCaching) { + const cachedResponse = yield this.cache.get( + cacheKeyOptions, + requestId + ); + if (cachedResponse) { + logger({ + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { requestId: { value: requestId, type: "string" } } + }); + return cachedResponse; + } else { + logger({ + category: "llm_cache", + message: "LLM cache miss - proceeding with API call", + level: 1, + auxiliary: { requestId: { value: requestId, type: "string" } } + }); + } + } + const formattedMessages = this.formatMessages(options.messages, image); + const formattedTools = this.formatTools(tools); + const generationConfig = { + maxOutputTokens: maxTokens, + temperature, + topP: top_p, + responseMimeType: response_model ? "application/json" : void 0, + responseSchema: response_model ? toGeminiSchema(response_model.schema) : void 0 + }; + logger({ + category: "google", + message: "creating chat completion", + level: 2, + auxiliary: { + modelName: { value: this.modelName, type: "string" }, + requestId: { value: requestId, type: "string" }, + requestPayloadSummary: { + value: `Model: ${this.modelName}, Messages: ${formattedMessages.length}, Config Keys: ${Object.keys(generationConfig).join(", ")}, Tools: ${formattedTools ? formattedTools.length : 0}, Safety Categories: ${safetySettings.map((s) => s.category).join(", ")}`, + type: "string" + } + } + }); + const requestPayload = { + model: this.modelName, + contents: formattedMessages, + config: __spreadProps(__spreadValues({}, generationConfig), { + safetySettings, + tools: formattedTools + }) + }; + try { + logger({ + category: "google", + message: "Full request payload", + level: 2, + auxiliary: { + requestId: { value: requestId, type: "string" }, + fullPayload: { + value: JSON.stringify(requestPayload), + type: "object" + } + } + }); + } catch (e) { + logger({ + category: "google", + message: "Failed to stringify full request payload for logging", + level: 0, + auxiliary: { + requestId: { value: requestId, type: "string" }, + error: { value: e.message, type: "string" } + } + }); + } + try { + const result = yield this.client.models.generateContent(requestPayload); + logger({ + category: "google", + message: "received response", + level: 2, + auxiliary: { + requestId: { value: requestId, type: "string" }, + response: { + value: JSON.stringify(result), + type: "object" + } + } + }); + const finishReason = ((_b = (_a15 = result.candidates) == null ? void 0 : _a15[0]) == null ? void 0 : _b.finishReason) || "unknown"; + const toolCalls = (_c = result.functionCalls) == null ? void 0 : _c.map( + (fc, index) => ({ + id: `tool_call_${requestId}_${index}`, + type: "function", + function: { + name: fc.name, + arguments: JSON.stringify(fc.args) + } + }) + ); + let content = null; + try { + content = result.text; + } catch (e) { + logger({ + category: "google", + message: `Could not extract text content: ${e.message}`, + level: 1, + auxiliary: { requestId: { value: requestId, type: "string" } } + }); + content = null; + } + const llmResponse = { + id: ((_f = (_e = (_d = result.candidates) == null ? void 0 : _d[0]) == null ? void 0 : _e.index) == null ? void 0 : _f.toString()) || requestId, + object: "chat.completion", + created: Math.floor(Date.now() / 1e3), + model: this.modelName, + choices: [ + { + index: 0, + message: { + role: "assistant", + content, + tool_calls: toolCalls + }, + finish_reason: finishReason + } + ], + usage: { + prompt_tokens: ((_g = result.usageMetadata) == null ? void 0 : _g.promptTokenCount) || 0, + completion_tokens: ((_h = result.usageMetadata) == null ? void 0 : _h.candidatesTokenCount) || 0, + total_tokens: ((_i = result.usageMetadata) == null ? void 0 : _i.totalTokenCount) || 0 + } + }; + if (response_model) { + let parsedData; + try { + const potentialJson = (content == null ? void 0 : content.trim().replace(/^```json\n?|\n?```$/g, "")) || "{}"; + parsedData = JSON.parse(potentialJson); + } catch (e) { + logger({ + category: "google", + message: `Failed to parse JSON response: ${e.message}`, + level: 0, + auxiliary: { + content: { value: content || "null", type: "string" } + } + }); + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + throw new CreateChatCompletionResponseError( + `Failed to parse JSON response: ${e.message}` + ); + } + try { + validateZodSchema(response_model.schema, parsedData); + } catch (err) { + logger({ + category: "google", + message: "Response failed Zod schema validation", + level: 0 + }); + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + throw err; + } + const extractionResult = { + data: parsedData, + usage: llmResponse.usage + }; + if (this.enableCaching) { + yield this.cache.set(cacheKeyOptions, extractionResult, requestId); + } + return extractionResult; + } + if (this.enableCaching) { + yield this.cache.set(cacheKeyOptions, llmResponse, requestId); + } + return llmResponse; + } catch (error) { + logger({ + category: "google", + message: `Error during Google AI chat completion: ${error.message}`, + level: 0, + auxiliary: { + errorDetails: { + value: `Message: ${error.message}${error.stack ? "\nStack: " + error.stack : ""}`, + type: "string" + }, + requestId: { value: requestId, type: "string" } + } + }); + if (retries > 0) { + logger({ + category: "google", + message: `Retrying... (${retries} attempts left)`, + level: 1 + }); + yield new Promise( + (resolve2) => setTimeout(resolve2, 1e3 * (4 - retries)) + ); + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + if (error instanceof StagehandError) { + throw error; + } + throw new StagehandError( + `Google AI API request failed: ${error.message}` + ); + } + }); + } +}; + +// lib/llm/GroqClient.ts +var import_openai2 = __toESM(require("openai")); +var import_zod_to_json_schema5 = require("zod-to-json-schema"); +var GroqClient = class extends LLMClient { + constructor({ + enableCaching = false, + cache, + modelName, + clientOptions, + userProvidedInstructions + }) { + super(modelName, userProvidedInstructions); + this.type = "groq"; + this.hasVision = false; + this.client = new import_openai2.default(__spreadValues({ + baseURL: "https://api.groq.com/openai/v1", + apiKey: (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.GROQ_API_KEY + }, clientOptions)); + this.cache = cache; + this.enableCaching = enableCaching; + this.modelName = modelName; + this.clientOptions = clientOptions; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + options, + retries, + logger + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; + const optionsWithoutImage = __spreadValues({}, options); + delete optionsWithoutImage.image; + logger({ + category: "groq", + message: "creating chat completion", + level: 2, + auxiliary: { + options: { + value: JSON.stringify(optionsWithoutImage), + type: "object" + } + } + }); + const cacheOptions = { + model: this.modelName.split("groq-")[1], + messages: options.messages, + temperature: options.temperature, + response_model: options.response_model, + tools: options.tools, + retries + }; + if (this.enableCaching) { + const cachedResponse = yield this.cache.get( + cacheOptions, + options.requestId + ); + if (cachedResponse) { + logger({ + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { + cachedResponse: { + value: JSON.stringify(cachedResponse), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + } + } + }); + return cachedResponse; + } + } + const formattedMessages = options.messages.map((msg) => { + const baseMessage = { + content: typeof msg.content === "string" ? msg.content : Array.isArray(msg.content) && msg.content.length > 0 && "text" in msg.content[0] ? msg.content[0].text : "" + }; + if (msg.role === "system") { + return __spreadProps(__spreadValues({}, baseMessage), { role: "system" }); + } else if (msg.role === "assistant") { + return __spreadProps(__spreadValues({}, baseMessage), { role: "assistant" }); + } else { + return __spreadProps(__spreadValues({}, baseMessage), { role: "user" }); + } + }); + let tools = (_a15 = options.tools) == null ? void 0 : _a15.map((tool) => ({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: { + type: "object", + properties: tool.parameters.properties, + required: tool.parameters.required + } + } + })); + if (options.response_model) { + const jsonSchema = (0, import_zod_to_json_schema5.zodToJsonSchema)(options.response_model.schema); + const schemaProperties = jsonSchema.properties || {}; + const schemaRequired = jsonSchema.required || []; + const responseTool = { + type: "function", + function: { + name: "print_extracted_data", + description: "Prints the extracted data based on the provided schema.", + parameters: { + type: "object", + properties: schemaProperties, + required: schemaRequired + } + } + }; + tools = tools ? [...tools, responseTool] : [responseTool]; + } + try { + const apiResponse = yield this.client.chat.completions.create({ + model: this.modelName.split("groq-")[1], + messages: [ + ...formattedMessages, + // Add explicit instruction to return JSON if we have a response model + ...options.response_model ? [ + { + role: "system", + content: `IMPORTANT: Your response must be valid JSON that matches this schema: ${JSON.stringify( + options.response_model.schema + )}` + } + ] : [] + ], + temperature: options.temperature || 0.7, + max_tokens: options.maxTokens, + tools, + tool_choice: options.tool_choice || "auto" + }); + const response = { + id: apiResponse.id, + object: "chat.completion", + created: Date.now(), + model: this.modelName.split("groq-")[1], + choices: [ + { + index: 0, + message: { + role: "assistant", + content: ((_c = (_b = apiResponse.choices[0]) == null ? void 0 : _b.message) == null ? void 0 : _c.content) || null, + tool_calls: ((_e = (_d = apiResponse.choices[0]) == null ? void 0 : _d.message) == null ? void 0 : _e.tool_calls) || [] + }, + finish_reason: ((_f = apiResponse.choices[0]) == null ? void 0 : _f.finish_reason) || "stop" + } + ], + usage: { + prompt_tokens: ((_g = apiResponse.usage) == null ? void 0 : _g.prompt_tokens) || 0, + completion_tokens: ((_h = apiResponse.usage) == null ? void 0 : _h.completion_tokens) || 0, + total_tokens: ((_i = apiResponse.usage) == null ? void 0 : _i.total_tokens) || 0 + } + }; + logger({ + category: "groq", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(response), + type: "object" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + if (!options.response_model) { + if (this.enableCaching) { + yield this.cache.set(cacheOptions, response, options.requestId); + } + return response; + } + const toolCall = (_l = (_k = (_j = response.choices[0]) == null ? void 0 : _j.message) == null ? void 0 : _k.tool_calls) == null ? void 0 : _l[0]; + if ((_m = toolCall == null ? void 0 : toolCall.function) == null ? void 0 : _m.arguments) { + try { + const result = JSON.parse(toolCall.function.arguments); + const finalResponse = { + data: result, + usage: response.usage + }; + if (this.enableCaching) { + yield this.cache.set( + cacheOptions, + finalResponse, + options.requestId + ); + } + return finalResponse; + } catch (e) { + logger({ + category: "groq", + message: "failed to parse tool call arguments as JSON, retrying", + level: 0, + auxiliary: { + error: { + value: e.message, + type: "string" + } + } + }); + } + } + const content = (_o = (_n = response.choices[0]) == null ? void 0 : _n.message) == null ? void 0 : _o.content; + if (content) { + try { + const jsonMatch = content.match(/\{[\s\S]*\}/); + if (jsonMatch) { + const result = JSON.parse(jsonMatch[0]); + const finalResponse = { + data: result, + usage: response.usage + }; + if (this.enableCaching) { + yield this.cache.set( + cacheOptions, + finalResponse, + options.requestId + ); + } + return finalResponse; + } + } catch (e) { + logger({ + category: "groq", + message: "failed to parse content as JSON", + level: 0, + auxiliary: { + error: { + value: e.message, + type: "string" + } + } + }); + } + } + if (!retries || retries < 5) { + return this.createChatCompletion({ + options, + logger, + retries: (retries != null ? retries : 0) + 1 + }); + } + throw new CreateChatCompletionResponseError("Invalid response schema"); + } catch (error) { + logger({ + category: "groq", + message: "error creating chat completion", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + requestId: { + value: options.requestId, + type: "string" + } + } + }); + throw error; + } + }); + } +}; + +// lib/llm/OpenAIClient.ts +var import_openai3 = __toESM(require("openai")); +var import_zod = require("openai/helpers/zod"); +var import_zod_to_json_schema6 = __toESM(require("zod-to-json-schema")); +var OpenAIClient = class extends LLMClient { + constructor({ + enableCaching = false, + cache, + modelName, + clientOptions + }) { + super(modelName); + this.type = "openai"; + this.clientOptions = clientOptions; + this.client = new import_openai3.default(clientOptions); + this.cache = cache; + this.enableCaching = enableCaching; + this.modelName = modelName; + } + createChatCompletion(_0) { + return __async(this, arguments, function* ({ + options: optionsInitial, + logger, + retries = 3 + }) { + var _a15, _b, _e; + let options = optionsInitial; + let isToolsOverridedForO1 = false; + if (this.modelName.startsWith("o1") || this.modelName.startsWith("o3")) { + let { + tool_choice, + top_p, + frequency_penalty, + presence_penalty, + temperature + } = options; + _a15 = options, { + tool_choice, + top_p, + frequency_penalty, + presence_penalty, + temperature + } = _a15, options = __objRest(_a15, [ + "tool_choice", + "top_p", + "frequency_penalty", + "presence_penalty", + "temperature" + ]); + options.messages = options.messages.map((message) => __spreadProps(__spreadValues({}, message), { + role: "user" + })); + if (options.tools && options.response_model) { + throw new StagehandError( + "Cannot use both tool and response_model for o1 models" + ); + } + if (options.tools) { + let { tools } = options; + _b = options, { tools } = _b, options = __objRest(_b, ["tools"]); + isToolsOverridedForO1 = true; + options.messages.push({ + role: "user", + content: `You have the following tools available to you: +${JSON.stringify( + tools + )} + + Respond with the following zod schema format to use a method: { + "name": "", + "arguments": + } + + Do not include any other text or formattings like \`\`\` in your response. Just the JSON object.` + }); + } + } + if (options.temperature && (this.modelName.startsWith("o1") || this.modelName.startsWith("o3"))) { + throw new StagehandError("Temperature is not supported for o1 models"); + } + const _c = options, { image, requestId } = _c, optionsWithoutImageAndRequestId = __objRest(_c, ["image", "requestId"]); + logger({ + category: "openai", + message: "creating chat completion", + level: 2, + auxiliary: { + options: { + value: JSON.stringify(__spreadProps(__spreadValues({}, optionsWithoutImageAndRequestId), { + requestId + })), + type: "object" + }, + modelName: { + value: this.modelName, + type: "string" + } + } + }); + const cacheOptions = { + model: this.modelName, + messages: options.messages, + temperature: options.temperature, + top_p: options.top_p, + frequency_penalty: options.frequency_penalty, + presence_penalty: options.presence_penalty, + image, + response_model: options.response_model + }; + if (this.enableCaching) { + const cachedResponse = yield this.cache.get( + cacheOptions, + options.requestId + ); + if (cachedResponse) { + logger({ + category: "llm_cache", + message: "LLM cache hit - returning cached response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + cachedResponse: { + value: JSON.stringify(cachedResponse), + type: "object" + } + } + }); + return cachedResponse; + } else { + logger({ + category: "llm_cache", + message: "LLM cache miss - no cached response found", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + } + } + }); + } + } + if (options.image) { + const screenshotMessage = { + role: "user", + content: [ + { + type: "image_url", + image_url: { + url: `data:image/jpeg;base64,${options.image.buffer.toString("base64")}` + } + }, + ...options.image.description ? [{ type: "text", text: options.image.description }] : [] + ] + }; + options.messages.push(screenshotMessage); + } + let responseFormat = void 0; + if (options.response_model) { + if (this.modelName.startsWith("o1") || this.modelName.startsWith("o3")) { + try { + const parsedSchema = JSON.stringify( + (0, import_zod_to_json_schema6.default)(options.response_model.schema) + ); + options.messages.push({ + role: "user", + content: `Respond in this zod schema format: +${parsedSchema} + + + Do not include any other text, formatting or markdown in your output. Do not include \`\`\` or \`\`\`json in your response. Only the JSON object itself.` + }); + } catch (error) { + logger({ + category: "openai", + message: "Failed to parse response model schema", + level: 0 + }); + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + throw error; + } + } else { + responseFormat = (0, import_zod.zodResponseFormat)( + options.response_model.schema, + options.response_model.name + ); + } + } + const _d = __spreadProps(__spreadValues({}, optionsWithoutImageAndRequestId), { + model: this.modelName + }), { response_model } = _d, openAiOptions = __objRest(_d, ["response_model"]); + logger({ + category: "openai", + message: "creating chat completion", + level: 2, + auxiliary: { + openAiOptions: { + value: JSON.stringify(openAiOptions), + type: "object" + } + } + }); + const formattedMessages = options.messages.map((message) => { + if (Array.isArray(message.content)) { + const contentParts = message.content.map((content) => { + if ("image_url" in content) { + const imageContent = { + image_url: { + url: content.image_url.url + }, + type: "image_url" + }; + return imageContent; + } else { + const textContent = { + text: content.text, + type: "text" + }; + return textContent; + } + }); + if (message.role === "system") { + const formattedMessage2 = __spreadProps(__spreadValues({}, message), { + role: "system", + content: contentParts.filter( + (content) => content.type === "text" + ) + }); + return formattedMessage2; + } else if (message.role === "user") { + const formattedMessage2 = __spreadProps(__spreadValues({}, message), { + role: "user", + content: contentParts + }); + return formattedMessage2; + } else { + const formattedMessage2 = __spreadProps(__spreadValues({}, message), { + role: "assistant", + content: contentParts.filter( + (content) => content.type === "text" + ) + }); + return formattedMessage2; + } + } + const formattedMessage = { + role: "user", + content: message.content + }; + return formattedMessage; + }); + const body = __spreadProps(__spreadValues({}, openAiOptions), { + model: this.modelName, + messages: formattedMessages, + response_format: responseFormat, + stream: false, + tools: (_e = options.tools) == null ? void 0 : _e.map((tool) => ({ + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters + }, + type: "function" + })) + }); + const response = yield this.client.chat.completions.create(body); + if (isToolsOverridedForO1) { + try { + const parsedContent = JSON.parse(response.choices[0].message.content); + response.choices[0].message.tool_calls = [ + { + function: { + name: parsedContent["name"], + arguments: JSON.stringify(parsedContent["arguments"]) + }, + type: "function", + id: "-1" + } + ]; + response.choices[0].message.content = null; + } catch (error) { + logger({ + category: "openai", + message: "Failed to parse tool call response", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + content: { + value: response.choices[0].message.content, + type: "string" + } + } + }); + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + throw error; + } + } + logger({ + category: "openai", + message: "response", + level: 2, + auxiliary: { + response: { + value: JSON.stringify(response), + type: "object" + }, + requestId: { + value: requestId, + type: "string" + } + } + }); + if (options.response_model) { + const extractedData = response.choices[0].message.content; + const parsedData = JSON.parse(extractedData); + try { + validateZodSchema(options.response_model.schema, parsedData); + } catch (e) { + logger({ + category: "openai", + message: "Response failed Zod schema validation", + level: 0 + }); + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1 + }); + } + if (e instanceof ZodSchemaValidationError) { + logger({ + category: "openai", + message: `Error during OpenAI chat completion: ${e.message}`, + level: 0, + auxiliary: { + errorDetails: { + value: `Message: ${e.message}${e.stack ? "\nStack: " + e.stack : ""}`, + type: "string" + }, + requestId: { value: requestId, type: "string" } + } + }); + throw new CreateChatCompletionResponseError(e.message); + } + throw e; + } + if (this.enableCaching) { + this.cache.set( + cacheOptions, + __spreadValues({}, parsedData), + options.requestId + ); + } + return { + data: parsedData, + usage: response.usage + }; + } + if (this.enableCaching) { + logger({ + category: "llm_cache", + message: "caching response", + level: 1, + auxiliary: { + requestId: { + value: options.requestId, + type: "string" + }, + cacheOptions: { + value: JSON.stringify(cacheOptions), + type: "object" + }, + response: { + value: JSON.stringify(response), + type: "object" + } + } + }); + this.cache.set(cacheOptions, response, options.requestId); + } + return response; + }); + } +}; + +// node_modules/.pnpm/@ai-sdk+provider@1.1.3/node_modules/@ai-sdk/provider/dist/index.mjs +var marker = "vercel.ai.error"; +var symbol = Symbol.for(marker); +var _a; +var _AISDKError = class _AISDKError2 extends Error { + /** + * Creates an AI SDK Error. + * + * @param {Object} params - The parameters for creating the error. + * @param {string} params.name - The name of the error. + * @param {string} params.message - The error message. + * @param {unknown} [params.cause] - The underlying cause of the error. + */ + constructor({ + name: name14, + message, + cause + }) { + super(message); + this[_a] = true; + this.name = name14; + this.cause = cause; + } + /** + * Checks if the given error is an AI SDK Error. + * @param {unknown} error - The error to check. + * @returns {boolean} True if the error is an AI SDK Error, false otherwise. + */ + static isInstance(error) { + return _AISDKError2.hasMarker(error, marker); + } + static hasMarker(error, marker15) { + const markerSymbol = Symbol.for(marker15); + return error != null && typeof error === "object" && markerSymbol in error && typeof error[markerSymbol] === "boolean" && error[markerSymbol] === true; + } +}; +_a = symbol; +var AISDKError = _AISDKError; +var name = "AI_APICallError"; +var marker2 = `vercel.ai.error.${name}`; +var symbol2 = Symbol.for(marker2); +var _a2; +var APICallError = class extends AISDKError { + constructor({ + message, + url, + requestBodyValues, + statusCode, + responseHeaders, + responseBody, + cause, + isRetryable = statusCode != null && (statusCode === 408 || // request timeout + statusCode === 409 || // conflict + statusCode === 429 || // too many requests + statusCode >= 500), + // server error + data + }) { + super({ name, message, cause }); + this[_a2] = true; + this.url = url; + this.requestBodyValues = requestBodyValues; + this.statusCode = statusCode; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + this.isRetryable = isRetryable; + this.data = data; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker2); + } +}; +_a2 = symbol2; +var name2 = "AI_EmptyResponseBodyError"; +var marker3 = `vercel.ai.error.${name2}`; +var symbol3 = Symbol.for(marker3); +var _a3; +var EmptyResponseBodyError = class extends AISDKError { + // used in isInstance + constructor({ message = "Empty response body" } = {}) { + super({ name: name2, message }); + this[_a3] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker3); + } +}; +_a3 = symbol3; +function getErrorMessage(error) { + if (error == null) { + return "unknown error"; + } + if (typeof error === "string") { + return error; + } + if (error instanceof Error) { + return error.message; + } + return JSON.stringify(error); +} +var name3 = "AI_InvalidArgumentError"; +var marker4 = `vercel.ai.error.${name3}`; +var symbol4 = Symbol.for(marker4); +var _a4; +var InvalidArgumentError = class extends AISDKError { + constructor({ + message, + cause, + argument + }) { + super({ name: name3, message, cause }); + this[_a4] = true; + this.argument = argument; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker4); + } +}; +_a4 = symbol4; +var name4 = "AI_InvalidPromptError"; +var marker5 = `vercel.ai.error.${name4}`; +var symbol5 = Symbol.for(marker5); +var _a5; +var InvalidPromptError = class extends AISDKError { + constructor({ + prompt, + message, + cause + }) { + super({ name: name4, message: `Invalid prompt: ${message}`, cause }); + this[_a5] = true; + this.prompt = prompt; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker5); + } +}; +_a5 = symbol5; +var name5 = "AI_InvalidResponseDataError"; +var marker6 = `vercel.ai.error.${name5}`; +var symbol6 = Symbol.for(marker6); +var _a6; +var InvalidResponseDataError = class extends AISDKError { + constructor({ + data, + message = `Invalid response data: ${JSON.stringify(data)}.` + }) { + super({ name: name5, message }); + this[_a6] = true; + this.data = data; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker6); + } +}; +_a6 = symbol6; +var name6 = "AI_JSONParseError"; +var marker7 = `vercel.ai.error.${name6}`; +var symbol7 = Symbol.for(marker7); +var _a7; +var JSONParseError = class extends AISDKError { + constructor({ text, cause }) { + super({ + name: name6, + message: `JSON parsing failed: Text: ${text}. +Error message: ${getErrorMessage(cause)}`, + cause + }); + this[_a7] = true; + this.text = text; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker7); + } +}; +_a7 = symbol7; +var name7 = "AI_LoadAPIKeyError"; +var marker8 = `vercel.ai.error.${name7}`; +var symbol8 = Symbol.for(marker8); +var _a8; +var LoadAPIKeyError = class extends AISDKError { + // used in isInstance + constructor({ message }) { + super({ name: name7, message }); + this[_a8] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker8); + } +}; +_a8 = symbol8; +var name8 = "AI_LoadSettingError"; +var marker9 = `vercel.ai.error.${name8}`; +var symbol9 = Symbol.for(marker9); +var _a9; +var LoadSettingError = class extends AISDKError { + // used in isInstance + constructor({ message }) { + super({ name: name8, message }); + this[_a9] = true; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker9); + } +}; +_a9 = symbol9; +var name9 = "AI_NoContentGeneratedError"; +var marker10 = `vercel.ai.error.${name9}`; +var symbol10 = Symbol.for(marker10); +var _a10; +_a10 = symbol10; +var name10 = "AI_NoSuchModelError"; +var marker11 = `vercel.ai.error.${name10}`; +var symbol11 = Symbol.for(marker11); +var _a11; +var NoSuchModelError = class extends AISDKError { + constructor({ + errorName = name10, + modelId, + modelType, + message = `No such ${modelType}: ${modelId}` + }) { + super({ name: errorName, message }); + this[_a11] = true; + this.modelId = modelId; + this.modelType = modelType; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker11); + } +}; +_a11 = symbol11; +var name11 = "AI_TooManyEmbeddingValuesForCallError"; +var marker12 = `vercel.ai.error.${name11}`; +var symbol12 = Symbol.for(marker12); +var _a12; +var TooManyEmbeddingValuesForCallError = class extends AISDKError { + constructor(options) { + super({ + name: name11, + message: `Too many values for a single embedding call. The ${options.provider} model "${options.modelId}" can only embed up to ${options.maxEmbeddingsPerCall} values per call, but ${options.values.length} values were provided.` + }); + this[_a12] = true; + this.provider = options.provider; + this.modelId = options.modelId; + this.maxEmbeddingsPerCall = options.maxEmbeddingsPerCall; + this.values = options.values; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker12); + } +}; +_a12 = symbol12; +var name12 = "AI_TypeValidationError"; +var marker13 = `vercel.ai.error.${name12}`; +var symbol13 = Symbol.for(marker13); +var _a13; +var _TypeValidationError = class _TypeValidationError2 extends AISDKError { + constructor({ value, cause }) { + super({ + name: name12, + message: `Type validation failed: Value: ${JSON.stringify(value)}. +Error message: ${getErrorMessage(cause)}`, + cause + }); + this[_a13] = true; + this.value = value; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker13); + } + /** + * Wraps an error into a TypeValidationError. + * If the cause is already a TypeValidationError with the same value, it returns the cause. + * Otherwise, it creates a new TypeValidationError. + * + * @param {Object} params - The parameters for wrapping the error. + * @param {unknown} params.value - The value that failed validation. + * @param {unknown} params.cause - The original error or cause of the validation failure. + * @returns {TypeValidationError} A TypeValidationError instance. + */ + static wrap({ + value, + cause + }) { + return _TypeValidationError2.isInstance(cause) && cause.value === value ? cause : new _TypeValidationError2({ value, cause }); + } +}; +_a13 = symbol13; +var TypeValidationError = _TypeValidationError; +var name13 = "AI_UnsupportedFunctionalityError"; +var marker14 = `vercel.ai.error.${name13}`; +var symbol14 = Symbol.for(marker14); +var _a14; +var UnsupportedFunctionalityError = class extends AISDKError { + constructor({ + functionality, + message = `'${functionality}' functionality not supported.` + }) { + super({ name: name13, message }); + this[_a14] = true; + this.functionality = functionality; + } + static isInstance(error) { + return AISDKError.hasMarker(error, marker14); + } +}; +_a14 = symbol14; + +// node_modules/.pnpm/nanoid@3.3.11/node_modules/nanoid/non-secure/index.js +var customAlphabet = (alphabet, defaultSize = 21) => { + return (size = defaultSize) => { + let id = ""; + let i = size | 0; + while (i--) { + id += alphabet[Math.random() * alphabet.length | 0]; + } + return id; + }; +}; + +// node_modules/.pnpm/@ai-sdk+provider-utils@2.2.7_zod@3.25.67/node_modules/@ai-sdk/provider-utils/dist/index.mjs +var import_secure_json_parse = __toESM(require_secure_json_parse(), 1); +function combineHeaders(...headers) { + return headers.reduce( + (combinedHeaders, currentHeaders) => __spreadValues(__spreadValues({}, combinedHeaders), currentHeaders != null ? currentHeaders : {}), + {} + ); +} +function createEventSourceParserStream() { + let buffer = ""; + let event = void 0; + let data = []; + let lastEventId = void 0; + let retry = void 0; + function parseLine(line, controller) { + if (line === "") { + dispatchEvent(controller); + return; + } + if (line.startsWith(":")) { + return; + } + const colonIndex = line.indexOf(":"); + if (colonIndex === -1) { + handleField(line, ""); + return; + } + const field = line.slice(0, colonIndex); + const valueStart = colonIndex + 1; + const value = valueStart < line.length && line[valueStart] === " " ? line.slice(valueStart + 1) : line.slice(valueStart); + handleField(field, value); + } + function dispatchEvent(controller) { + if (data.length > 0) { + controller.enqueue({ + event, + data: data.join("\n"), + id: lastEventId, + retry + }); + data = []; + event = void 0; + retry = void 0; + } + } + function handleField(field, value) { + switch (field) { + case "event": + event = value; + break; + case "data": + data.push(value); + break; + case "id": + lastEventId = value; + break; + case "retry": + const parsedRetry = parseInt(value, 10); + if (!isNaN(parsedRetry)) { + retry = parsedRetry; + } + break; + } + } + return new TransformStream({ + transform(chunk, controller) { + const { lines, incompleteLine } = splitLines(buffer, chunk); + buffer = incompleteLine; + for (let i = 0; i < lines.length; i++) { + parseLine(lines[i], controller); + } + }, + flush(controller) { + parseLine(buffer, controller); + dispatchEvent(controller); + } + }); +} +function splitLines(buffer, chunk) { + const lines = []; + let currentLine = buffer; + for (let i = 0; i < chunk.length; ) { + const char = chunk[i++]; + if (char === "\n") { + lines.push(currentLine); + currentLine = ""; + } else if (char === "\r") { + lines.push(currentLine); + currentLine = ""; + if (chunk[i + 1] === "\n") { + i++; + } + } else { + currentLine += char; + } + } + return { lines, incompleteLine: currentLine }; +} +function extractResponseHeaders(response) { + const headers = {}; + response.headers.forEach((value, key) => { + headers[key] = value; + }); + return headers; +} +var createIdGenerator = ({ + prefix, + size: defaultSize = 16, + alphabet = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz", + separator = "-" +} = {}) => { + const generator = customAlphabet(alphabet, defaultSize); + if (prefix == null) { + return generator; + } + if (alphabet.includes(separator)) { + throw new InvalidArgumentError({ + argument: "separator", + message: `The separator "${separator}" must not be part of the alphabet "${alphabet}".` + }); + } + return (size) => `${prefix}${separator}${generator(size)}`; +}; +var generateId = createIdGenerator(); +function removeUndefinedEntries(record) { + return Object.fromEntries( + Object.entries(record).filter(([_key, value]) => value != null) + ); +} +function isAbortError(error) { + return error instanceof Error && (error.name === "AbortError" || error.name === "TimeoutError"); +} +function loadApiKey({ + apiKey, + environmentVariableName, + apiKeyParameterName = "apiKey", + description +}) { + if (typeof apiKey === "string") { + return apiKey; + } + if (apiKey != null) { + throw new LoadAPIKeyError({ + message: `${description} API key must be a string.` + }); + } + if (typeof process === "undefined") { + throw new LoadAPIKeyError({ + message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter. Environment variables is not supported in this environment.` + }); + } + apiKey = process.env[environmentVariableName]; + if (apiKey == null) { + throw new LoadAPIKeyError({ + message: `${description} API key is missing. Pass it using the '${apiKeyParameterName}' parameter or the ${environmentVariableName} environment variable.` + }); + } + if (typeof apiKey !== "string") { + throw new LoadAPIKeyError({ + message: `${description} API key must be a string. The value of the ${environmentVariableName} environment variable is not a string.` + }); + } + return apiKey; +} +function loadSetting({ + settingValue, + environmentVariableName, + settingName, + description +}) { + if (typeof settingValue === "string") { + return settingValue; + } + if (settingValue != null) { + throw new LoadSettingError({ + message: `${description} setting must be a string.` + }); + } + if (typeof process === "undefined") { + throw new LoadSettingError({ + message: `${description} setting is missing. Pass it using the '${settingName}' parameter. Environment variables is not supported in this environment.` + }); + } + settingValue = process.env[environmentVariableName]; + if (settingValue == null) { + throw new LoadSettingError({ + message: `${description} setting is missing. Pass it using the '${settingName}' parameter or the ${environmentVariableName} environment variable.` + }); + } + if (typeof settingValue !== "string") { + throw new LoadSettingError({ + message: `${description} setting must be a string. The value of the ${environmentVariableName} environment variable is not a string.` + }); + } + return settingValue; +} +var validatorSymbol = Symbol.for("vercel.ai.validator"); +function validator(validate) { + return { [validatorSymbol]: true, validate }; +} +function isValidator(value) { + return typeof value === "object" && value !== null && validatorSymbol in value && value[validatorSymbol] === true && "validate" in value; +} +function asValidator(value) { + return isValidator(value) ? value : zodValidator(value); +} +function zodValidator(zodSchema) { + return validator((value) => { + const result = zodSchema.safeParse(value); + return result.success ? { success: true, value: result.data } : { success: false, error: result.error }; + }); +} +function validateTypes({ + value, + schema: inputSchema +}) { + const result = safeValidateTypes({ value, schema: inputSchema }); + if (!result.success) { + throw TypeValidationError.wrap({ value, cause: result.error }); + } + return result.value; +} +function safeValidateTypes({ + value, + schema +}) { + const validator2 = asValidator(schema); + try { + if (validator2.validate == null) { + return { success: true, value }; + } + const result = validator2.validate(value); + if (result.success) { + return result; + } + return { + success: false, + error: TypeValidationError.wrap({ value, cause: result.error }) + }; + } catch (error) { + return { + success: false, + error: TypeValidationError.wrap({ value, cause: error }) + }; + } +} +function parseJSON({ + text, + schema +}) { + try { + const value = import_secure_json_parse.default.parse(text); + if (schema == null) { + return value; + } + return validateTypes({ value, schema }); + } catch (error) { + if (JSONParseError.isInstance(error) || TypeValidationError.isInstance(error)) { + throw error; + } + throw new JSONParseError({ text, cause: error }); + } +} +function safeParseJSON({ + text, + schema +}) { + try { + const value = import_secure_json_parse.default.parse(text); + if (schema == null) { + return { success: true, value, rawValue: value }; + } + const validationResult = safeValidateTypes({ value, schema }); + return validationResult.success ? __spreadProps(__spreadValues({}, validationResult), { rawValue: value }) : validationResult; + } catch (error) { + return { + success: false, + error: JSONParseError.isInstance(error) ? error : new JSONParseError({ text, cause: error }) + }; + } +} +function isParsableJson(input) { + try { + import_secure_json_parse.default.parse(input); + return true; + } catch (e) { + return false; + } +} +function parseProviderOptions({ + provider, + providerOptions, + schema +}) { + if ((providerOptions == null ? void 0 : providerOptions[provider]) == null) { + return void 0; + } + const parsedProviderOptions = safeValidateTypes({ + value: providerOptions[provider], + schema + }); + if (!parsedProviderOptions.success) { + throw new InvalidArgumentError({ + argument: "providerOptions", + message: `invalid ${provider} provider options`, + cause: parsedProviderOptions.error + }); + } + return parsedProviderOptions.value; +} +var getOriginalFetch2 = () => globalThis.fetch; +var postJsonToApi = (_0) => __async(null, [_0], function* ({ + url, + headers, + body, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 +}) { + return postToApi({ + url, + headers: __spreadValues({ + "Content-Type": "application/json" + }, headers), + body: { + content: JSON.stringify(body), + values: body + }, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 + }); +}); +var postFormDataToApi = (_0) => __async(null, [_0], function* ({ + url, + headers, + formData, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 +}) { + return postToApi({ + url, + headers, + body: { + content: formData, + values: Object.fromEntries(formData.entries()) + }, + failedResponseHandler, + successfulResponseHandler, + abortSignal, + fetch: fetch2 + }); +}); +var postToApi = (_0) => __async(null, [_0], function* ({ + url, + headers = {}, + body, + successfulResponseHandler, + failedResponseHandler, + abortSignal, + fetch: fetch2 = getOriginalFetch2() +}) { + try { + const response = yield fetch2(url, { + method: "POST", + headers: removeUndefinedEntries(headers), + body: body.content, + signal: abortSignal + }); + const responseHeaders = extractResponseHeaders(response); + if (!response.ok) { + let errorInformation; + try { + errorInformation = yield failedResponseHandler({ + response, + url, + requestBodyValues: body.values + }); + } catch (error) { + if (isAbortError(error) || APICallError.isInstance(error)) { + throw error; + } + throw new APICallError({ + message: "Failed to process error response", + cause: error, + statusCode: response.status, + url, + responseHeaders, + requestBodyValues: body.values + }); + } + throw errorInformation.value; + } + try { + return yield successfulResponseHandler({ + response, + url, + requestBodyValues: body.values + }); + } catch (error) { + if (error instanceof Error) { + if (isAbortError(error) || APICallError.isInstance(error)) { + throw error; + } + } + throw new APICallError({ + message: "Failed to process successful response", + cause: error, + statusCode: response.status, + url, + responseHeaders, + requestBodyValues: body.values + }); + } + } catch (error) { + if (isAbortError(error)) { + throw error; + } + if (error instanceof TypeError && error.message === "fetch failed") { + const cause = error.cause; + if (cause != null) { + throw new APICallError({ + message: `Cannot connect to API: ${cause.message}`, + cause, + url, + requestBodyValues: body.values, + isRetryable: true + // retry when network error + }); + } + } + throw error; + } +}); +function resolve(value) { + return __async(this, null, function* () { + if (typeof value === "function") { + value = value(); + } + return Promise.resolve(value); + }); +} +var createJsonErrorResponseHandler = ({ + errorSchema, + errorToMessage: errorToMessage2, + isRetryable +}) => (_0) => __async(null, [_0], function* ({ response, url, requestBodyValues }) { + const responseBody = yield response.text(); + const responseHeaders = extractResponseHeaders(response); + if (responseBody.trim() === "") { + return { + responseHeaders, + value: new APICallError({ + message: response.statusText, + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody, + isRetryable: isRetryable == null ? void 0 : isRetryable(response) + }) + }; + } + try { + const parsedError = parseJSON({ + text: responseBody, + schema: errorSchema + }); + return { + responseHeaders, + value: new APICallError({ + message: errorToMessage2(parsedError), + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody, + data: parsedError, + isRetryable: isRetryable == null ? void 0 : isRetryable(response, parsedError) + }) + }; + } catch (parseError) { + return { + responseHeaders, + value: new APICallError({ + message: response.statusText, + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody, + isRetryable: isRetryable == null ? void 0 : isRetryable(response) + }) + }; + } +}); +var createEventSourceResponseHandler = (chunkSchema2) => (_0) => __async(null, [_0], function* ({ response }) { + const responseHeaders = extractResponseHeaders(response); + if (response.body == null) { + throw new EmptyResponseBodyError({}); + } + return { + responseHeaders, + value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(createEventSourceParserStream()).pipeThrough( + new TransformStream({ + transform({ data }, controller) { + if (data === "[DONE]") { + return; + } + controller.enqueue( + safeParseJSON({ + text: data, + schema: chunkSchema2 + }) + ); + } + }) + ) + }; +}); +var createJsonResponseHandler = (responseSchema2) => (_0) => __async(null, [_0], function* ({ response, url, requestBodyValues }) { + const responseBody = yield response.text(); + const parsedResult = safeParseJSON({ + text: responseBody, + schema: responseSchema2 + }); + const responseHeaders = extractResponseHeaders(response); + if (!parsedResult.success) { + throw new APICallError({ + message: "Invalid JSON response", + cause: parsedResult.error, + statusCode: response.status, + responseHeaders, + responseBody, + url, + requestBodyValues + }); + } + return { + responseHeaders, + value: parsedResult.value, + rawValue: parsedResult.rawValue + }; +}); +var createBinaryResponseHandler = () => (_0) => __async(null, [_0], function* ({ response, url, requestBodyValues }) { + const responseHeaders = extractResponseHeaders(response); + if (!response.body) { + throw new APICallError({ + message: "Response body is empty", + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody: void 0 + }); + } + try { + const buffer = yield response.arrayBuffer(); + return { + responseHeaders, + value: new Uint8Array(buffer) + }; + } catch (error) { + throw new APICallError({ + message: "Failed to read response as array buffer", + url, + requestBodyValues, + statusCode: response.status, + responseHeaders, + responseBody: void 0, + cause: error + }); + } +}); +var { btoa, atob } = globalThis; +function convertBase64ToUint8Array(base64String) { + const base64Url = base64String.replace(/-/g, "+").replace(/_/g, "/"); + const latin1string = atob(base64Url); + return Uint8Array.from(latin1string, (byte) => byte.codePointAt(0)); +} +function convertUint8ArrayToBase64(array) { + let latin1string = ""; + for (let i = 0; i < array.length; i++) { + latin1string += String.fromCodePoint(array[i]); + } + return btoa(latin1string); +} +function withoutTrailingSlash(url) { + return url == null ? void 0 : url.replace(/\/$/, ""); +} + +// node_modules/.pnpm/@ai-sdk+openai@1.3.21_zod@3.25.67/node_modules/@ai-sdk/openai/dist/index.mjs +var import_zod2 = require("zod"); +var import_zod3 = require("zod"); +var import_zod4 = require("zod"); +var import_zod5 = require("zod"); +var import_zod6 = require("zod"); +var import_zod7 = require("zod"); +var import_zod8 = require("zod"); +var import_zod9 = require("zod"); +var import_zod10 = require("zod"); +function convertToOpenAIChatMessages({ + prompt, + useLegacyFunctionCalling = false, + systemMessageMode = "system" +}) { + const messages = []; + const warnings = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + switch (systemMessageMode) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "developer": { + messages.push({ role: "developer", content }); + break; + } + case "remove": { + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + } + default: { + const _exhaustiveCheck = systemMessageMode; + throw new Error( + `Unsupported system message mode: ${_exhaustiveCheck}` + ); + } + } + break; + } + case "user": { + if (content.length === 1 && content[0].type === "text") { + messages.push({ role: "user", content: content[0].text }); + break; + } + messages.push({ + role: "user", + content: content.map((part, index) => { + var _a15, _b, _c, _d; + switch (part.type) { + case "text": { + return { type: "text", text: part.text }; + } + case "image": { + return { + type: "image_url", + image_url: { + url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`, + // OpenAI specific extension: image detail + detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail + } + }; + } + case "file": { + if (part.data instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "'File content parts with URL data' functionality not supported." + }); + } + switch (part.mimeType) { + case "audio/wav": { + return { + type: "input_audio", + input_audio: { data: part.data, format: "wav" } + }; + } + case "audio/mp3": + case "audio/mpeg": { + return { + type: "input_audio", + input_audio: { data: part.data, format: "mp3" } + }; + } + case "application/pdf": { + return { + type: "file", + file: { + filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${part.data}` + } + }; + } + default: { + throw new UnsupportedFunctionalityError({ + functionality: `File content part type ${part.mimeType} in user messages` + }); + } + } + } + } + }) + }); + break; + } + case "assistant": { + let text = ""; + const toolCalls = []; + for (const part of content) { + switch (part.type) { + case "text": { + text += part.text; + break; + } + case "tool-call": { + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.args) + } + }); + break; + } + } + } + if (useLegacyFunctionCalling) { + if (toolCalls.length > 1) { + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling with multiple tool calls in one message" + }); + } + messages.push({ + role: "assistant", + content: text, + function_call: toolCalls.length > 0 ? toolCalls[0].function : void 0 + }); + } else { + messages.push({ + role: "assistant", + content: text, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + } + break; + } + case "tool": { + for (const toolResponse of content) { + if (useLegacyFunctionCalling) { + messages.push({ + role: "function", + name: toolResponse.toolName, + content: JSON.stringify(toolResponse.result) + }); + } else { + messages.push({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: JSON.stringify(toolResponse.result) + }); + } + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return { messages, warnings }; +} +function mapOpenAIChatLogProbsOutput(logprobs) { + var _a15, _b; + return (_b = (_a15 = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a15.map(({ token, logprob, top_logprobs }) => ({ + token, + logprob, + topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({ + token: token2, + logprob: logprob2 + })) : [] + }))) != null ? _b : void 0; +} +function mapOpenAIFinishReason(finishReason) { + switch (finishReason) { + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "unknown"; + } +} +var openaiErrorDataSchema = import_zod3.z.object({ + error: import_zod3.z.object({ + message: import_zod3.z.string(), + // The additional information below is handled loosely to support + // OpenAI-compatible providers that have slightly different error + // responses: + type: import_zod3.z.string().nullish(), + param: import_zod3.z.any().nullish(), + code: import_zod3.z.union([import_zod3.z.string(), import_zod3.z.number()]).nullish() + }) +}); +var openaiFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: openaiErrorDataSchema, + errorToMessage: (data) => data.error.message +}); +function getResponseMetadata({ + id, + model, + created +}) { + return { + id: id != null ? id : void 0, + modelId: model != null ? model : void 0, + timestamp: created != null ? new Date(created * 1e3) : void 0 + }; +} +function prepareTools({ + mode, + useLegacyFunctionCalling = false, + structuredOutputs +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + if (useLegacyFunctionCalling) { + const openaiFunctions = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + openaiFunctions.push({ + name: tool.name, + description: tool.description, + parameters: tool.parameters + }); + } + } + if (toolChoice == null) { + return { + functions: openaiFunctions, + function_call: void 0, + toolWarnings + }; + } + const type2 = toolChoice.type; + switch (type2) { + case "auto": + case "none": + case void 0: + return { + functions: openaiFunctions, + function_call: void 0, + toolWarnings + }; + case "required": + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling and toolChoice: required" + }); + default: + return { + functions: openaiFunctions, + function_call: { name: toolChoice.toolName }, + toolWarnings + }; + } + } + const openaiTools2 = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + openaiTools2.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + strict: structuredOutputs ? true : void 0 + } + }); + } + } + if (toolChoice == null) { + return { tools: openaiTools2, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: openaiTools2, tool_choice: type, toolWarnings }; + case "tool": + return { + tools: openaiTools2, + tool_choice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var OpenAIChatLanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get supportsStructuredOutputs() { + var _a15; + return (_a15 = this.settings.structuredOutputs) != null ? _a15 : isReasoningModel(this.modelId); + } + get defaultObjectGenerationMode() { + if (isAudioModel(this.modelId)) { + return "tool"; + } + return this.supportsStructuredOutputs ? "json" : "tool"; + } + get provider() { + return this.config.provider; + } + get supportsImageUrls() { + return !this.settings.downloadImages; + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format schema is only supported with structuredOutputs" + }); + } + const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling; + if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) { + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling with parallelToolCalls" + }); + } + if (useLegacyFunctionCalling && this.supportsStructuredOutputs) { + throw new UnsupportedFunctionalityError({ + functionality: "structuredOutputs with useLegacyFunctionCalling" + }); + } + const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages( + { + prompt, + useLegacyFunctionCalling, + systemMessageMode: getSystemMessageMode(this.modelId) + } + ); + warnings.push(...messageWarnings); + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + logit_bias: this.settings.logitBias, + logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0, + top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0, + user: this.settings.user, + parallel_tool_calls: this.settings.parallelToolCalls, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs && responseFormat.schema != null ? { + type: "json_schema", + json_schema: { + schema: responseFormat.schema, + strict: true, + name: (_a15 = responseFormat.name) != null ? _a15 : "response", + description: responseFormat.description + } + } : { type: "json_object" } : void 0, + stop: stopSequences, + seed, + // openai specific settings: + // TODO remove in next major version; we auto-map maxTokens now + max_completion_tokens: (_b = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _b.maxCompletionTokens, + store: (_c = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _c.store, + metadata: (_d = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _d.metadata, + prediction: (_e = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _e.prediction, + reasoning_effort: (_g = (_f = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _f.reasoningEffort) != null ? _g : this.settings.reasoningEffort, + // messages: + messages + }; + if (isReasoningModel(this.modelId)) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (baseArgs.top_p != null) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topP", + details: "topP is not supported for reasoning models" + }); + } + if (baseArgs.frequency_penalty != null) { + baseArgs.frequency_penalty = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty", + details: "frequencyPenalty is not supported for reasoning models" + }); + } + if (baseArgs.presence_penalty != null) { + baseArgs.presence_penalty = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty", + details: "presencePenalty is not supported for reasoning models" + }); + } + if (baseArgs.logit_bias != null) { + baseArgs.logit_bias = void 0; + warnings.push({ + type: "other", + message: "logitBias is not supported for reasoning models" + }); + } + if (baseArgs.logprobs != null) { + baseArgs.logprobs = void 0; + warnings.push({ + type: "other", + message: "logprobs is not supported for reasoning models" + }); + } + if (baseArgs.top_logprobs != null) { + baseArgs.top_logprobs = void 0; + warnings.push({ + type: "other", + message: "topLogprobs is not supported for reasoning models" + }); + } + if (baseArgs.max_tokens != null) { + if (baseArgs.max_completion_tokens == null) { + baseArgs.max_completion_tokens = baseArgs.max_tokens; + } + baseArgs.max_tokens = void 0; + } + } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for the search preview models and has been removed." + }); + } + } + switch (type) { + case "regular": { + const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools({ + mode, + useLegacyFunctionCalling, + structuredOutputs: this.supportsStructuredOutputs + }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools, + tool_choice, + functions, + function_call + }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: this.supportsStructuredOutputs && mode.schema != null ? { + type: "json_schema", + json_schema: { + schema: mode.schema, + strict: true, + name: (_h = mode.name) != null ? _h : "response", + description: mode.description + } + } : { type: "json_object" } + }), + warnings + }; + } + case "object-tool": { + return { + args: useLegacyFunctionCalling ? __spreadProps(__spreadValues({}, baseArgs), { + function_call: { + name: mode.tool.name + }, + functions: [ + { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters + } + ] + }) : __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { + type: "function", + function: { name: mode.tool.name } + }, + tools: [ + { + type: "function", + function: { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters, + strict: this.supportsStructuredOutputs ? true : void 0 + } + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g, _h; + const { args: body, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiChatResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = body, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = response.choices[0]; + const completionTokenDetails = (_a15 = response.usage) == null ? void 0 : _a15.completion_tokens_details; + const promptTokenDetails = (_b = response.usage) == null ? void 0 : _b.prompt_tokens_details; + const providerMetadata = { openai: {} }; + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null) { + providerMetadata.openai.reasoningTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { + providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { + providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; + } + if ((promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null) { + providerMetadata.openai.cachedPromptTokens = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens; + } + return { + text: (_c = choice.message.content) != null ? _c : void 0, + toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [ + { + toolCallType: "function", + toolCallId: generateId(), + toolName: choice.message.function_call.name, + args: choice.message.function_call.arguments + } + ] : (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => { + var _a22; + return { + toolCallType: "function", + toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }; + }), + finishReason: mapOpenAIFinishReason(choice.finish_reason), + usage: { + promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : NaN, + completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : NaN + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + request: { body: JSON.stringify(body) }, + response: getResponseMetadata(response), + warnings, + logprobs: mapOpenAIChatLogProbsOutput(choice.logprobs), + providerMetadata + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + if (this.settings.simulateStreaming) { + const result = yield this.doGenerate(options); + const simulatedStream = new ReadableStream({ + start(controller) { + controller.enqueue(__spreadValues({ type: "response-metadata" }, result.response)); + if (result.text) { + controller.enqueue({ + type: "text-delta", + textDelta: result.text + }); + } + if (result.toolCalls) { + for (const toolCall of result.toolCalls) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + argsTextDelta: toolCall.args + }); + controller.enqueue(__spreadValues({ + type: "tool-call" + }, toolCall)); + } + } + controller.enqueue({ + type: "finish", + finishReason: result.finishReason, + usage: result.usage, + logprobs: result.logprobs, + providerMetadata: result.providerMetadata + }); + controller.close(); + } + }); + return { + stream: simulatedStream, + rawCall: result.rawCall, + rawResponse: result.rawResponse, + warnings: result.warnings + }; + } + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0 + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + openaiChatChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + const toolCalls = []; + let finishReason = "unknown"; + let usage = { + promptTokens: void 0, + completionTokens: void 0 + }; + let logprobs; + let isFirstChunk = true; + const { useLegacyFunctionCalling } = this.settings; + const providerMetadata = { openai: {} }; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata(value))); + } + if (value.usage != null) { + const { + prompt_tokens, + completion_tokens, + prompt_tokens_details, + completion_tokens_details + } = value.usage; + usage = { + promptTokens: prompt_tokens != null ? prompt_tokens : void 0, + completionTokens: completion_tokens != null ? completion_tokens : void 0 + }; + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) { + providerMetadata.openai.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) { + providerMetadata.openai.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) { + providerMetadata.openai.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens; + } + if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) { + providerMetadata.openai.cachedPromptTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens; + } + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAIFinishReason(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + if (delta.content != null) { + controller.enqueue({ + type: "text-delta", + textDelta: delta.content + }); + } + const mappedLogprobs = mapOpenAIChatLogProbsOutput( + choice == null ? void 0 : choice.logprobs + ); + if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) { + if (logprobs === void 0) logprobs = []; + logprobs.push(...mappedLogprobs); + } + const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [ + { + type: "function", + id: generateId(), + function: delta.function_call, + index: 0 + } + ] : delta.tool_calls; + if (mappedToolCalls != null) { + for (const toolCallDelta of mappedToolCalls) { + const index = toolCallDelta.index; + if (toolCalls[index] == null) { + if (toolCallDelta.type !== "function") { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function' type.` + }); + } + if (toolCallDelta.id == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'id' to be a string.` + }); + } + if (((_a16 = toolCallDelta.function) == null ? void 0 : _a16.name) == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function.name' to be a string.` + }); + } + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: (_b = toolCallDelta.function.arguments) != null ? _b : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) { + if (toolCall2.function.arguments.length > 0) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall2.id, + toolName: toolCall2.function.name, + argsTextDelta: toolCall2.function.arguments + }); + } + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_e = toolCall2.id) != null ? _e : generateId(), + toolName: toolCall2.function.name, + args: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (toolCall.hasFinished) { + continue; + } + if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) { + toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : ""; + } + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : "" + }); + if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_l = toolCall.id) != null ? _l : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + }, + flush(controller) { + var _a16, _b; + controller.enqueue(__spreadValues({ + type: "finish", + finishReason, + logprobs, + usage: { + promptTokens: (_a16 = usage.promptTokens) != null ? _a16 : NaN, + completionTokens: (_b = usage.completionTokens) != null ? _b : NaN + } + }, providerMetadata != null ? { providerMetadata } : {})); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +var openaiTokenUsageSchema = import_zod2.z.object({ + prompt_tokens: import_zod2.z.number().nullish(), + completion_tokens: import_zod2.z.number().nullish(), + prompt_tokens_details: import_zod2.z.object({ + cached_tokens: import_zod2.z.number().nullish() + }).nullish(), + completion_tokens_details: import_zod2.z.object({ + reasoning_tokens: import_zod2.z.number().nullish(), + accepted_prediction_tokens: import_zod2.z.number().nullish(), + rejected_prediction_tokens: import_zod2.z.number().nullish() + }).nullish() +}).nullish(); +var openaiChatResponseSchema = import_zod2.z.object({ + id: import_zod2.z.string().nullish(), + created: import_zod2.z.number().nullish(), + model: import_zod2.z.string().nullish(), + choices: import_zod2.z.array( + import_zod2.z.object({ + message: import_zod2.z.object({ + role: import_zod2.z.literal("assistant").nullish(), + content: import_zod2.z.string().nullish(), + function_call: import_zod2.z.object({ + arguments: import_zod2.z.string(), + name: import_zod2.z.string() + }).nullish(), + tool_calls: import_zod2.z.array( + import_zod2.z.object({ + id: import_zod2.z.string().nullish(), + type: import_zod2.z.literal("function"), + function: import_zod2.z.object({ + name: import_zod2.z.string(), + arguments: import_zod2.z.string() + }) + }) + ).nullish() + }), + index: import_zod2.z.number(), + logprobs: import_zod2.z.object({ + content: import_zod2.z.array( + import_zod2.z.object({ + token: import_zod2.z.string(), + logprob: import_zod2.z.number(), + top_logprobs: import_zod2.z.array( + import_zod2.z.object({ + token: import_zod2.z.string(), + logprob: import_zod2.z.number() + }) + ) + }) + ).nullable() + }).nullish(), + finish_reason: import_zod2.z.string().nullish() + }) + ), + usage: openaiTokenUsageSchema +}); +var openaiChatChunkSchema = import_zod2.z.union([ + import_zod2.z.object({ + id: import_zod2.z.string().nullish(), + created: import_zod2.z.number().nullish(), + model: import_zod2.z.string().nullish(), + choices: import_zod2.z.array( + import_zod2.z.object({ + delta: import_zod2.z.object({ + role: import_zod2.z.enum(["assistant"]).nullish(), + content: import_zod2.z.string().nullish(), + function_call: import_zod2.z.object({ + name: import_zod2.z.string().optional(), + arguments: import_zod2.z.string().optional() + }).nullish(), + tool_calls: import_zod2.z.array( + import_zod2.z.object({ + index: import_zod2.z.number(), + id: import_zod2.z.string().nullish(), + type: import_zod2.z.literal("function").nullish(), + function: import_zod2.z.object({ + name: import_zod2.z.string().nullish(), + arguments: import_zod2.z.string().nullish() + }) + }) + ).nullish() + }).nullish(), + logprobs: import_zod2.z.object({ + content: import_zod2.z.array( + import_zod2.z.object({ + token: import_zod2.z.string(), + logprob: import_zod2.z.number(), + top_logprobs: import_zod2.z.array( + import_zod2.z.object({ + token: import_zod2.z.string(), + logprob: import_zod2.z.number() + }) + ) + }) + ).nullable() + }).nullish(), + finish_reason: import_zod2.z.string().nullish(), + index: import_zod2.z.number() + }) + ), + usage: openaiTokenUsageSchema + }), + openaiErrorDataSchema +]); +function isReasoningModel(modelId) { + return modelId.startsWith("o"); +} +function isAudioModel(modelId) { + return modelId.startsWith("gpt-4o-audio-preview"); +} +function getSystemMessageMode(modelId) { + var _a15, _b; + if (!isReasoningModel(modelId)) { + return "system"; + } + return (_b = (_a15 = reasoningModels[modelId]) == null ? void 0 : _a15.systemMessageMode) != null ? _b : "developer"; +} +var reasoningModels = { + "o1-mini": { + systemMessageMode: "remove" + }, + "o1-mini-2024-09-12": { + systemMessageMode: "remove" + }, + "o1-preview": { + systemMessageMode: "remove" + }, + "o1-preview-2024-09-12": { + systemMessageMode: "remove" + }, + o3: { + systemMessageMode: "developer" + }, + "o3-2025-04-16": { + systemMessageMode: "developer" + }, + "o3-mini": { + systemMessageMode: "developer" + }, + "o3-mini-2025-01-31": { + systemMessageMode: "developer" + }, + "o4-mini": { + systemMessageMode: "developer" + }, + "o4-mini-2025-04-16": { + systemMessageMode: "developer" + } +}; +function convertToOpenAICompletionPrompt({ + prompt, + inputFormat, + user = "user", + assistant = "assistant" +}) { + if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") { + return { prompt: prompt[0].content[0].text }; + } + let text = ""; + if (prompt[0].role === "system") { + text += `${prompt[0].content} + +`; + prompt = prompt.slice(1); + } + for (const { role, content } of prompt) { + switch (role) { + case "system": { + throw new InvalidPromptError({ + message: "Unexpected system message in prompt: ${content}", + prompt + }); + } + case "user": { + const userMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "image": { + throw new UnsupportedFunctionalityError({ + functionality: "images" + }); + } + } + }).join(""); + text += `${user}: +${userMessage} + +`; + break; + } + case "assistant": { + const assistantMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "tool-call": { + throw new UnsupportedFunctionalityError({ + functionality: "tool-call messages" + }); + } + } + }).join(""); + text += `${assistant}: +${assistantMessage} + +`; + break; + } + case "tool": { + throw new UnsupportedFunctionalityError({ + functionality: "tool messages" + }); + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + text += `${assistant}: +`; + return { + prompt: text, + stopSequences: [` +${user}:`] + }; +} +function mapOpenAICompletionLogProbs(logprobs) { + return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => ({ + token, + logprob: logprobs.token_logprobs[index], + topLogprobs: logprobs.top_logprobs ? Object.entries(logprobs.top_logprobs[index]).map( + ([token2, logprob]) => ({ + token: token2, + logprob + }) + ) : [] + })); +} +var OpenAICompletionLanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = void 0; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + getArgs({ + mode, + inputFormat, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences: userStopSequences, + responseFormat, + seed + }) { + var _a15; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (responseFormat != null && responseFormat.type !== "text") { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format is not supported." + }); + } + const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt({ prompt, inputFormat }); + const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + echo: this.settings.echo, + logit_bias: this.settings.logitBias, + logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0, + suffix: this.settings.suffix, + user: this.settings.user, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + seed, + // prompt: + prompt: completionPrompt, + // stop sequences: + stop: stop.length > 0 ? stop : void 0 + }; + switch (type) { + case "regular": { + if ((_a15 = mode.tools) == null ? void 0 : _a15.length) { + throw new UnsupportedFunctionalityError({ + functionality: "tools" + }); + } + if (mode.toolChoice) { + throw new UnsupportedFunctionalityError({ + functionality: "toolChoice" + }); + } + return { args: baseArgs, warnings }; + } + case "object-json": { + throw new UnsupportedFunctionalityError({ + functionality: "object-json mode" + }); + } + case "object-tool": { + throw new UnsupportedFunctionalityError({ + functionality: "object-tool mode" + }); + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiCompletionResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { prompt: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["prompt"]); + const choice = response.choices[0]; + return { + text: choice.text, + usage: { + promptTokens: response.usage.prompt_tokens, + completionTokens: response.usage.completion_tokens + }, + finishReason: mapOpenAIFinishReason(choice.finish_reason), + logprobs: mapOpenAICompletionLogProbs(choice.logprobs), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + response: getResponseMetadata(response), + warnings, + request: { body: JSON.stringify(args) } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0 + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + openaiCompletionChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { prompt: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["prompt"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + let logprobs; + let isFirstChunk = true; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata(value))); + } + if (value.usage != null) { + usage = { + promptTokens: value.usage.prompt_tokens, + completionTokens: value.usage.completion_tokens + }; + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAIFinishReason(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.text) != null) { + controller.enqueue({ + type: "text-delta", + textDelta: choice.text + }); + } + const mappedLogprobs = mapOpenAICompletionLogProbs( + choice == null ? void 0 : choice.logprobs + ); + if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) { + if (logprobs === void 0) logprobs = []; + logprobs.push(...mappedLogprobs); + } + }, + flush(controller) { + controller.enqueue({ + type: "finish", + finishReason, + logprobs, + usage + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body: JSON.stringify(body) } + }; + }); + } +}; +var openaiCompletionResponseSchema = import_zod4.z.object({ + id: import_zod4.z.string().nullish(), + created: import_zod4.z.number().nullish(), + model: import_zod4.z.string().nullish(), + choices: import_zod4.z.array( + import_zod4.z.object({ + text: import_zod4.z.string(), + finish_reason: import_zod4.z.string(), + logprobs: import_zod4.z.object({ + tokens: import_zod4.z.array(import_zod4.z.string()), + token_logprobs: import_zod4.z.array(import_zod4.z.number()), + top_logprobs: import_zod4.z.array(import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number())).nullable() + }).nullish() + }) + ), + usage: import_zod4.z.object({ + prompt_tokens: import_zod4.z.number(), + completion_tokens: import_zod4.z.number() + }) +}); +var openaiCompletionChunkSchema = import_zod4.z.union([ + import_zod4.z.object({ + id: import_zod4.z.string().nullish(), + created: import_zod4.z.number().nullish(), + model: import_zod4.z.string().nullish(), + choices: import_zod4.z.array( + import_zod4.z.object({ + text: import_zod4.z.string(), + finish_reason: import_zod4.z.string().nullish(), + index: import_zod4.z.number(), + logprobs: import_zod4.z.object({ + tokens: import_zod4.z.array(import_zod4.z.string()), + token_logprobs: import_zod4.z.array(import_zod4.z.number()), + top_logprobs: import_zod4.z.array(import_zod4.z.record(import_zod4.z.string(), import_zod4.z.number())).nullable() + }).nullish() + }) + ), + usage: import_zod4.z.object({ + prompt_tokens: import_zod4.z.number(), + completion_tokens: import_zod4.z.number() + }).nullish() + }), + openaiErrorDataSchema +]); +var OpenAIEmbeddingModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + var _a15; + return (_a15 = this.settings.maxEmbeddingsPerCall) != null ? _a15 : 2048; + } + get supportsParallelCalls() { + var _a15; + return (_a15 = this.settings.supportsParallelCalls) != null ? _a15 : true; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + values, + headers, + abortSignal + }) { + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + } + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/embeddings", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + input: values, + encoding_format: "float", + dimensions: this.settings.dimensions, + user: this.settings.user + }, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiTextEmbeddingResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + embeddings: response.data.map((item) => item.embedding), + usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, + rawResponse: { headers: responseHeaders } + }; + }); + } +}; +var openaiTextEmbeddingResponseSchema = import_zod5.z.object({ + data: import_zod5.z.array(import_zod5.z.object({ embedding: import_zod5.z.array(import_zod5.z.number()) })), + usage: import_zod5.z.object({ prompt_tokens: import_zod5.z.number() }).nullish() +}); +var modelMaxImagesPerCall = { + "dall-e-3": 1, + "dall-e-2": 10, + "gpt-image-1": 10 +}; +var hasDefaultResponseFormat = /* @__PURE__ */ new Set(["gpt-image-1"]); +var OpenAIImageModel = class { + constructor(modelId, settings, config) { + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v1"; + } + get maxImagesPerCall() { + var _a15, _b; + return (_b = (_a15 = this.settings.maxImagesPerCall) != null ? _a15 : modelMaxImagesPerCall[this.modelId]) != null ? _b : 1; + } + get provider() { + return this.config.provider; + } + doGenerate(_0) { + return __async(this, arguments, function* ({ + prompt, + n, + size, + aspectRatio, + seed, + providerOptions, + headers, + abortSignal + }) { + var _a15, _b, _c, _d; + const warnings = []; + if (aspectRatio != null) { + warnings.push({ + type: "unsupported-setting", + setting: "aspectRatio", + details: "This model does not support aspect ratio. Use `size` instead." + }); + } + if (seed != null) { + warnings.push({ type: "unsupported-setting", setting: "seed" }); + } + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { value: response, responseHeaders } = yield postJsonToApi({ + url: this.config.url({ + path: "/images/generations", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: __spreadValues(__spreadValues({ + model: this.modelId, + prompt, + n, + size + }, (_d = providerOptions.openai) != null ? _d : {}), !hasDefaultResponseFormat.has(this.modelId) ? { response_format: "b64_json" } : {}), + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiImageResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.data.map((item) => item.b64_json), + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + } + }; + }); + } +}; +var openaiImageResponseSchema = import_zod6.z.object({ + data: import_zod6.z.array(import_zod6.z.object({ b64_json: import_zod6.z.string() })) +}); +var openAIProviderOptionsSchema = import_zod7.z.object({ + include: import_zod7.z.array(import_zod7.z.string()).nullish(), + language: import_zod7.z.string().nullish(), + prompt: import_zod7.z.string().nullish(), + temperature: import_zod7.z.number().min(0).max(1).nullish().default(0), + timestampGranularities: import_zod7.z.array(import_zod7.z.enum(["word", "segment"])).nullish().default(["segment"]) +}); +var languageMap = { + afrikaans: "af", + arabic: "ar", + armenian: "hy", + azerbaijani: "az", + belarusian: "be", + bosnian: "bs", + bulgarian: "bg", + catalan: "ca", + chinese: "zh", + croatian: "hr", + czech: "cs", + danish: "da", + dutch: "nl", + english: "en", + estonian: "et", + finnish: "fi", + french: "fr", + galician: "gl", + german: "de", + greek: "el", + hebrew: "he", + hindi: "hi", + hungarian: "hu", + icelandic: "is", + indonesian: "id", + italian: "it", + japanese: "ja", + kannada: "kn", + kazakh: "kk", + korean: "ko", + latvian: "lv", + lithuanian: "lt", + macedonian: "mk", + malay: "ms", + marathi: "mr", + maori: "mi", + nepali: "ne", + norwegian: "no", + persian: "fa", + polish: "pl", + portuguese: "pt", + romanian: "ro", + russian: "ru", + serbian: "sr", + slovak: "sk", + slovenian: "sl", + spanish: "es", + swahili: "sw", + swedish: "sv", + tagalog: "tl", + tamil: "ta", + thai: "th", + turkish: "tr", + ukrainian: "uk", + urdu: "ur", + vietnamese: "vi", + welsh: "cy" +}; +var OpenAITranscriptionModel = class { + constructor(modelId, config) { + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v1"; + } + get provider() { + return this.config.provider; + } + getArgs({ + audio, + mediaType, + providerOptions + }) { + var _a15, _b, _c, _d, _e; + const warnings = []; + const openAIOptions = parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openAIProviderOptionsSchema + }); + const formData = new FormData(); + const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]); + formData.append("model", this.modelId); + formData.append("file", new File([blob], "audio", { type: mediaType })); + if (openAIOptions) { + const transcriptionModelOptions = { + include: (_a15 = openAIOptions.include) != null ? _a15 : void 0, + language: (_b = openAIOptions.language) != null ? _b : void 0, + prompt: (_c = openAIOptions.prompt) != null ? _c : void 0, + temperature: (_d = openAIOptions.temperature) != null ? _d : void 0, + timestamp_granularities: (_e = openAIOptions.timestampGranularities) != null ? _e : void 0 + }; + for (const key in transcriptionModelOptions) { + const value = transcriptionModelOptions[key]; + if (value !== void 0) { + formData.append(key, String(value)); + } + } + } + return { + formData, + warnings + }; + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f; + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { formData, warnings } = this.getArgs(options); + const { + value: response, + responseHeaders, + rawValue: rawResponse + } = yield postFormDataToApi({ + url: this.config.url({ + path: "/audio/transcriptions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + formData, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiTranscriptionResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const language = response.language != null && response.language in languageMap ? languageMap[response.language] : void 0; + return { + text: response.text, + segments: (_e = (_d = response.words) == null ? void 0 : _d.map((word) => ({ + text: word.word, + startSecond: word.start, + endSecond: word.end + }))) != null ? _e : [], + language, + durationInSeconds: (_f = response.duration) != null ? _f : void 0, + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + }); + } +}; +var openaiTranscriptionResponseSchema = import_zod7.z.object({ + text: import_zod7.z.string(), + language: import_zod7.z.string().nullish(), + duration: import_zod7.z.number().nullish(), + words: import_zod7.z.array( + import_zod7.z.object({ + word: import_zod7.z.string(), + start: import_zod7.z.number(), + end: import_zod7.z.number() + }) + ).nullish() +}); +function convertToOpenAIResponsesMessages({ + prompt, + systemMessageMode +}) { + const messages = []; + const warnings = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + switch (systemMessageMode) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "developer": { + messages.push({ role: "developer", content }); + break; + } + case "remove": { + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + } + default: { + const _exhaustiveCheck = systemMessageMode; + throw new Error( + `Unsupported system message mode: ${_exhaustiveCheck}` + ); + } + } + break; + } + case "user": { + messages.push({ + role: "user", + content: content.map((part, index) => { + var _a15, _b, _c, _d; + switch (part.type) { + case "text": { + return { type: "input_text", text: part.text }; + } + case "image": { + return { + type: "input_image", + image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`, + // OpenAI specific extension: image detail + detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail + }; + } + case "file": { + if (part.data instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "File URLs in user messages" + }); + } + switch (part.mimeType) { + case "application/pdf": { + return { + type: "input_file", + filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${part.data}` + }; + } + default: { + throw new UnsupportedFunctionalityError({ + functionality: "Only PDF files are supported in user messages" + }); + } + } + } + } + }) + }); + break; + } + case "assistant": { + for (const part of content) { + switch (part.type) { + case "text": { + messages.push({ + role: "assistant", + content: [{ type: "output_text", text: part.text }] + }); + break; + } + case "tool-call": { + messages.push({ + type: "function_call", + call_id: part.toolCallId, + name: part.toolName, + arguments: JSON.stringify(part.args) + }); + break; + } + } + } + break; + } + case "tool": { + for (const part of content) { + messages.push({ + type: "function_call_output", + call_id: part.toolCallId, + output: JSON.stringify(part.result) + }); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return { messages, warnings }; +} +function mapOpenAIResponseFinishReason({ + finishReason, + hasToolCalls +}) { + switch (finishReason) { + case void 0: + case null: + return hasToolCalls ? "tool-calls" : "stop"; + case "max_output_tokens": + return "length"; + case "content_filter": + return "content-filter"; + default: + return hasToolCalls ? "tool-calls" : "unknown"; + } +} +function prepareResponsesTools({ + mode, + strict +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + const openaiTools2 = []; + for (const tool of tools) { + switch (tool.type) { + case "function": + openaiTools2.push({ + type: "function", + name: tool.name, + description: tool.description, + parameters: tool.parameters, + strict: strict ? true : void 0 + }); + break; + case "provider-defined": + switch (tool.id) { + case "openai.web_search_preview": + openaiTools2.push({ + type: "web_search_preview", + search_context_size: tool.args.searchContextSize, + user_location: tool.args.userLocation + }); + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + } + if (toolChoice == null) { + return { tools: openaiTools2, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: openaiTools2, tool_choice: type, toolWarnings }; + case "tool": { + if (toolChoice.toolName === "web_search_preview") { + return { + tools: openaiTools2, + tool_choice: { + type: "web_search_preview" + }, + toolWarnings + }; + } + return { + tools: openaiTools2, + tool_choice: { + type: "function", + name: toolChoice.toolName + }, + toolWarnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var OpenAIResponsesLanguageModel = class { + constructor(modelId, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsStructuredOutputs = true; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + getArgs({ + mode, + maxTokens, + temperature, + stopSequences, + topP, + topK, + presencePenalty, + frequencyPenalty, + seed, + prompt, + providerMetadata, + responseFormat + }) { + var _a15, _b, _c; + const warnings = []; + const modelConfig = getResponsesModelConfig(this.modelId); + const type = mode.type; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (seed != null) { + warnings.push({ + type: "unsupported-setting", + setting: "seed" + }); + } + if (presencePenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty" + }); + } + if (frequencyPenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty" + }); + } + if (stopSequences != null) { + warnings.push({ + type: "unsupported-setting", + setting: "stopSequences" + }); + } + const { messages, warnings: messageWarnings } = convertToOpenAIResponsesMessages({ + prompt, + systemMessageMode: modelConfig.systemMessageMode + }); + warnings.push(...messageWarnings); + const openaiOptions = parseProviderOptions({ + provider: "openai", + providerOptions: providerMetadata, + schema: openaiResponsesProviderOptionsSchema + }); + const isStrict = (_a15 = openaiOptions == null ? void 0 : openaiOptions.strictSchemas) != null ? _a15 : true; + const baseArgs = __spreadValues(__spreadValues(__spreadProps(__spreadValues({ + model: this.modelId, + input: messages, + temperature, + top_p: topP, + max_output_tokens: maxTokens + }, (responseFormat == null ? void 0 : responseFormat.type) === "json" && { + text: { + format: responseFormat.schema != null ? { + type: "json_schema", + strict: isStrict, + name: (_b = responseFormat.name) != null ? _b : "response", + description: responseFormat.description, + schema: responseFormat.schema + } : { type: "json_object" } + } + }), { + // provider options: + metadata: openaiOptions == null ? void 0 : openaiOptions.metadata, + parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls, + previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId, + store: openaiOptions == null ? void 0 : openaiOptions.store, + user: openaiOptions == null ? void 0 : openaiOptions.user, + instructions: openaiOptions == null ? void 0 : openaiOptions.instructions + }), modelConfig.isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && { + reasoning: __spreadValues(__spreadValues({}, (openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && { + effort: openaiOptions.reasoningEffort + }), (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { + summary: openaiOptions.reasoningSummary + }) + }), modelConfig.requiredAutoTruncation && { + truncation: "auto" + }); + if (modelConfig.isReasoningModel) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (baseArgs.top_p != null) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topP", + details: "topP is not supported for reasoning models" + }); + } + } + switch (type) { + case "regular": { + const { tools, tool_choice, toolWarnings } = prepareResponsesTools({ + mode, + strict: isStrict + // TODO support provider options on tools + }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools, + tool_choice + }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + text: { + format: mode.schema != null ? { + type: "json_schema", + strict: isStrict, + name: (_c = mode.name) != null ? _c : "response", + description: mode.description, + schema: mode.schema + } : { type: "json_object" } + } + }), + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { type: "function", name: mode.tool.name }, + tools: [ + { + type: "function", + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters, + strict: isStrict + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g; + const { args: body, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/responses", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + import_zod8.z.object({ + id: import_zod8.z.string(), + created_at: import_zod8.z.number(), + model: import_zod8.z.string(), + output: import_zod8.z.array( + import_zod8.z.discriminatedUnion("type", [ + import_zod8.z.object({ + type: import_zod8.z.literal("message"), + role: import_zod8.z.literal("assistant"), + content: import_zod8.z.array( + import_zod8.z.object({ + type: import_zod8.z.literal("output_text"), + text: import_zod8.z.string(), + annotations: import_zod8.z.array( + import_zod8.z.object({ + type: import_zod8.z.literal("url_citation"), + start_index: import_zod8.z.number(), + end_index: import_zod8.z.number(), + url: import_zod8.z.string(), + title: import_zod8.z.string() + }) + ) + }) + ) + }), + import_zod8.z.object({ + type: import_zod8.z.literal("function_call"), + call_id: import_zod8.z.string(), + name: import_zod8.z.string(), + arguments: import_zod8.z.string() + }), + import_zod8.z.object({ + type: import_zod8.z.literal("web_search_call") + }), + import_zod8.z.object({ + type: import_zod8.z.literal("computer_call") + }), + import_zod8.z.object({ + type: import_zod8.z.literal("reasoning"), + summary: import_zod8.z.array( + import_zod8.z.object({ + type: import_zod8.z.literal("summary_text"), + text: import_zod8.z.string() + }) + ) + }) + ]) + ), + incomplete_details: import_zod8.z.object({ reason: import_zod8.z.string() }).nullable(), + usage: usageSchema + }) + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const outputTextElements = response.output.filter((output) => output.type === "message").flatMap((output) => output.content).filter((content) => content.type === "output_text"); + const toolCalls = response.output.filter((output) => output.type === "function_call").map((output) => ({ + toolCallType: "function", + toolCallId: output.call_id, + toolName: output.name, + args: output.arguments + })); + const reasoningSummary = (_b = (_a15 = response.output.find((item) => item.type === "reasoning")) == null ? void 0 : _a15.summary) != null ? _b : null; + return { + text: outputTextElements.map((content) => content.text).join("\n"), + sources: outputTextElements.flatMap( + (content) => content.annotations.map((annotation) => { + var _a22, _b2, _c2; + return { + sourceType: "url", + id: (_c2 = (_b2 = (_a22 = this.config).generateId) == null ? void 0 : _b2.call(_a22)) != null ? _c2 : generateId(), + url: annotation.url, + title: annotation.title + }; + }) + ), + finishReason: mapOpenAIResponseFinishReason({ + finishReason: (_c = response.incomplete_details) == null ? void 0 : _c.reason, + hasToolCalls: toolCalls.length > 0 + }), + toolCalls: toolCalls.length > 0 ? toolCalls : void 0, + reasoning: reasoningSummary ? reasoningSummary.map((summary) => ({ + type: "text", + text: summary.text + })) : void 0, + usage: { + promptTokens: response.usage.input_tokens, + completionTokens: response.usage.output_tokens + }, + rawCall: { + rawPrompt: void 0, + rawSettings: {} + }, + rawResponse: { + headers: responseHeaders, + body: rawResponse + }, + request: { + body: JSON.stringify(body) + }, + response: { + id: response.id, + timestamp: new Date(response.created_at * 1e3), + modelId: response.model + }, + providerMetadata: { + openai: { + responseId: response.id, + cachedPromptTokens: (_e = (_d = response.usage.input_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : null, + reasoningTokens: (_g = (_f = response.usage.output_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : null + } + }, + warnings + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args: body, warnings } = this.getArgs(options); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/responses", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: __spreadProps(__spreadValues({}, body), { + stream: true + }), + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + openaiResponsesChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const self = this; + let finishReason = "unknown"; + let promptTokens = NaN; + let completionTokens = NaN; + let cachedPromptTokens = null; + let reasoningTokens = null; + let responseId = null; + const ongoingToolCalls = {}; + let hasToolCalls = false; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a15, _b, _c, _d, _e, _f, _g, _h; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if (isResponseOutputItemAddedChunk(value)) { + if (value.item.type === "function_call") { + ongoingToolCalls[value.output_index] = { + toolName: value.item.name, + toolCallId: value.item.call_id + }; + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: value.item.call_id, + toolName: value.item.name, + argsTextDelta: value.item.arguments + }); + } + } else if (isResponseFunctionCallArgumentsDeltaChunk(value)) { + const toolCall = ongoingToolCalls[value.output_index]; + if (toolCall != null) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + argsTextDelta: value.delta + }); + } + } else if (isResponseCreatedChunk(value)) { + responseId = value.response.id; + controller.enqueue({ + type: "response-metadata", + id: value.response.id, + timestamp: new Date(value.response.created_at * 1e3), + modelId: value.response.model + }); + } else if (isTextDeltaChunk(value)) { + controller.enqueue({ + type: "text-delta", + textDelta: value.delta + }); + } else if (isResponseReasoningSummaryTextDeltaChunk(value)) { + controller.enqueue({ + type: "reasoning", + textDelta: value.delta + }); + } else if (isResponseOutputItemDoneChunk(value) && value.item.type === "function_call") { + ongoingToolCalls[value.output_index] = void 0; + hasToolCalls = true; + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: value.item.call_id, + toolName: value.item.name, + args: value.item.arguments + }); + } else if (isResponseFinishedChunk(value)) { + finishReason = mapOpenAIResponseFinishReason({ + finishReason: (_a15 = value.response.incomplete_details) == null ? void 0 : _a15.reason, + hasToolCalls + }); + promptTokens = value.response.usage.input_tokens; + completionTokens = value.response.usage.output_tokens; + cachedPromptTokens = (_c = (_b = value.response.usage.input_tokens_details) == null ? void 0 : _b.cached_tokens) != null ? _c : cachedPromptTokens; + reasoningTokens = (_e = (_d = value.response.usage.output_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : reasoningTokens; + } else if (isResponseAnnotationAddedChunk(value)) { + controller.enqueue({ + type: "source", + source: { + sourceType: "url", + id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(), + url: value.annotation.url, + title: value.annotation.title + } + }); + } + }, + flush(controller) { + controller.enqueue(__spreadValues({ + type: "finish", + finishReason, + usage: { promptTokens, completionTokens } + }, (cachedPromptTokens != null || reasoningTokens != null) && { + providerMetadata: { + openai: { + responseId, + cachedPromptTokens, + reasoningTokens + } + } + })); + } + }) + ), + rawCall: { + rawPrompt: void 0, + rawSettings: {} + }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +var usageSchema = import_zod8.z.object({ + input_tokens: import_zod8.z.number(), + input_tokens_details: import_zod8.z.object({ cached_tokens: import_zod8.z.number().nullish() }).nullish(), + output_tokens: import_zod8.z.number(), + output_tokens_details: import_zod8.z.object({ reasoning_tokens: import_zod8.z.number().nullish() }).nullish() +}); +var textDeltaChunkSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.output_text.delta"), + delta: import_zod8.z.string() +}); +var responseFinishedChunkSchema = import_zod8.z.object({ + type: import_zod8.z.enum(["response.completed", "response.incomplete"]), + response: import_zod8.z.object({ + incomplete_details: import_zod8.z.object({ reason: import_zod8.z.string() }).nullish(), + usage: usageSchema + }) +}); +var responseCreatedChunkSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.created"), + response: import_zod8.z.object({ + id: import_zod8.z.string(), + created_at: import_zod8.z.number(), + model: import_zod8.z.string() + }) +}); +var responseOutputItemDoneSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.output_item.done"), + output_index: import_zod8.z.number(), + item: import_zod8.z.discriminatedUnion("type", [ + import_zod8.z.object({ + type: import_zod8.z.literal("message") + }), + import_zod8.z.object({ + type: import_zod8.z.literal("function_call"), + id: import_zod8.z.string(), + call_id: import_zod8.z.string(), + name: import_zod8.z.string(), + arguments: import_zod8.z.string(), + status: import_zod8.z.literal("completed") + }) + ]) +}); +var responseFunctionCallArgumentsDeltaSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.function_call_arguments.delta"), + item_id: import_zod8.z.string(), + output_index: import_zod8.z.number(), + delta: import_zod8.z.string() +}); +var responseOutputItemAddedSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.output_item.added"), + output_index: import_zod8.z.number(), + item: import_zod8.z.discriminatedUnion("type", [ + import_zod8.z.object({ + type: import_zod8.z.literal("message") + }), + import_zod8.z.object({ + type: import_zod8.z.literal("function_call"), + id: import_zod8.z.string(), + call_id: import_zod8.z.string(), + name: import_zod8.z.string(), + arguments: import_zod8.z.string() + }) + ]) +}); +var responseAnnotationAddedSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.output_text.annotation.added"), + annotation: import_zod8.z.object({ + type: import_zod8.z.literal("url_citation"), + url: import_zod8.z.string(), + title: import_zod8.z.string() + }) +}); +var responseReasoningSummaryTextDeltaSchema = import_zod8.z.object({ + type: import_zod8.z.literal("response.reasoning_summary_text.delta"), + item_id: import_zod8.z.string(), + output_index: import_zod8.z.number(), + summary_index: import_zod8.z.number(), + delta: import_zod8.z.string() +}); +var openaiResponsesChunkSchema = import_zod8.z.union([ + textDeltaChunkSchema, + responseFinishedChunkSchema, + responseCreatedChunkSchema, + responseOutputItemDoneSchema, + responseFunctionCallArgumentsDeltaSchema, + responseOutputItemAddedSchema, + responseAnnotationAddedSchema, + responseReasoningSummaryTextDeltaSchema, + import_zod8.z.object({ type: import_zod8.z.string() }).passthrough() + // fallback for unknown chunks +]); +function isTextDeltaChunk(chunk) { + return chunk.type === "response.output_text.delta"; +} +function isResponseOutputItemDoneChunk(chunk) { + return chunk.type === "response.output_item.done"; +} +function isResponseFinishedChunk(chunk) { + return chunk.type === "response.completed" || chunk.type === "response.incomplete"; +} +function isResponseCreatedChunk(chunk) { + return chunk.type === "response.created"; +} +function isResponseFunctionCallArgumentsDeltaChunk(chunk) { + return chunk.type === "response.function_call_arguments.delta"; +} +function isResponseOutputItemAddedChunk(chunk) { + return chunk.type === "response.output_item.added"; +} +function isResponseAnnotationAddedChunk(chunk) { + return chunk.type === "response.output_text.annotation.added"; +} +function isResponseReasoningSummaryTextDeltaChunk(chunk) { + return chunk.type === "response.reasoning_summary_text.delta"; +} +function getResponsesModelConfig(modelId) { + if (modelId.startsWith("o")) { + if (modelId.startsWith("o1-mini") || modelId.startsWith("o1-preview")) { + return { + isReasoningModel: true, + systemMessageMode: "remove", + requiredAutoTruncation: false + }; + } + return { + isReasoningModel: true, + systemMessageMode: "developer", + requiredAutoTruncation: false + }; + } + return { + isReasoningModel: false, + systemMessageMode: "system", + requiredAutoTruncation: false + }; +} +var openaiResponsesProviderOptionsSchema = import_zod8.z.object({ + metadata: import_zod8.z.any().nullish(), + parallelToolCalls: import_zod8.z.boolean().nullish(), + previousResponseId: import_zod8.z.string().nullish(), + store: import_zod8.z.boolean().nullish(), + user: import_zod8.z.string().nullish(), + reasoningEffort: import_zod8.z.string().nullish(), + strictSchemas: import_zod8.z.boolean().nullish(), + instructions: import_zod8.z.string().nullish(), + reasoningSummary: import_zod8.z.string().nullish() +}); +var WebSearchPreviewParameters = import_zod9.z.object({}); +function webSearchPreviewTool({ + searchContextSize, + userLocation +} = {}) { + return { + type: "provider-defined", + id: "openai.web_search_preview", + args: { + searchContextSize, + userLocation + }, + parameters: WebSearchPreviewParameters + }; +} +var openaiTools = { + webSearchPreview: webSearchPreviewTool +}; +var OpenAIProviderOptionsSchema = import_zod10.z.object({ + instructions: import_zod10.z.string().nullish(), + speed: import_zod10.z.number().min(0.25).max(4).default(1).nullish() +}); +var OpenAISpeechModel = class { + constructor(modelId, config) { + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v1"; + } + get provider() { + return this.config.provider; + } + getArgs({ + text, + voice = "alloy", + outputFormat = "mp3", + speed, + instructions, + providerOptions + }) { + const warnings = []; + const openAIOptions = parseProviderOptions({ + provider: "openai", + providerOptions, + schema: OpenAIProviderOptionsSchema + }); + const requestBody = { + model: this.modelId, + input: text, + voice, + response_format: "mp3", + speed, + instructions + }; + if (outputFormat) { + if (["mp3", "opus", "aac", "flac", "wav", "pcm"].includes(outputFormat)) { + requestBody.response_format = outputFormat; + } else { + warnings.push({ + type: "unsupported-setting", + setting: "outputFormat", + details: `Unsupported output format: ${outputFormat}. Using mp3 instead.` + }); + } + } + if (openAIOptions) { + const speechModelOptions = {}; + for (const key in speechModelOptions) { + const value = speechModelOptions[key]; + if (value !== void 0) { + requestBody[key] = value; + } + } + } + return { + requestBody, + warnings + }; + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c; + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { requestBody, warnings } = this.getArgs(options); + const { + value: audio, + responseHeaders, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/audio/speech", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: requestBody, + failedResponseHandler: openaiFailedResponseHandler, + successfulResponseHandler: createBinaryResponseHandler(), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + return { + audio, + warnings, + request: { + body: JSON.stringify(requestBody) + }, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + }); + } +}; +function createOpenAI(options = {}) { + var _a15, _b, _c; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.openai.com/v1"; + const compatibility = (_b = options.compatibility) != null ? _b : "compatible"; + const providerName = (_c = options.name) != null ? _c : "openai"; + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "OPENAI_API_KEY", + description: "OpenAI" + })}`, + "OpenAI-Organization": options.organization, + "OpenAI-Project": options.project + }, options.headers); + const createChatModel = (modelId, settings = {}) => new OpenAIChatLanguageModel(modelId, settings, { + provider: `${providerName}.chat`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + compatibility, + fetch: options.fetch + }); + const createCompletionModel = (modelId, settings = {}) => new OpenAICompletionLanguageModel(modelId, settings, { + provider: `${providerName}.completion`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + compatibility, + fetch: options.fetch + }); + const createEmbeddingModel = (modelId, settings = {}) => new OpenAIEmbeddingModel(modelId, settings, { + provider: `${providerName}.embedding`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createImageModel = (modelId, settings = {}) => new OpenAIImageModel(modelId, settings, { + provider: `${providerName}.image`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel(modelId, { + provider: `${providerName}.transcription`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createSpeechModel = (modelId) => new OpenAISpeechModel(modelId, { + provider: `${providerName}.speech`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createLanguageModel = (modelId, settings) => { + if (new.target) { + throw new Error( + "The OpenAI model function cannot be called with the new keyword." + ); + } + if (modelId === "gpt-3.5-turbo-instruct") { + return createCompletionModel( + modelId, + settings + ); + } + return createChatModel(modelId, settings); + }; + const createResponsesModel = (modelId) => { + return new OpenAIResponsesLanguageModel(modelId, { + provider: `${providerName}.responses`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + }; + const provider = function(modelId, settings) { + return createLanguageModel(modelId, settings); + }; + provider.languageModel = createLanguageModel; + provider.chat = createChatModel; + provider.completion = createCompletionModel; + provider.responses = createResponsesModel; + provider.embedding = createEmbeddingModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + provider.image = createImageModel; + provider.imageModel = createImageModel; + provider.transcription = createTranscriptionModel; + provider.transcriptionModel = createTranscriptionModel; + provider.speech = createSpeechModel; + provider.speechModel = createSpeechModel; + provider.tools = openaiTools; + return provider; +} +var openai = createOpenAI({ + compatibility: "strict" + // strict for OpenAI API +}); + +// node_modules/.pnpm/@ai-sdk+anthropic@1.2.10_zod@3.25.67/node_modules/@ai-sdk/anthropic/dist/index.mjs +var import_zod11 = require("zod"); +var import_zod12 = require("zod"); +var import_zod13 = require("zod"); +var anthropicErrorDataSchema = import_zod12.z.object({ + type: import_zod12.z.literal("error"), + error: import_zod12.z.object({ + type: import_zod12.z.string(), + message: import_zod12.z.string() + }) +}); +var anthropicFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: anthropicErrorDataSchema, + errorToMessage: (data) => data.error.message +}); +function prepareTools2(mode) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + const betas = /* @__PURE__ */ new Set(); + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings, betas }; + } + const anthropicTools2 = []; + for (const tool of tools) { + switch (tool.type) { + case "function": + anthropicTools2.push({ + name: tool.name, + description: tool.description, + input_schema: tool.parameters + }); + break; + case "provider-defined": + switch (tool.id) { + case "anthropic.computer_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: tool.name, + type: "computer_20250124", + display_width_px: tool.args.displayWidthPx, + display_height_px: tool.args.displayHeightPx, + display_number: tool.args.displayNumber + }); + break; + case "anthropic.computer_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: tool.name, + type: "computer_20241022", + display_width_px: tool.args.displayWidthPx, + display_height_px: tool.args.displayHeightPx, + display_number: tool.args.displayNumber + }); + break; + case "anthropic.text_editor_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: tool.name, + type: "text_editor_20250124" + }); + break; + case "anthropic.text_editor_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: tool.name, + type: "text_editor_20241022" + }); + break; + case "anthropic.bash_20250124": + betas.add("computer-use-2025-01-24"); + anthropicTools2.push({ + name: tool.name, + type: "bash_20250124" + }); + break; + case "anthropic.bash_20241022": + betas.add("computer-use-2024-10-22"); + anthropicTools2.push({ + name: tool.name, + type: "bash_20241022" + }); + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + } + const toolChoice = mode.toolChoice; + if (toolChoice == null) { + return { + tools: anthropicTools2, + tool_choice: void 0, + toolWarnings, + betas + }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + return { + tools: anthropicTools2, + tool_choice: { type: "auto" }, + toolWarnings, + betas + }; + case "required": + return { + tools: anthropicTools2, + tool_choice: { type: "any" }, + toolWarnings, + betas + }; + case "none": + return { tools: void 0, tool_choice: void 0, toolWarnings, betas }; + case "tool": + return { + tools: anthropicTools2, + tool_choice: { type: "tool", name: toolChoice.toolName }, + toolWarnings, + betas + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +function convertToAnthropicMessagesPrompt({ + prompt, + sendReasoning, + warnings +}) { + var _a15, _b, _c, _d; + const betas = /* @__PURE__ */ new Set(); + const blocks = groupIntoBlocks(prompt); + let system = void 0; + const messages = []; + function getCacheControl(providerMetadata) { + var _a22; + const anthropic2 = providerMetadata == null ? void 0 : providerMetadata.anthropic; + const cacheControlValue = (_a22 = anthropic2 == null ? void 0 : anthropic2.cacheControl) != null ? _a22 : anthropic2 == null ? void 0 : anthropic2.cache_control; + return cacheControlValue; + } + for (let i = 0; i < blocks.length; i++) { + const block = blocks[i]; + const isLastBlock = i === blocks.length - 1; + const type = block.type; + switch (type) { + case "system": { + if (system != null) { + throw new UnsupportedFunctionalityError({ + functionality: "Multiple system messages that are separated by user/assistant messages" + }); + } + system = block.messages.map(({ content, providerMetadata }) => ({ + type: "text", + text: content, + cache_control: getCacheControl(providerMetadata) + })); + break; + } + case "user": { + const anthropicContent = []; + for (const message of block.messages) { + const { role, content } = message; + switch (role) { + case "user": { + for (let j = 0; j < content.length; j++) { + const part = content[j]; + const isLastPart = j === content.length - 1; + const cacheControl = (_a15 = getCacheControl(part.providerMetadata)) != null ? _a15 : isLastPart ? getCacheControl(message.providerMetadata) : void 0; + switch (part.type) { + case "text": { + anthropicContent.push({ + type: "text", + text: part.text, + cache_control: cacheControl + }); + break; + } + case "image": { + anthropicContent.push({ + type: "image", + source: part.image instanceof URL ? { + type: "url", + url: part.image.toString() + } : { + type: "base64", + media_type: (_b = part.mimeType) != null ? _b : "image/jpeg", + data: convertUint8ArrayToBase64(part.image) + }, + cache_control: cacheControl + }); + break; + } + case "file": { + if (part.mimeType !== "application/pdf") { + throw new UnsupportedFunctionalityError({ + functionality: "Non-PDF files in user messages" + }); + } + betas.add("pdfs-2024-09-25"); + anthropicContent.push({ + type: "document", + source: part.data instanceof URL ? { + type: "url", + url: part.data.toString() + } : { + type: "base64", + media_type: "application/pdf", + data: part.data + }, + cache_control: cacheControl + }); + break; + } + } + } + break; + } + case "tool": { + for (let i2 = 0; i2 < content.length; i2++) { + const part = content[i2]; + const isLastPart = i2 === content.length - 1; + const cacheControl = (_c = getCacheControl(part.providerMetadata)) != null ? _c : isLastPart ? getCacheControl(message.providerMetadata) : void 0; + const toolResultContent = part.content != null ? part.content.map((part2) => { + var _a22; + switch (part2.type) { + case "text": + return { + type: "text", + text: part2.text, + cache_control: void 0 + }; + case "image": + return { + type: "image", + source: { + type: "base64", + media_type: (_a22 = part2.mimeType) != null ? _a22 : "image/jpeg", + data: part2.data + }, + cache_control: void 0 + }; + } + }) : JSON.stringify(part.result); + anthropicContent.push({ + type: "tool_result", + tool_use_id: part.toolCallId, + content: toolResultContent, + is_error: part.isError, + cache_control: cacheControl + }); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + messages.push({ role: "user", content: anthropicContent }); + break; + } + case "assistant": { + const anthropicContent = []; + for (let j = 0; j < block.messages.length; j++) { + const message = block.messages[j]; + const isLastMessage = j === block.messages.length - 1; + const { content } = message; + for (let k = 0; k < content.length; k++) { + const part = content[k]; + const isLastContentPart = k === content.length - 1; + const cacheControl = (_d = getCacheControl(part.providerMetadata)) != null ? _d : isLastContentPart ? getCacheControl(message.providerMetadata) : void 0; + switch (part.type) { + case "text": { + anthropicContent.push({ + type: "text", + text: ( + // trim the last text part if it's the last message in the block + // because Anthropic does not allow trailing whitespace + // in pre-filled assistant responses + isLastBlock && isLastMessage && isLastContentPart ? part.text.trim() : part.text + ), + cache_control: cacheControl + }); + break; + } + case "reasoning": { + if (sendReasoning) { + anthropicContent.push({ + type: "thinking", + thinking: part.text, + signature: part.signature, + cache_control: cacheControl + }); + } else { + warnings.push({ + type: "other", + message: "sending reasoning content is disabled for this model" + }); + } + break; + } + case "redacted-reasoning": { + anthropicContent.push({ + type: "redacted_thinking", + data: part.data, + cache_control: cacheControl + }); + break; + } + case "tool-call": { + anthropicContent.push({ + type: "tool_use", + id: part.toolCallId, + name: part.toolName, + input: part.args, + cache_control: cacheControl + }); + break; + } + } + } + } + messages.push({ role: "assistant", content: anthropicContent }); + break; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + return { + prompt: { system, messages }, + betas + }; +} +function groupIntoBlocks(prompt) { + const blocks = []; + let currentBlock = void 0; + for (const message of prompt) { + const { role } = message; + switch (role) { + case "system": { + if ((currentBlock == null ? void 0 : currentBlock.type) !== "system") { + currentBlock = { type: "system", messages: [] }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + } + case "assistant": { + if ((currentBlock == null ? void 0 : currentBlock.type) !== "assistant") { + currentBlock = { type: "assistant", messages: [] }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + } + case "user": { + if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") { + currentBlock = { type: "user", messages: [] }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + } + case "tool": { + if ((currentBlock == null ? void 0 : currentBlock.type) !== "user") { + currentBlock = { type: "user", messages: [] }; + blocks.push(currentBlock); + } + currentBlock.messages.push(message); + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return blocks; +} +function mapAnthropicStopReason(finishReason) { + switch (finishReason) { + case "end_turn": + case "stop_sequence": + return "stop"; + case "tool_use": + return "tool-calls"; + case "max_tokens": + return "length"; + default: + return "unknown"; + } +} +var AnthropicMessagesLanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "tool"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + supportsUrl(url) { + return url.protocol === "https:"; + } + get provider() { + return this.config.provider; + } + get supportsImageUrls() { + return this.config.supportsImageUrls; + } + getArgs(_0) { + return __async(this, arguments, function* ({ + mode, + prompt, + maxTokens = 4096, + // 4096: max model output tokens TODO update default in v5 + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata: providerOptions + }) { + var _a15, _b, _c; + const type = mode.type; + const warnings = []; + if (frequencyPenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty" + }); + } + if (presencePenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty" + }); + } + if (seed != null) { + warnings.push({ + type: "unsupported-setting", + setting: "seed" + }); + } + if (responseFormat != null && responseFormat.type !== "text") { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format is not supported." + }); + } + const { prompt: messagesPrompt, betas: messagesBetas } = convertToAnthropicMessagesPrompt({ + prompt, + sendReasoning: (_a15 = this.settings.sendReasoning) != null ? _a15 : true, + warnings + }); + const anthropicOptions = parseProviderOptions({ + provider: "anthropic", + providerOptions, + schema: anthropicProviderOptionsSchema + }); + const isThinking = ((_b = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _b.type) === "enabled"; + const thinkingBudget = (_c = anthropicOptions == null ? void 0 : anthropicOptions.thinking) == null ? void 0 : _c.budgetTokens; + const baseArgs = __spreadProps(__spreadValues({ + // model id: + model: this.modelId, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_k: topK, + top_p: topP, + stop_sequences: stopSequences + }, isThinking && { + thinking: { type: "enabled", budget_tokens: thinkingBudget } + }), { + // prompt: + system: messagesPrompt.system, + messages: messagesPrompt.messages + }); + if (isThinking) { + if (thinkingBudget == null) { + throw new UnsupportedFunctionalityError({ + functionality: "thinking requires a budget" + }); + } + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported when thinking is enabled" + }); + } + if (topK != null) { + baseArgs.top_k = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topK", + details: "topK is not supported when thinking is enabled" + }); + } + if (topP != null) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topP", + details: "topP is not supported when thinking is enabled" + }); + } + baseArgs.max_tokens = maxTokens + thinkingBudget; + } + switch (type) { + case "regular": { + const { + tools, + tool_choice, + toolWarnings, + betas: toolsBetas + } = prepareTools2(mode); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { tools, tool_choice }), + warnings: [...warnings, ...toolWarnings], + betas: /* @__PURE__ */ new Set([...messagesBetas, ...toolsBetas]) + }; + } + case "object-json": { + throw new UnsupportedFunctionalityError({ + functionality: "json-mode object generation" + }); + } + case "object-tool": { + const { name: name14, description, parameters } = mode.tool; + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools: [{ name: name14, description, input_schema: parameters }], + tool_choice: { type: "tool", name: name14 } + }), + warnings, + betas: messagesBetas + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + }); + } + getHeaders(_0) { + return __async(this, arguments, function* ({ + betas, + headers + }) { + return combineHeaders( + yield resolve(this.config.headers), + betas.size > 0 ? { "anthropic-beta": Array.from(betas).join(",") } : {}, + headers + ); + }); + } + buildRequestUrl(isStreaming) { + var _a15, _b, _c; + return (_c = (_b = (_a15 = this.config).buildRequestUrl) == null ? void 0 : _b.call(_a15, this.config.baseURL, isStreaming)) != null ? _c : `${this.config.baseURL}/messages`; + } + transformRequestBody(args) { + var _a15, _b, _c; + return (_c = (_b = (_a15 = this.config).transformRequestBody) == null ? void 0 : _b.call(_a15, args)) != null ? _c : args; + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d; + const { args, warnings, betas } = yield this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.buildRequestUrl(false), + headers: yield this.getHeaders({ betas, headers: options.headers }), + body: this.transformRequestBody(args), + failedResponseHandler: anthropicFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + anthropicMessagesResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + let text = ""; + for (const content of response.content) { + if (content.type === "text") { + text += content.text; + } + } + let toolCalls = void 0; + if (response.content.some((content) => content.type === "tool_use")) { + toolCalls = []; + for (const content of response.content) { + if (content.type === "tool_use") { + toolCalls.push({ + toolCallType: "function", + toolCallId: content.id, + toolName: content.name, + args: JSON.stringify(content.input) + }); + } + } + } + const reasoning = response.content.filter( + (content) => content.type === "redacted_thinking" || content.type === "thinking" + ).map( + (content) => content.type === "thinking" ? { + type: "text", + text: content.thinking, + signature: content.signature + } : { + type: "redacted", + data: content.data + } + ); + return { + text, + reasoning: reasoning.length > 0 ? reasoning : void 0, + toolCalls, + finishReason: mapAnthropicStopReason(response.stop_reason), + usage: { + promptTokens: response.usage.input_tokens, + completionTokens: response.usage.output_tokens + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { + headers: responseHeaders, + body: rawResponse + }, + response: { + id: (_a15 = response.id) != null ? _a15 : void 0, + modelId: (_b = response.model) != null ? _b : void 0 + }, + warnings, + providerMetadata: { + anthropic: { + cacheCreationInputTokens: (_c = response.usage.cache_creation_input_tokens) != null ? _c : null, + cacheReadInputTokens: (_d = response.usage.cache_read_input_tokens) != null ? _d : null + } + }, + request: { body: JSON.stringify(args) } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings, betas } = yield this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { stream: true }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.buildRequestUrl(true), + headers: yield this.getHeaders({ betas, headers: options.headers }), + body: this.transformRequestBody(body), + failedResponseHandler: anthropicFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + anthropicMessagesChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + let finishReason = "unknown"; + const usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + const toolCallContentBlocks = {}; + let providerMetadata = void 0; + let blockType = void 0; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c, _d; + if (!chunk.success) { + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + switch (value.type) { + case "ping": { + return; + } + case "content_block_start": { + const contentBlockType = value.content_block.type; + blockType = contentBlockType; + switch (contentBlockType) { + case "text": + case "thinking": { + return; + } + case "redacted_thinking": { + controller.enqueue({ + type: "redacted-reasoning", + data: value.content_block.data + }); + return; + } + case "tool_use": { + toolCallContentBlocks[value.index] = { + toolCallId: value.content_block.id, + toolName: value.content_block.name, + jsonText: "" + }; + return; + } + default: { + const _exhaustiveCheck = contentBlockType; + throw new Error( + `Unsupported content block type: ${_exhaustiveCheck}` + ); + } + } + } + case "content_block_stop": { + if (toolCallContentBlocks[value.index] != null) { + const contentBlock = toolCallContentBlocks[value.index]; + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: contentBlock.toolCallId, + toolName: contentBlock.toolName, + args: contentBlock.jsonText + }); + delete toolCallContentBlocks[value.index]; + } + blockType = void 0; + return; + } + case "content_block_delta": { + const deltaType = value.delta.type; + switch (deltaType) { + case "text_delta": { + controller.enqueue({ + type: "text-delta", + textDelta: value.delta.text + }); + return; + } + case "thinking_delta": { + controller.enqueue({ + type: "reasoning", + textDelta: value.delta.thinking + }); + return; + } + case "signature_delta": { + if (blockType === "thinking") { + controller.enqueue({ + type: "reasoning-signature", + signature: value.delta.signature + }); + } + return; + } + case "input_json_delta": { + const contentBlock = toolCallContentBlocks[value.index]; + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: contentBlock.toolCallId, + toolName: contentBlock.toolName, + argsTextDelta: value.delta.partial_json + }); + contentBlock.jsonText += value.delta.partial_json; + return; + } + default: { + const _exhaustiveCheck = deltaType; + throw new Error( + `Unsupported delta type: ${_exhaustiveCheck}` + ); + } + } + } + case "message_start": { + usage.promptTokens = value.message.usage.input_tokens; + usage.completionTokens = value.message.usage.output_tokens; + providerMetadata = { + anthropic: { + cacheCreationInputTokens: (_a16 = value.message.usage.cache_creation_input_tokens) != null ? _a16 : null, + cacheReadInputTokens: (_b = value.message.usage.cache_read_input_tokens) != null ? _b : null + } + }; + controller.enqueue({ + type: "response-metadata", + id: (_c = value.message.id) != null ? _c : void 0, + modelId: (_d = value.message.model) != null ? _d : void 0 + }); + return; + } + case "message_delta": { + usage.completionTokens = value.usage.output_tokens; + finishReason = mapAnthropicStopReason(value.delta.stop_reason); + return; + } + case "message_stop": { + controller.enqueue({ + type: "finish", + finishReason, + usage, + providerMetadata + }); + return; + } + case "error": { + controller.enqueue({ type: "error", error: value.error }); + return; + } + default: { + const _exhaustiveCheck = value; + throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`); + } + } + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body: JSON.stringify(body) } + }; + }); + } +}; +var anthropicMessagesResponseSchema = import_zod11.z.object({ + type: import_zod11.z.literal("message"), + id: import_zod11.z.string().nullish(), + model: import_zod11.z.string().nullish(), + content: import_zod11.z.array( + import_zod11.z.discriminatedUnion("type", [ + import_zod11.z.object({ + type: import_zod11.z.literal("text"), + text: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("thinking"), + thinking: import_zod11.z.string(), + signature: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("redacted_thinking"), + data: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("tool_use"), + id: import_zod11.z.string(), + name: import_zod11.z.string(), + input: import_zod11.z.unknown() + }) + ]) + ), + stop_reason: import_zod11.z.string().nullish(), + usage: import_zod11.z.object({ + input_tokens: import_zod11.z.number(), + output_tokens: import_zod11.z.number(), + cache_creation_input_tokens: import_zod11.z.number().nullish(), + cache_read_input_tokens: import_zod11.z.number().nullish() + }) +}); +var anthropicMessagesChunkSchema = import_zod11.z.discriminatedUnion("type", [ + import_zod11.z.object({ + type: import_zod11.z.literal("message_start"), + message: import_zod11.z.object({ + id: import_zod11.z.string().nullish(), + model: import_zod11.z.string().nullish(), + usage: import_zod11.z.object({ + input_tokens: import_zod11.z.number(), + output_tokens: import_zod11.z.number(), + cache_creation_input_tokens: import_zod11.z.number().nullish(), + cache_read_input_tokens: import_zod11.z.number().nullish() + }) + }) + }), + import_zod11.z.object({ + type: import_zod11.z.literal("content_block_start"), + index: import_zod11.z.number(), + content_block: import_zod11.z.discriminatedUnion("type", [ + import_zod11.z.object({ + type: import_zod11.z.literal("text"), + text: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("thinking"), + thinking: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("tool_use"), + id: import_zod11.z.string(), + name: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("redacted_thinking"), + data: import_zod11.z.string() + }) + ]) + }), + import_zod11.z.object({ + type: import_zod11.z.literal("content_block_delta"), + index: import_zod11.z.number(), + delta: import_zod11.z.discriminatedUnion("type", [ + import_zod11.z.object({ + type: import_zod11.z.literal("input_json_delta"), + partial_json: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("text_delta"), + text: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("thinking_delta"), + thinking: import_zod11.z.string() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("signature_delta"), + signature: import_zod11.z.string() + }) + ]) + }), + import_zod11.z.object({ + type: import_zod11.z.literal("content_block_stop"), + index: import_zod11.z.number() + }), + import_zod11.z.object({ + type: import_zod11.z.literal("error"), + error: import_zod11.z.object({ + type: import_zod11.z.string(), + message: import_zod11.z.string() + }) + }), + import_zod11.z.object({ + type: import_zod11.z.literal("message_delta"), + delta: import_zod11.z.object({ stop_reason: import_zod11.z.string().nullish() }), + usage: import_zod11.z.object({ output_tokens: import_zod11.z.number() }) + }), + import_zod11.z.object({ + type: import_zod11.z.literal("message_stop") + }), + import_zod11.z.object({ + type: import_zod11.z.literal("ping") + }) +]); +var anthropicProviderOptionsSchema = import_zod11.z.object({ + thinking: import_zod11.z.object({ + type: import_zod11.z.union([import_zod11.z.literal("enabled"), import_zod11.z.literal("disabled")]), + budgetTokens: import_zod11.z.number().optional() + }).optional() +}); +var Bash20241022Parameters = import_zod13.z.object({ + command: import_zod13.z.string(), + restart: import_zod13.z.boolean().optional() +}); +function bashTool_20241022(options = {}) { + return { + type: "provider-defined", + id: "anthropic.bash_20241022", + args: {}, + parameters: Bash20241022Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var Bash20250124Parameters = import_zod13.z.object({ + command: import_zod13.z.string(), + restart: import_zod13.z.boolean().optional() +}); +function bashTool_20250124(options = {}) { + return { + type: "provider-defined", + id: "anthropic.bash_20250124", + args: {}, + parameters: Bash20250124Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var TextEditor20241022Parameters = import_zod13.z.object({ + command: import_zod13.z.enum(["view", "create", "str_replace", "insert", "undo_edit"]), + path: import_zod13.z.string(), + file_text: import_zod13.z.string().optional(), + insert_line: import_zod13.z.number().int().optional(), + new_str: import_zod13.z.string().optional(), + old_str: import_zod13.z.string().optional(), + view_range: import_zod13.z.array(import_zod13.z.number().int()).optional() +}); +function textEditorTool_20241022(options = {}) { + return { + type: "provider-defined", + id: "anthropic.text_editor_20241022", + args: {}, + parameters: TextEditor20241022Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var TextEditor20250124Parameters = import_zod13.z.object({ + command: import_zod13.z.enum(["view", "create", "str_replace", "insert", "undo_edit"]), + path: import_zod13.z.string(), + file_text: import_zod13.z.string().optional(), + insert_line: import_zod13.z.number().int().optional(), + new_str: import_zod13.z.string().optional(), + old_str: import_zod13.z.string().optional(), + view_range: import_zod13.z.array(import_zod13.z.number().int()).optional() +}); +function textEditorTool_20250124(options = {}) { + return { + type: "provider-defined", + id: "anthropic.text_editor_20250124", + args: {}, + parameters: TextEditor20250124Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var Computer20241022Parameters = import_zod13.z.object({ + action: import_zod13.z.enum([ + "key", + "type", + "mouse_move", + "left_click", + "left_click_drag", + "right_click", + "middle_click", + "double_click", + "screenshot", + "cursor_position" + ]), + coordinate: import_zod13.z.array(import_zod13.z.number().int()).optional(), + text: import_zod13.z.string().optional() +}); +function computerTool_20241022(options) { + return { + type: "provider-defined", + id: "anthropic.computer_20241022", + args: { + displayWidthPx: options.displayWidthPx, + displayHeightPx: options.displayHeightPx, + displayNumber: options.displayNumber + }, + parameters: Computer20241022Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var Computer20250124Parameters = import_zod13.z.object({ + action: import_zod13.z.enum([ + "key", + "hold_key", + "type", + "cursor_position", + "mouse_move", + "left_mouse_down", + "left_mouse_up", + "left_click", + "left_click_drag", + "right_click", + "middle_click", + "double_click", + "triple_click", + "scroll", + "wait", + "screenshot" + ]), + coordinate: import_zod13.z.tuple([import_zod13.z.number().int(), import_zod13.z.number().int()]).optional(), + duration: import_zod13.z.number().optional(), + scroll_amount: import_zod13.z.number().optional(), + scroll_direction: import_zod13.z.enum(["up", "down", "left", "right"]).optional(), + start_coordinate: import_zod13.z.tuple([import_zod13.z.number().int(), import_zod13.z.number().int()]).optional(), + text: import_zod13.z.string().optional() +}); +function computerTool_20250124(options) { + return { + type: "provider-defined", + id: "anthropic.computer_20250124", + args: { + displayWidthPx: options.displayWidthPx, + displayHeightPx: options.displayHeightPx, + displayNumber: options.displayNumber + }, + parameters: Computer20250124Parameters, + execute: options.execute, + experimental_toToolResultContent: options.experimental_toToolResultContent + }; +} +var anthropicTools = { + bash_20241022: bashTool_20241022, + bash_20250124: bashTool_20250124, + textEditor_20241022: textEditorTool_20241022, + textEditor_20250124: textEditorTool_20250124, + computer_20241022: computerTool_20241022, + computer_20250124: computerTool_20250124 +}; +function createAnthropic(options = {}) { + var _a15; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.anthropic.com/v1"; + const getHeaders = () => __spreadValues({ + "anthropic-version": "2023-06-01", + "x-api-key": loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "ANTHROPIC_API_KEY", + description: "Anthropic" + }) + }, options.headers); + const createChatModel = (modelId, settings = {}) => new AnthropicMessagesLanguageModel(modelId, settings, { + provider: "anthropic.messages", + baseURL, + headers: getHeaders, + fetch: options.fetch, + supportsImageUrls: true + }); + const provider = function(modelId, settings) { + if (new.target) { + throw new Error( + "The Anthropic model function cannot be called with the new keyword." + ); + } + return createChatModel(modelId, settings); + }; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.messages = createChatModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + provider.tools = anthropicTools; + return provider; +} +var anthropic = createAnthropic(); + +// node_modules/.pnpm/@ai-sdk+google@1.2.14_zod@3.25.67/node_modules/@ai-sdk/google/dist/index.mjs +var import_zod14 = require("zod"); +var import_zod15 = require("zod"); +var import_zod16 = require("zod"); +function convertJSONSchemaToOpenAPISchema(jsonSchema) { + if (isEmptyObjectSchema(jsonSchema)) { + return void 0; + } + if (typeof jsonSchema === "boolean") { + return { type: "boolean", properties: {} }; + } + const { + type, + description, + required, + properties, + items, + allOf, + anyOf, + oneOf, + format, + const: constValue, + minLength, + enum: enumValues + } = jsonSchema; + const result = {}; + if (description) + result.description = description; + if (required) + result.required = required; + if (format) + result.format = format; + if (constValue !== void 0) { + result.enum = [constValue]; + } + if (type) { + if (Array.isArray(type)) { + if (type.includes("null")) { + result.type = type.filter((t) => t !== "null")[0]; + result.nullable = true; + } else { + result.type = type; + } + } else if (type === "null") { + result.type = "null"; + } else { + result.type = type; + } + } + if (enumValues !== void 0) { + result.enum = enumValues; + } + if (properties != null) { + result.properties = Object.entries(properties).reduce( + (acc, [key, value]) => { + acc[key] = convertJSONSchemaToOpenAPISchema(value); + return acc; + }, + {} + ); + } + if (items) { + result.items = Array.isArray(items) ? items.map(convertJSONSchemaToOpenAPISchema) : convertJSONSchemaToOpenAPISchema(items); + } + if (allOf) { + result.allOf = allOf.map(convertJSONSchemaToOpenAPISchema); + } + if (anyOf) { + if (anyOf.some( + (schema) => typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null" + )) { + const nonNullSchemas = anyOf.filter( + (schema) => !(typeof schema === "object" && (schema == null ? void 0 : schema.type) === "null") + ); + if (nonNullSchemas.length === 1) { + const converted = convertJSONSchemaToOpenAPISchema(nonNullSchemas[0]); + if (typeof converted === "object") { + result.nullable = true; + Object.assign(result, converted); + } + } else { + result.anyOf = nonNullSchemas.map(convertJSONSchemaToOpenAPISchema); + result.nullable = true; + } + } else { + result.anyOf = anyOf.map(convertJSONSchemaToOpenAPISchema); + } + } + if (oneOf) { + result.oneOf = oneOf.map(convertJSONSchemaToOpenAPISchema); + } + if (minLength !== void 0) { + result.minLength = minLength; + } + return result; +} +function isEmptyObjectSchema(jsonSchema) { + return jsonSchema != null && typeof jsonSchema === "object" && jsonSchema.type === "object" && (jsonSchema.properties == null || Object.keys(jsonSchema.properties).length === 0); +} +function convertToGoogleGenerativeAIMessages(prompt) { + var _a15, _b; + const systemInstructionParts = []; + const contents = []; + let systemMessagesAllowed = true; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + if (!systemMessagesAllowed) { + throw new UnsupportedFunctionalityError({ + functionality: "system messages are only supported at the beginning of the conversation" + }); + } + systemInstructionParts.push({ text: content }); + break; + } + case "user": { + systemMessagesAllowed = false; + const parts = []; + for (const part of content) { + switch (part.type) { + case "text": { + parts.push({ text: part.text }); + break; + } + case "image": { + parts.push( + part.image instanceof URL ? { + fileData: { + mimeType: (_a15 = part.mimeType) != null ? _a15 : "image/jpeg", + fileUri: part.image.toString() + } + } : { + inlineData: { + mimeType: (_b = part.mimeType) != null ? _b : "image/jpeg", + data: convertUint8ArrayToBase64(part.image) + } + } + ); + break; + } + case "file": { + parts.push( + part.data instanceof URL ? { + fileData: { + mimeType: part.mimeType, + fileUri: part.data.toString() + } + } : { + inlineData: { + mimeType: part.mimeType, + data: part.data + } + } + ); + break; + } + } + } + contents.push({ role: "user", parts }); + break; + } + case "assistant": { + systemMessagesAllowed = false; + contents.push({ + role: "model", + parts: content.map((part) => { + switch (part.type) { + case "text": { + return part.text.length === 0 ? void 0 : { text: part.text }; + } + case "file": { + if (part.mimeType !== "image/png") { + throw new UnsupportedFunctionalityError({ + functionality: "Only PNG images are supported in assistant messages" + }); + } + if (part.data instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "File data URLs in assistant messages are not supported" + }); + } + return { + inlineData: { + mimeType: part.mimeType, + data: part.data + } + }; + } + case "tool-call": { + return { + functionCall: { + name: part.toolName, + args: part.args + } + }; + } + } + }).filter((part) => part !== void 0) + }); + break; + } + case "tool": { + systemMessagesAllowed = false; + contents.push({ + role: "user", + parts: content.map((part) => ({ + functionResponse: { + name: part.toolName, + response: { + name: part.toolName, + content: part.result + } + } + })) + }); + break; + } + } + } + return { + systemInstruction: systemInstructionParts.length > 0 ? { parts: systemInstructionParts } : void 0, + contents + }; +} +function getModelPath(modelId) { + return modelId.includes("/") ? modelId : `models/${modelId}`; +} +var googleErrorDataSchema = import_zod15.z.object({ + error: import_zod15.z.object({ + code: import_zod15.z.number().nullable(), + message: import_zod15.z.string(), + status: import_zod15.z.string() + }) +}); +var googleFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: googleErrorDataSchema, + errorToMessage: (data) => data.error.message +}); +function prepareTools3(mode, useSearchGrounding, dynamicRetrievalConfig, modelId) { + var _a15, _b; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + const isGemini2 = modelId.includes("gemini-2"); + const supportsDynamicRetrieval = modelId.includes("gemini-1.5-flash") && !modelId.includes("-8b"); + if (useSearchGrounding) { + return { + tools: isGemini2 ? { googleSearch: {} } : { + googleSearchRetrieval: !supportsDynamicRetrieval || !dynamicRetrievalConfig ? {} : { dynamicRetrievalConfig } + }, + toolConfig: void 0, + toolWarnings + }; + } + if (tools == null) { + return { tools: void 0, toolConfig: void 0, toolWarnings }; + } + const functionDeclarations = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + functionDeclarations.push({ + name: tool.name, + description: (_b = tool.description) != null ? _b : "", + parameters: convertJSONSchemaToOpenAPISchema(tool.parameters) + }); + } + } + const toolChoice = mode.toolChoice; + if (toolChoice == null) { + return { + tools: { functionDeclarations }, + toolConfig: void 0, + toolWarnings + }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + return { + tools: { functionDeclarations }, + toolConfig: { functionCallingConfig: { mode: "AUTO" } }, + toolWarnings + }; + case "none": + return { + tools: { functionDeclarations }, + toolConfig: { functionCallingConfig: { mode: "NONE" } }, + toolWarnings + }; + case "required": + return { + tools: { functionDeclarations }, + toolConfig: { functionCallingConfig: { mode: "ANY" } }, + toolWarnings + }; + case "tool": + return { + tools: { functionDeclarations }, + toolConfig: { + functionCallingConfig: { + mode: "ANY", + allowedFunctionNames: [toolChoice.toolName] + } + }, + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +function mapGoogleGenerativeAIFinishReason({ + finishReason, + hasToolCalls +}) { + switch (finishReason) { + case "STOP": + return hasToolCalls ? "tool-calls" : "stop"; + case "MAX_TOKENS": + return "length"; + case "IMAGE_SAFETY": + case "RECITATION": + case "SAFETY": + case "BLOCKLIST": + case "PROHIBITED_CONTENT": + case "SPII": + return "content-filter"; + case "FINISH_REASON_UNSPECIFIED": + case "OTHER": + return "other"; + case "MALFORMED_FUNCTION_CALL": + return "error"; + default: + return "unknown"; + } +} +var GoogleGenerativeAILanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsImageUrls = false; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get supportsStructuredOutputs() { + var _a15; + return (_a15 = this.settings.structuredOutputs) != null ? _a15 : true; + } + get provider() { + return this.config.provider; + } + getArgs(_0) { + return __async(this, arguments, function* ({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15, _b; + const type = mode.type; + const warnings = []; + const googleOptions = parseProviderOptions({ + provider: "google", + providerOptions: providerMetadata, + schema: googleGenerativeAIProviderOptionsSchema + }); + const generationConfig = __spreadProps(__spreadValues({ + // standardized settings: + maxOutputTokens: maxTokens, + temperature, + topK, + topP, + frequencyPenalty, + presencePenalty, + stopSequences, + seed, + // response format: + responseMimeType: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? "application/json" : void 0, + responseSchema: (responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && // Google GenAI does not support all OpenAPI Schema features, + // so this is needed as an escape hatch: + this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(responseFormat.schema) : void 0 + }, this.settings.audioTimestamp && { + audioTimestamp: this.settings.audioTimestamp + }), { + // provider options: + responseModalities: googleOptions == null ? void 0 : googleOptions.responseModalities, + thinkingConfig: googleOptions == null ? void 0 : googleOptions.thinkingConfig + }); + const { contents, systemInstruction } = convertToGoogleGenerativeAIMessages(prompt); + switch (type) { + case "regular": { + const { tools, toolConfig, toolWarnings } = prepareTools3( + mode, + (_a15 = this.settings.useSearchGrounding) != null ? _a15 : false, + this.settings.dynamicRetrievalConfig, + this.modelId + ); + return { + args: { + generationConfig, + contents, + systemInstruction, + safetySettings: this.settings.safetySettings, + tools, + toolConfig, + cachedContent: this.settings.cachedContent + }, + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: { + generationConfig: __spreadProps(__spreadValues({}, generationConfig), { + responseMimeType: "application/json", + responseSchema: mode.schema != null && // Google GenAI does not support all OpenAPI Schema features, + // so this is needed as an escape hatch: + this.supportsStructuredOutputs ? convertJSONSchemaToOpenAPISchema(mode.schema) : void 0 + }), + contents, + systemInstruction, + safetySettings: this.settings.safetySettings, + cachedContent: this.settings.cachedContent + }, + warnings + }; + } + case "object-tool": { + return { + args: { + generationConfig, + contents, + tools: { + functionDeclarations: [ + { + name: mode.tool.name, + description: (_b = mode.tool.description) != null ? _b : "", + parameters: convertJSONSchemaToOpenAPISchema( + mode.tool.parameters + ) + } + ] + }, + toolConfig: { functionCallingConfig: { mode: "ANY" } }, + safetySettings: this.settings.safetySettings, + cachedContent: this.settings.cachedContent + }, + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + }); + } + supportsUrl(url) { + return this.config.isSupportedUrl(url); + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e; + const { args, warnings } = yield this.getArgs(options); + const body = JSON.stringify(args); + const mergedHeaders = combineHeaders( + yield resolve(this.config.headers), + options.headers + ); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: `${this.config.baseURL}/${getModelPath( + this.modelId + )}:generateContent`, + headers: mergedHeaders, + body: args, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler(responseSchema), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { contents: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["contents"]); + const candidate = response.candidates[0]; + const parts = candidate.content == null || typeof candidate.content !== "object" || !("parts" in candidate.content) ? [] : candidate.content.parts; + const toolCalls = getToolCallsFromParts({ + parts, + generateId: this.config.generateId + }); + const usageMetadata = response.usageMetadata; + return { + text: getTextFromParts(parts), + files: (_a15 = getInlineDataParts(parts)) == null ? void 0 : _a15.map((part) => ({ + data: part.inlineData.data, + mimeType: part.inlineData.mimeType + })), + toolCalls, + finishReason: mapGoogleGenerativeAIFinishReason({ + finishReason: candidate.finishReason, + hasToolCalls: toolCalls != null && toolCalls.length > 0 + }), + usage: { + promptTokens: (_b = usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) != null ? _b : NaN, + completionTokens: (_c = usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) != null ? _c : NaN + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + warnings, + providerMetadata: { + google: { + groundingMetadata: (_d = candidate.groundingMetadata) != null ? _d : null, + safetyRatings: (_e = candidate.safetyRatings) != null ? _e : null + } + }, + sources: extractSources({ + groundingMetadata: candidate.groundingMetadata, + generateId: this.config.generateId + }), + request: { body } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = yield this.getArgs(options); + const body = JSON.stringify(args); + const headers = combineHeaders( + yield resolve(this.config.headers), + options.headers + ); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: `${this.config.baseURL}/${getModelPath( + this.modelId + )}:streamGenerateContent?alt=sse`, + headers, + body: args, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(chunkSchema), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { contents: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["contents"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + let providerMetadata = void 0; + const generateId2 = this.config.generateId; + let hasToolCalls = false; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c, _d, _e, _f; + if (!chunk.success) { + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + const usageMetadata = value.usageMetadata; + if (usageMetadata != null) { + usage = { + promptTokens: (_a16 = usageMetadata.promptTokenCount) != null ? _a16 : NaN, + completionTokens: (_b = usageMetadata.candidatesTokenCount) != null ? _b : NaN + }; + } + const candidate = (_c = value.candidates) == null ? void 0 : _c[0]; + if (candidate == null) { + return; + } + const content = candidate.content; + if (content != null) { + const deltaText = getTextFromParts(content.parts); + if (deltaText != null) { + controller.enqueue({ + type: "text-delta", + textDelta: deltaText + }); + } + const inlineDataParts = getInlineDataParts(content.parts); + if (inlineDataParts != null) { + for (const part of inlineDataParts) { + controller.enqueue({ + type: "file", + mimeType: part.inlineData.mimeType, + data: part.inlineData.data + }); + } + } + const toolCallDeltas = getToolCallsFromParts({ + parts: content.parts, + generateId: generateId2 + }); + if (toolCallDeltas != null) { + for (const toolCall of toolCallDeltas) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + argsTextDelta: toolCall.args + }); + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + args: toolCall.args + }); + hasToolCalls = true; + } + } + } + if (candidate.finishReason != null) { + finishReason = mapGoogleGenerativeAIFinishReason({ + finishReason: candidate.finishReason, + hasToolCalls + }); + const sources = (_d = extractSources({ + groundingMetadata: candidate.groundingMetadata, + generateId: generateId2 + })) != null ? _d : []; + for (const source of sources) { + controller.enqueue({ type: "source", source }); + } + providerMetadata = { + google: { + groundingMetadata: (_e = candidate.groundingMetadata) != null ? _e : null, + safetyRatings: (_f = candidate.safetyRatings) != null ? _f : null + } + }; + } + }, + flush(controller) { + controller.enqueue({ + type: "finish", + finishReason, + usage, + providerMetadata + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body } + }; + }); + } +}; +function getToolCallsFromParts({ + parts, + generateId: generateId2 +}) { + const functionCallParts = parts == null ? void 0 : parts.filter( + (part) => "functionCall" in part + ); + return functionCallParts == null || functionCallParts.length === 0 ? void 0 : functionCallParts.map((part) => ({ + toolCallType: "function", + toolCallId: generateId2(), + toolName: part.functionCall.name, + args: JSON.stringify(part.functionCall.args) + })); +} +function getTextFromParts(parts) { + const textParts = parts == null ? void 0 : parts.filter((part) => "text" in part); + return textParts == null || textParts.length === 0 ? void 0 : textParts.map((part) => part.text).join(""); +} +function getInlineDataParts(parts) { + return parts == null ? void 0 : parts.filter( + (part) => "inlineData" in part + ); +} +function extractSources({ + groundingMetadata, + generateId: generateId2 +}) { + var _a15; + return (_a15 = groundingMetadata == null ? void 0 : groundingMetadata.groundingChunks) == null ? void 0 : _a15.filter( + (chunk) => chunk.web != null + ).map((chunk) => ({ + sourceType: "url", + id: generateId2(), + url: chunk.web.uri, + title: chunk.web.title + })); +} +var contentSchema = import_zod14.z.object({ + role: import_zod14.z.string(), + parts: import_zod14.z.array( + import_zod14.z.union([ + import_zod14.z.object({ + text: import_zod14.z.string() + }), + import_zod14.z.object({ + functionCall: import_zod14.z.object({ + name: import_zod14.z.string(), + args: import_zod14.z.unknown() + }) + }), + import_zod14.z.object({ + inlineData: import_zod14.z.object({ + mimeType: import_zod14.z.string(), + data: import_zod14.z.string() + }) + }) + ]) + ).nullish() +}); +var groundingChunkSchema = import_zod14.z.object({ + web: import_zod14.z.object({ uri: import_zod14.z.string(), title: import_zod14.z.string() }).nullish(), + retrievedContext: import_zod14.z.object({ uri: import_zod14.z.string(), title: import_zod14.z.string() }).nullish() +}); +var groundingMetadataSchema = import_zod14.z.object({ + webSearchQueries: import_zod14.z.array(import_zod14.z.string()).nullish(), + retrievalQueries: import_zod14.z.array(import_zod14.z.string()).nullish(), + searchEntryPoint: import_zod14.z.object({ renderedContent: import_zod14.z.string() }).nullish(), + groundingChunks: import_zod14.z.array(groundingChunkSchema).nullish(), + groundingSupports: import_zod14.z.array( + import_zod14.z.object({ + segment: import_zod14.z.object({ + startIndex: import_zod14.z.number().nullish(), + endIndex: import_zod14.z.number().nullish(), + text: import_zod14.z.string().nullish() + }), + segment_text: import_zod14.z.string().nullish(), + groundingChunkIndices: import_zod14.z.array(import_zod14.z.number()).nullish(), + supportChunkIndices: import_zod14.z.array(import_zod14.z.number()).nullish(), + confidenceScores: import_zod14.z.array(import_zod14.z.number()).nullish(), + confidenceScore: import_zod14.z.array(import_zod14.z.number()).nullish() + }) + ).nullish(), + retrievalMetadata: import_zod14.z.union([ + import_zod14.z.object({ + webDynamicRetrievalScore: import_zod14.z.number() + }), + import_zod14.z.object({}) + ]).nullish() +}); +var safetyRatingSchema = import_zod14.z.object({ + category: import_zod14.z.string(), + probability: import_zod14.z.string(), + probabilityScore: import_zod14.z.number().nullish(), + severity: import_zod14.z.string().nullish(), + severityScore: import_zod14.z.number().nullish(), + blocked: import_zod14.z.boolean().nullish() +}); +var responseSchema = import_zod14.z.object({ + candidates: import_zod14.z.array( + import_zod14.z.object({ + content: contentSchema.nullish().or(import_zod14.z.object({}).strict()), + finishReason: import_zod14.z.string().nullish(), + safetyRatings: import_zod14.z.array(safetyRatingSchema).nullish(), + groundingMetadata: groundingMetadataSchema.nullish() + }) + ), + usageMetadata: import_zod14.z.object({ + promptTokenCount: import_zod14.z.number().nullish(), + candidatesTokenCount: import_zod14.z.number().nullish(), + totalTokenCount: import_zod14.z.number().nullish() + }).nullish() +}); +var chunkSchema = import_zod14.z.object({ + candidates: import_zod14.z.array( + import_zod14.z.object({ + content: contentSchema.nullish(), + finishReason: import_zod14.z.string().nullish(), + safetyRatings: import_zod14.z.array(safetyRatingSchema).nullish(), + groundingMetadata: groundingMetadataSchema.nullish() + }) + ).nullish(), + usageMetadata: import_zod14.z.object({ + promptTokenCount: import_zod14.z.number().nullish(), + candidatesTokenCount: import_zod14.z.number().nullish(), + totalTokenCount: import_zod14.z.number().nullish() + }).nullish() +}); +var googleGenerativeAIProviderOptionsSchema = import_zod14.z.object({ + responseModalities: import_zod14.z.array(import_zod14.z.enum(["TEXT", "IMAGE"])).nullish(), + thinkingConfig: import_zod14.z.object({ + thinkingBudget: import_zod14.z.number().nullish() + }).nullish() +}); +var GoogleGenerativeAIEmbeddingModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + return 2048; + } + get supportsParallelCalls() { + return true; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + values, + headers, + abortSignal + }) { + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + } + const mergedHeaders = combineHeaders( + yield resolve(this.config.headers), + headers + ); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: `${this.config.baseURL}/models/${this.modelId}:batchEmbedContents`, + headers: mergedHeaders, + body: { + requests: values.map((value) => ({ + model: `models/${this.modelId}`, + content: { role: "user", parts: [{ text: value }] }, + outputDimensionality: this.settings.outputDimensionality, + taskType: this.settings.taskType + })) + }, + failedResponseHandler: googleFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + googleGenerativeAITextEmbeddingResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + embeddings: response.embeddings.map((item) => item.values), + usage: void 0, + rawResponse: { headers: responseHeaders } + }; + }); + } +}; +var googleGenerativeAITextEmbeddingResponseSchema = import_zod16.z.object({ + embeddings: import_zod16.z.array(import_zod16.z.object({ values: import_zod16.z.array(import_zod16.z.number()) })) +}); +function isSupportedFileUrl(url) { + return url.toString().startsWith("https://generativelanguage.googleapis.com/v1beta/files/"); +} +function createGoogleGenerativeAI(options = {}) { + var _a15; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://generativelanguage.googleapis.com/v1beta"; + const getHeaders = () => __spreadValues({ + "x-goog-api-key": loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "GOOGLE_GENERATIVE_AI_API_KEY", + description: "Google Generative AI" + }) + }, options.headers); + const createChatModel = (modelId, settings = {}) => { + var _a22; + return new GoogleGenerativeAILanguageModel(modelId, settings, { + provider: "google.generative-ai", + baseURL, + headers: getHeaders, + generateId: (_a22 = options.generateId) != null ? _a22 : generateId, + isSupportedUrl: isSupportedFileUrl, + fetch: options.fetch + }); + }; + const createEmbeddingModel = (modelId, settings = {}) => new GoogleGenerativeAIEmbeddingModel(modelId, settings, { + provider: "google.generative-ai", + baseURL, + headers: getHeaders, + fetch: options.fetch + }); + const provider = function(modelId, settings) { + if (new.target) { + throw new Error( + "The Google Generative AI model function cannot be called with the new keyword." + ); + } + return createChatModel(modelId, settings); + }; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.generativeAI = createChatModel; + provider.embedding = createEmbeddingModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + return provider; +} +var google = createGoogleGenerativeAI(); + +// node_modules/.pnpm/@ai-sdk+openai-compatible@0.2.13_zod@3.25.67/node_modules/@ai-sdk/openai-compatible/dist/index.mjs +var import_zod17 = require("zod"); +var import_zod18 = require("zod"); +var import_zod19 = require("zod"); +var import_zod20 = require("zod"); +var import_zod21 = require("zod"); +function getOpenAIMetadata(message) { + var _a15, _b; + return (_b = (_a15 = message == null ? void 0 : message.providerMetadata) == null ? void 0 : _a15.openaiCompatible) != null ? _b : {}; +} +function convertToOpenAICompatibleChatMessages(prompt) { + const messages = []; + for (const _a15 of prompt) { + const _b = _a15, { role, content } = _b, message = __objRest(_b, ["role", "content"]); + const metadata = getOpenAIMetadata(__spreadValues({}, message)); + switch (role) { + case "system": { + messages.push(__spreadValues({ role: "system", content }, metadata)); + break; + } + case "user": { + if (content.length === 1 && content[0].type === "text") { + messages.push(__spreadValues({ + role: "user", + content: content[0].text + }, getOpenAIMetadata(content[0]))); + break; + } + messages.push(__spreadValues({ + role: "user", + content: content.map((part) => { + var _a16; + const partMetadata = getOpenAIMetadata(part); + switch (part.type) { + case "text": { + return __spreadValues({ type: "text", text: part.text }, partMetadata); + } + case "image": { + return __spreadValues({ + type: "image_url", + image_url: { + url: part.image instanceof URL ? part.image.toString() : `data:${(_a16 = part.mimeType) != null ? _a16 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}` + } + }, partMetadata); + } + case "file": { + throw new UnsupportedFunctionalityError({ + functionality: "File content parts in user messages" + }); + } + } + }) + }, metadata)); + break; + } + case "assistant": { + let text = ""; + const toolCalls = []; + for (const part of content) { + const partMetadata = getOpenAIMetadata(part); + switch (part.type) { + case "text": { + text += part.text; + break; + } + case "tool-call": { + toolCalls.push(__spreadValues({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.args) + } + }, partMetadata)); + break; + } + } + } + messages.push(__spreadValues({ + role: "assistant", + content: text, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }, metadata)); + break; + } + case "tool": { + for (const toolResponse of content) { + const toolResponseMetadata = getOpenAIMetadata(toolResponse); + messages.push(__spreadValues({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: JSON.stringify(toolResponse.result) + }, toolResponseMetadata)); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return messages; +} +function getResponseMetadata2({ + id, + model, + created +}) { + return { + id: id != null ? id : void 0, + modelId: model != null ? model : void 0, + timestamp: created != null ? new Date(created * 1e3) : void 0 + }; +} +function mapOpenAICompatibleFinishReason(finishReason) { + switch (finishReason) { + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "unknown"; + } +} +var openaiCompatibleErrorDataSchema = import_zod18.z.object({ + error: import_zod18.z.object({ + message: import_zod18.z.string(), + // The additional information below is handled loosely to support + // OpenAI-compatible providers that have slightly different error + // responses: + type: import_zod18.z.string().nullish(), + param: import_zod18.z.any().nullish(), + code: import_zod18.z.union([import_zod18.z.string(), import_zod18.z.number()]).nullish() + }) +}); +var defaultOpenAICompatibleErrorStructure = { + errorSchema: openaiCompatibleErrorDataSchema, + errorToMessage: (data) => data.error.message +}; +function prepareTools4({ + mode, + structuredOutputs +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + const openaiCompatTools = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + openaiCompatTools.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters + } + }); + } + } + if (toolChoice == null) { + return { tools: openaiCompatTools, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: openaiCompatTools, tool_choice: type, toolWarnings }; + case "tool": + return { + tools: openaiCompatTools, + tool_choice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var OpenAICompatibleChatLanguageModel = class { + // type inferred via constructor + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + var _a15, _b; + this.modelId = modelId; + this.settings = settings; + this.config = config; + const errorStructure = (_a15 = config.errorStructure) != null ? _a15 : defaultOpenAICompatibleErrorStructure; + this.chunkSchema = createOpenAICompatibleChatChunkSchema( + errorStructure.errorSchema + ); + this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure); + this.supportsStructuredOutputs = (_b = config.supportsStructuredOutputs) != null ? _b : false; + } + get defaultObjectGenerationMode() { + return this.config.defaultObjectGenerationMode; + } + get provider() { + return this.config.provider; + } + get providerOptionsName() { + return this.config.provider.split(".")[0].trim(); + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + providerMetadata, + stopSequences, + responseFormat, + seed + }) { + var _a15, _b, _c, _d, _e; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format schema is only supported with structuredOutputs" + }); + } + const baseArgs = __spreadProps(__spreadValues({ + // model id: + model: this.modelId, + // model specific settings: + user: this.settings.user, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs === true && responseFormat.schema != null ? { + type: "json_schema", + json_schema: { + schema: responseFormat.schema, + name: (_a15 = responseFormat.name) != null ? _a15 : "response", + description: responseFormat.description + } + } : { type: "json_object" } : void 0, + stop: stopSequences, + seed + }, providerMetadata == null ? void 0 : providerMetadata[this.providerOptionsName]), { + reasoning_effort: (_d = (_b = providerMetadata == null ? void 0 : providerMetadata[this.providerOptionsName]) == null ? void 0 : _b.reasoningEffort) != null ? _d : (_c = providerMetadata == null ? void 0 : providerMetadata["openai-compatible"]) == null ? void 0 : _c.reasoningEffort, + // messages: + messages: convertToOpenAICompatibleChatMessages(prompt) + }); + switch (type) { + case "regular": { + const { tools, tool_choice, toolWarnings } = prepareTools4({ + mode, + structuredOutputs: this.supportsStructuredOutputs + }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { tools, tool_choice }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: this.supportsStructuredOutputs === true && mode.schema != null ? { + type: "json_schema", + json_schema: { + schema: mode.schema, + name: (_e = mode.name) != null ? _e : "response", + description: mode.description + } + } : { type: "json_object" } + }), + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { + type: "function", + function: { name: mode.tool.name } + }, + tools: [ + { + type: "function", + function: { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters + } + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + const { args, warnings } = this.getArgs(__spreadValues({}, options)); + const body = JSON.stringify(args); + const { + responseHeaders, + value: responseBody, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + OpenAICompatibleChatResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = responseBody.choices[0]; + const providerMetadata = __spreadValues({ + [this.providerOptionsName]: {} + }, (_b = (_a15 = this.config.metadataExtractor) == null ? void 0 : _a15.extractMetadata) == null ? void 0 : _b.call(_a15, { + parsedBody: rawResponse + })); + const completionTokenDetails = (_c = responseBody.usage) == null ? void 0 : _c.completion_tokens_details; + const promptTokenDetails = (_d = responseBody.usage) == null ? void 0 : _d.prompt_tokens_details; + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null) { + providerMetadata[this.providerOptionsName].reasoningTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { + providerMetadata[this.providerOptionsName].acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { + providerMetadata[this.providerOptionsName].rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; + } + if ((promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null) { + providerMetadata[this.providerOptionsName].cachedPromptTokens = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens; + } + return { + text: (_e = choice.message.content) != null ? _e : void 0, + reasoning: (_f = choice.message.reasoning_content) != null ? _f : void 0, + toolCalls: (_g = choice.message.tool_calls) == null ? void 0 : _g.map((toolCall) => { + var _a22; + return { + toolCallType: "function", + toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }; + }), + finishReason: mapOpenAICompatibleFinishReason(choice.finish_reason), + usage: { + promptTokens: (_i = (_h = responseBody.usage) == null ? void 0 : _h.prompt_tokens) != null ? _i : NaN, + completionTokens: (_k = (_j = responseBody.usage) == null ? void 0 : _j.completion_tokens) != null ? _k : NaN + }, + providerMetadata, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + response: getResponseMetadata2(responseBody), + warnings, + request: { body } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + var _a15; + if (this.settings.simulateStreaming) { + const result = yield this.doGenerate(options); + const simulatedStream = new ReadableStream({ + start(controller) { + controller.enqueue(__spreadValues({ type: "response-metadata" }, result.response)); + if (result.reasoning) { + if (Array.isArray(result.reasoning)) { + for (const part of result.reasoning) { + if (part.type === "text") { + controller.enqueue({ + type: "reasoning", + textDelta: part.text + }); + } + } + } else { + controller.enqueue({ + type: "reasoning", + textDelta: result.reasoning + }); + } + } + if (result.text) { + controller.enqueue({ + type: "text-delta", + textDelta: result.text + }); + } + if (result.toolCalls) { + for (const toolCall of result.toolCalls) { + controller.enqueue(__spreadValues({ + type: "tool-call" + }, toolCall)); + } + } + controller.enqueue({ + type: "finish", + finishReason: result.finishReason, + usage: result.usage, + logprobs: result.logprobs, + providerMetadata: result.providerMetadata + }); + controller.close(); + } + }); + return { + stream: simulatedStream, + rawCall: result.rawCall, + rawResponse: result.rawResponse, + warnings: result.warnings + }; + } + const { args, warnings } = this.getArgs(__spreadValues({}, options)); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.includeUsage ? { include_usage: true } : void 0 + }); + const metadataExtractor = (_a15 = this.config.metadataExtractor) == null ? void 0 : _a15.createStreamExtractor(); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + this.chunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const toolCalls = []; + let finishReason = "unknown"; + let usage = { + completionTokens: void 0, + completionTokensDetails: { + reasoningTokens: void 0, + acceptedPredictionTokens: void 0, + rejectedPredictionTokens: void 0 + }, + promptTokens: void 0, + promptTokensDetails: { + cachedTokens: void 0 + } + }; + let isFirstChunk = true; + let providerOptionsName = this.providerOptionsName; + return { + stream: response.pipeThrough( + new TransformStream({ + // TODO we lost type safety on Chunk, most likely due to the error schema. MUST FIX + transform(chunk, controller) { + var _a22, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + metadataExtractor == null ? void 0 : metadataExtractor.processChunk(chunk.rawValue); + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error.message }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata2(value))); + } + if (value.usage != null) { + const { + prompt_tokens, + completion_tokens, + prompt_tokens_details, + completion_tokens_details + } = value.usage; + usage.promptTokens = prompt_tokens != null ? prompt_tokens : void 0; + usage.completionTokens = completion_tokens != null ? completion_tokens : void 0; + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) { + usage.completionTokensDetails.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) { + usage.completionTokensDetails.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) { + usage.completionTokensDetails.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens; + } + if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) { + usage.promptTokensDetails.cachedTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens; + } + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAICompatibleFinishReason( + choice.finish_reason + ); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + if (delta.reasoning_content != null) { + controller.enqueue({ + type: "reasoning", + textDelta: delta.reasoning_content + }); + } + if (delta.content != null) { + controller.enqueue({ + type: "text-delta", + textDelta: delta.content + }); + } + if (delta.tool_calls != null) { + for (const toolCallDelta of delta.tool_calls) { + const index = toolCallDelta.index; + if (toolCalls[index] == null) { + if (toolCallDelta.type !== "function") { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function' type.` + }); + } + if (toolCallDelta.id == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'id' to be a string.` + }); + } + if (((_a22 = toolCallDelta.function) == null ? void 0 : _a22.name) == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function.name' to be a string.` + }); + } + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: (_b = toolCallDelta.function.arguments) != null ? _b : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) { + if (toolCall2.function.arguments.length > 0) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall2.id, + toolName: toolCall2.function.name, + argsTextDelta: toolCall2.function.arguments + }); + } + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_e = toolCall2.id) != null ? _e : generateId(), + toolName: toolCall2.function.name, + args: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (toolCall.hasFinished) { + continue; + } + if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) { + toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : ""; + } + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : "" + }); + if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_l = toolCall.id) != null ? _l : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + }, + flush(controller) { + var _a22, _b; + const providerMetadata = __spreadValues({ + [providerOptionsName]: {} + }, metadataExtractor == null ? void 0 : metadataExtractor.buildMetadata()); + if (usage.completionTokensDetails.reasoningTokens != null) { + providerMetadata[providerOptionsName].reasoningTokens = usage.completionTokensDetails.reasoningTokens; + } + if (usage.completionTokensDetails.acceptedPredictionTokens != null) { + providerMetadata[providerOptionsName].acceptedPredictionTokens = usage.completionTokensDetails.acceptedPredictionTokens; + } + if (usage.completionTokensDetails.rejectedPredictionTokens != null) { + providerMetadata[providerOptionsName].rejectedPredictionTokens = usage.completionTokensDetails.rejectedPredictionTokens; + } + if (usage.promptTokensDetails.cachedTokens != null) { + providerMetadata[providerOptionsName].cachedPromptTokens = usage.promptTokensDetails.cachedTokens; + } + controller.enqueue({ + type: "finish", + finishReason, + usage: { + promptTokens: (_a22 = usage.promptTokens) != null ? _a22 : NaN, + completionTokens: (_b = usage.completionTokens) != null ? _b : NaN + }, + providerMetadata + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body: JSON.stringify(body) } + }; + }); + } +}; +var openaiCompatibleTokenUsageSchema = import_zod17.z.object({ + prompt_tokens: import_zod17.z.number().nullish(), + completion_tokens: import_zod17.z.number().nullish(), + prompt_tokens_details: import_zod17.z.object({ + cached_tokens: import_zod17.z.number().nullish() + }).nullish(), + completion_tokens_details: import_zod17.z.object({ + reasoning_tokens: import_zod17.z.number().nullish(), + accepted_prediction_tokens: import_zod17.z.number().nullish(), + rejected_prediction_tokens: import_zod17.z.number().nullish() + }).nullish() +}).nullish(); +var OpenAICompatibleChatResponseSchema = import_zod17.z.object({ + id: import_zod17.z.string().nullish(), + created: import_zod17.z.number().nullish(), + model: import_zod17.z.string().nullish(), + choices: import_zod17.z.array( + import_zod17.z.object({ + message: import_zod17.z.object({ + role: import_zod17.z.literal("assistant").nullish(), + content: import_zod17.z.string().nullish(), + reasoning_content: import_zod17.z.string().nullish(), + tool_calls: import_zod17.z.array( + import_zod17.z.object({ + id: import_zod17.z.string().nullish(), + type: import_zod17.z.literal("function"), + function: import_zod17.z.object({ + name: import_zod17.z.string(), + arguments: import_zod17.z.string() + }) + }) + ).nullish() + }), + finish_reason: import_zod17.z.string().nullish() + }) + ), + usage: openaiCompatibleTokenUsageSchema +}); +var createOpenAICompatibleChatChunkSchema = (errorSchema) => import_zod17.z.union([ + import_zod17.z.object({ + id: import_zod17.z.string().nullish(), + created: import_zod17.z.number().nullish(), + model: import_zod17.z.string().nullish(), + choices: import_zod17.z.array( + import_zod17.z.object({ + delta: import_zod17.z.object({ + role: import_zod17.z.enum(["assistant"]).nullish(), + content: import_zod17.z.string().nullish(), + reasoning_content: import_zod17.z.string().nullish(), + tool_calls: import_zod17.z.array( + import_zod17.z.object({ + index: import_zod17.z.number(), + id: import_zod17.z.string().nullish(), + type: import_zod17.z.literal("function").nullish(), + function: import_zod17.z.object({ + name: import_zod17.z.string().nullish(), + arguments: import_zod17.z.string().nullish() + }) + }) + ).nullish() + }).nullish(), + finish_reason: import_zod17.z.string().nullish() + }) + ), + usage: openaiCompatibleTokenUsageSchema + }), + errorSchema +]); +function convertToOpenAICompatibleCompletionPrompt({ + prompt, + inputFormat, + user = "user", + assistant = "assistant" +}) { + if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") { + return { prompt: prompt[0].content[0].text }; + } + let text = ""; + if (prompt[0].role === "system") { + text += `${prompt[0].content} + +`; + prompt = prompt.slice(1); + } + for (const { role, content } of prompt) { + switch (role) { + case "system": { + throw new InvalidPromptError({ + message: "Unexpected system message in prompt: ${content}", + prompt + }); + } + case "user": { + const userMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "image": { + throw new UnsupportedFunctionalityError({ + functionality: "images" + }); + } + } + }).join(""); + text += `${user}: +${userMessage} + +`; + break; + } + case "assistant": { + const assistantMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "tool-call": { + throw new UnsupportedFunctionalityError({ + functionality: "tool-call messages" + }); + } + } + }).join(""); + text += `${assistant}: +${assistantMessage} + +`; + break; + } + case "tool": { + throw new UnsupportedFunctionalityError({ + functionality: "tool messages" + }); + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + text += `${assistant}: +`; + return { + prompt: text, + stopSequences: [` +${user}:`] + }; +} +var OpenAICompatibleCompletionLanguageModel = class { + // type inferred via constructor + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = void 0; + var _a15; + this.modelId = modelId; + this.settings = settings; + this.config = config; + const errorStructure = (_a15 = config.errorStructure) != null ? _a15 : defaultOpenAICompatibleErrorStructure; + this.chunkSchema = createOpenAICompatibleCompletionChunkSchema( + errorStructure.errorSchema + ); + this.failedResponseHandler = createJsonErrorResponseHandler(errorStructure); + } + get provider() { + return this.config.provider; + } + get providerOptionsName() { + return this.config.provider.split(".")[0].trim(); + } + getArgs({ + mode, + inputFormat, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences: userStopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (responseFormat != null && responseFormat.type !== "text") { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format is not supported." + }); + } + const { prompt: completionPrompt, stopSequences } = convertToOpenAICompatibleCompletionPrompt({ prompt, inputFormat }); + const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; + const baseArgs = __spreadProps(__spreadValues({ + // model id: + model: this.modelId, + // model specific settings: + echo: this.settings.echo, + logit_bias: this.settings.logitBias, + suffix: this.settings.suffix, + user: this.settings.user, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + seed + }, providerMetadata == null ? void 0 : providerMetadata[this.providerOptionsName]), { + // prompt: + prompt: completionPrompt, + // stop sequences: + stop: stop.length > 0 ? stop : void 0 + }); + switch (type) { + case "regular": { + if ((_a15 = mode.tools) == null ? void 0 : _a15.length) { + throw new UnsupportedFunctionalityError({ + functionality: "tools" + }); + } + if (mode.toolChoice) { + throw new UnsupportedFunctionalityError({ + functionality: "toolChoice" + }); + } + return { args: baseArgs, warnings }; + } + case "object-json": { + throw new UnsupportedFunctionalityError({ + functionality: "object-json mode" + }); + } + case "object-tool": { + throw new UnsupportedFunctionalityError({ + functionality: "object-tool mode" + }); + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d; + const { args, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + openaiCompatibleCompletionResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { prompt: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["prompt"]); + const choice = response.choices[0]; + return { + text: choice.text, + usage: { + promptTokens: (_b = (_a15 = response.usage) == null ? void 0 : _a15.prompt_tokens) != null ? _b : NaN, + completionTokens: (_d = (_c = response.usage) == null ? void 0 : _c.completion_tokens) != null ? _d : NaN + }, + finishReason: mapOpenAICompatibleFinishReason(choice.finish_reason), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + response: getResponseMetadata2(response), + warnings, + request: { body: JSON.stringify(args) } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.includeUsage ? { include_usage: true } : void 0 + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: this.failedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + this.chunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { prompt: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["prompt"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + let isFirstChunk = true; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata2(value))); + } + if (value.usage != null) { + usage = { + promptTokens: value.usage.prompt_tokens, + completionTokens: value.usage.completion_tokens + }; + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAICompatibleFinishReason( + choice.finish_reason + ); + } + if ((choice == null ? void 0 : choice.text) != null) { + controller.enqueue({ + type: "text-delta", + textDelta: choice.text + }); + } + }, + flush(controller) { + controller.enqueue({ + type: "finish", + finishReason, + usage + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body: JSON.stringify(body) } + }; + }); + } +}; +var openaiCompatibleCompletionResponseSchema = import_zod19.z.object({ + id: import_zod19.z.string().nullish(), + created: import_zod19.z.number().nullish(), + model: import_zod19.z.string().nullish(), + choices: import_zod19.z.array( + import_zod19.z.object({ + text: import_zod19.z.string(), + finish_reason: import_zod19.z.string() + }) + ), + usage: import_zod19.z.object({ + prompt_tokens: import_zod19.z.number(), + completion_tokens: import_zod19.z.number() + }).nullish() +}); +var createOpenAICompatibleCompletionChunkSchema = (errorSchema) => import_zod19.z.union([ + import_zod19.z.object({ + id: import_zod19.z.string().nullish(), + created: import_zod19.z.number().nullish(), + model: import_zod19.z.string().nullish(), + choices: import_zod19.z.array( + import_zod19.z.object({ + text: import_zod19.z.string(), + finish_reason: import_zod19.z.string().nullish(), + index: import_zod19.z.number() + }) + ), + usage: import_zod19.z.object({ + prompt_tokens: import_zod19.z.number(), + completion_tokens: import_zod19.z.number() + }).nullish() + }), + errorSchema +]); +var OpenAICompatibleEmbeddingModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + var _a15; + return (_a15 = this.config.maxEmbeddingsPerCall) != null ? _a15 : 2048; + } + get supportsParallelCalls() { + var _a15; + return (_a15 = this.config.supportsParallelCalls) != null ? _a15 : true; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + values, + headers, + abortSignal + }) { + var _a15; + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + } + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/embeddings", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + input: values, + encoding_format: "float", + dimensions: this.settings.dimensions, + user: this.settings.user + }, + failedResponseHandler: createJsonErrorResponseHandler( + (_a15 = this.config.errorStructure) != null ? _a15 : defaultOpenAICompatibleErrorStructure + ), + successfulResponseHandler: createJsonResponseHandler( + openaiTextEmbeddingResponseSchema2 + ), + abortSignal, + fetch: this.config.fetch + }); + return { + embeddings: response.data.map((item) => item.embedding), + usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, + rawResponse: { headers: responseHeaders } + }; + }); + } +}; +var openaiTextEmbeddingResponseSchema2 = import_zod20.z.object({ + data: import_zod20.z.array(import_zod20.z.object({ embedding: import_zod20.z.array(import_zod20.z.number()) })), + usage: import_zod20.z.object({ prompt_tokens: import_zod20.z.number() }).nullish() +}); +var OpenAICompatibleImageModel = class { + constructor(modelId, settings, config) { + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v1"; + } + get maxImagesPerCall() { + var _a15; + return (_a15 = this.settings.maxImagesPerCall) != null ? _a15 : 10; + } + get provider() { + return this.config.provider; + } + doGenerate(_0) { + return __async(this, arguments, function* ({ + prompt, + n, + size, + aspectRatio, + seed, + providerOptions, + headers, + abortSignal + }) { + var _a15, _b, _c, _d, _e; + const warnings = []; + if (aspectRatio != null) { + warnings.push({ + type: "unsupported-setting", + setting: "aspectRatio", + details: "This model does not support aspect ratio. Use `size` instead." + }); + } + if (seed != null) { + warnings.push({ type: "unsupported-setting", setting: "seed" }); + } + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { value: response, responseHeaders } = yield postJsonToApi({ + url: this.config.url({ + path: "/images/generations", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: __spreadValues(__spreadProps(__spreadValues({ + model: this.modelId, + prompt, + n, + size + }, (_d = providerOptions.openai) != null ? _d : {}), { + response_format: "b64_json" + }), this.settings.user ? { user: this.settings.user } : {}), + failedResponseHandler: createJsonErrorResponseHandler( + (_e = this.config.errorStructure) != null ? _e : defaultOpenAICompatibleErrorStructure + ), + successfulResponseHandler: createJsonResponseHandler( + openaiCompatibleImageResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.data.map((item) => item.b64_json), + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + } + }; + }); + } +}; +var openaiCompatibleImageResponseSchema = import_zod21.z.object({ + data: import_zod21.z.array(import_zod21.z.object({ b64_json: import_zod21.z.string() })) +}); + +// node_modules/.pnpm/@ai-sdk+xai@1.2.15_zod@3.25.67/node_modules/@ai-sdk/xai/dist/index.mjs +var import_zod22 = require("zod"); +function supportsStructuredOutputs(modelId) { + return [ + "grok-3", + "grok-3-beta", + "grok-3-latest", + "grok-3-fast", + "grok-3-fast-beta", + "grok-3-fast-latest", + "grok-3-mini", + "grok-3-mini-beta", + "grok-3-mini-latest", + "grok-3-mini-fast", + "grok-3-mini-fast-beta", + "grok-3-mini-fast-latest", + "grok-2-1212", + "grok-2-vision-1212" + ].includes(modelId); +} +var xaiErrorSchema = import_zod22.z.object({ + code: import_zod22.z.string(), + error: import_zod22.z.string() +}); +var xaiErrorStructure = { + errorSchema: xaiErrorSchema, + errorToMessage: (data) => data.error +}; +function createXai(options = {}) { + var _a15; + const baseURL = withoutTrailingSlash( + (_a15 = options.baseURL) != null ? _a15 : "https://api.x.ai/v1" + ); + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "XAI_API_KEY", + description: "xAI API key" + })}` + }, options.headers); + const createLanguageModel = (modelId, settings = {}) => { + const structuredOutputs = supportsStructuredOutputs(modelId); + return new OpenAICompatibleChatLanguageModel(modelId, settings, { + provider: "xai.chat", + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch, + defaultObjectGenerationMode: structuredOutputs ? "json" : "tool", + errorStructure: xaiErrorStructure, + supportsStructuredOutputs: structuredOutputs, + includeUsage: true + }); + }; + const createImageModel = (modelId, settings = {}) => { + return new OpenAICompatibleImageModel(modelId, settings, { + provider: "xai.image", + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch, + errorStructure: xaiErrorStructure + }); + }; + const provider = (modelId, settings) => createLanguageModel(modelId, settings); + provider.languageModel = createLanguageModel; + provider.chat = createLanguageModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + provider.imageModel = createImageModel; + provider.image = createImageModel; + return provider; +} +var xai = createXai(); + +// node_modules/.pnpm/@ai-sdk+openai@1.3.21_zod@3.25.67/node_modules/@ai-sdk/openai/internal/dist/index.mjs +var import_zod23 = require("zod"); +var import_zod24 = require("zod"); +var import_zod25 = require("zod"); +var import_zod26 = require("zod"); +var import_zod27 = require("zod"); +var import_zod28 = require("zod"); +var import_zod29 = require("zod"); +var import_zod30 = require("zod"); +function convertToOpenAIChatMessages2({ + prompt, + useLegacyFunctionCalling = false, + systemMessageMode = "system" +}) { + const messages = []; + const warnings = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + switch (systemMessageMode) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "developer": { + messages.push({ role: "developer", content }); + break; + } + case "remove": { + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + } + default: { + const _exhaustiveCheck = systemMessageMode; + throw new Error( + `Unsupported system message mode: ${_exhaustiveCheck}` + ); + } + } + break; + } + case "user": { + if (content.length === 1 && content[0].type === "text") { + messages.push({ role: "user", content: content[0].text }); + break; + } + messages.push({ + role: "user", + content: content.map((part, index) => { + var _a15, _b, _c, _d; + switch (part.type) { + case "text": { + return { type: "text", text: part.text }; + } + case "image": { + return { + type: "image_url", + image_url: { + url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`, + // OpenAI specific extension: image detail + detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail + } + }; + } + case "file": { + if (part.data instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "'File content parts with URL data' functionality not supported." + }); + } + switch (part.mimeType) { + case "audio/wav": { + return { + type: "input_audio", + input_audio: { data: part.data, format: "wav" } + }; + } + case "audio/mp3": + case "audio/mpeg": { + return { + type: "input_audio", + input_audio: { data: part.data, format: "mp3" } + }; + } + case "application/pdf": { + return { + type: "file", + file: { + filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${part.data}` + } + }; + } + default: { + throw new UnsupportedFunctionalityError({ + functionality: `File content part type ${part.mimeType} in user messages` + }); + } + } + } + } + }) + }); + break; + } + case "assistant": { + let text = ""; + const toolCalls = []; + for (const part of content) { + switch (part.type) { + case "text": { + text += part.text; + break; + } + case "tool-call": { + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.args) + } + }); + break; + } + } + } + if (useLegacyFunctionCalling) { + if (toolCalls.length > 1) { + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling with multiple tool calls in one message" + }); + } + messages.push({ + role: "assistant", + content: text, + function_call: toolCalls.length > 0 ? toolCalls[0].function : void 0 + }); + } else { + messages.push({ + role: "assistant", + content: text, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + } + break; + } + case "tool": { + for (const toolResponse of content) { + if (useLegacyFunctionCalling) { + messages.push({ + role: "function", + name: toolResponse.toolName, + content: JSON.stringify(toolResponse.result) + }); + } else { + messages.push({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: JSON.stringify(toolResponse.result) + }); + } + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return { messages, warnings }; +} +function mapOpenAIChatLogProbsOutput2(logprobs) { + var _a15, _b; + return (_b = (_a15 = logprobs == null ? void 0 : logprobs.content) == null ? void 0 : _a15.map(({ token, logprob, top_logprobs }) => ({ + token, + logprob, + topLogprobs: top_logprobs ? top_logprobs.map(({ token: token2, logprob: logprob2 }) => ({ + token: token2, + logprob: logprob2 + })) : [] + }))) != null ? _b : void 0; +} +function mapOpenAIFinishReason2(finishReason) { + switch (finishReason) { + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "unknown"; + } +} +var openaiErrorDataSchema2 = import_zod24.z.object({ + error: import_zod24.z.object({ + message: import_zod24.z.string(), + // The additional information below is handled loosely to support + // OpenAI-compatible providers that have slightly different error + // responses: + type: import_zod24.z.string().nullish(), + param: import_zod24.z.any().nullish(), + code: import_zod24.z.union([import_zod24.z.string(), import_zod24.z.number()]).nullish() + }) +}); +var openaiFailedResponseHandler2 = createJsonErrorResponseHandler({ + errorSchema: openaiErrorDataSchema2, + errorToMessage: (data) => data.error.message +}); +function getResponseMetadata3({ + id, + model, + created +}) { + return { + id: id != null ? id : void 0, + modelId: model != null ? model : void 0, + timestamp: created != null ? new Date(created * 1e3) : void 0 + }; +} +function prepareTools5({ + mode, + useLegacyFunctionCalling = false, + structuredOutputs +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + if (useLegacyFunctionCalling) { + const openaiFunctions = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + openaiFunctions.push({ + name: tool.name, + description: tool.description, + parameters: tool.parameters + }); + } + } + if (toolChoice == null) { + return { + functions: openaiFunctions, + function_call: void 0, + toolWarnings + }; + } + const type2 = toolChoice.type; + switch (type2) { + case "auto": + case "none": + case void 0: + return { + functions: openaiFunctions, + function_call: void 0, + toolWarnings + }; + case "required": + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling and toolChoice: required" + }); + default: + return { + functions: openaiFunctions, + function_call: { name: toolChoice.toolName }, + toolWarnings + }; + } + } + const openaiTools2 = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + openaiTools2.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + strict: structuredOutputs ? true : void 0 + } + }); + } + } + if (toolChoice == null) { + return { tools: openaiTools2, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: openaiTools2, tool_choice: type, toolWarnings }; + case "tool": + return { + tools: openaiTools2, + tool_choice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var OpenAIChatLanguageModel2 = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get supportsStructuredOutputs() { + var _a15; + return (_a15 = this.settings.structuredOutputs) != null ? _a15 : isReasoningModel2(this.modelId); + } + get defaultObjectGenerationMode() { + if (isAudioModel2(this.modelId)) { + return "tool"; + } + return this.supportsStructuredOutputs ? "json" : "tool"; + } + get provider() { + return this.config.provider; + } + get supportsImageUrls() { + return !this.settings.downloadImages; + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15, _b, _c, _d, _e, _f, _g, _h; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if ((responseFormat == null ? void 0 : responseFormat.type) === "json" && responseFormat.schema != null && !this.supportsStructuredOutputs) { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format schema is only supported with structuredOutputs" + }); + } + const useLegacyFunctionCalling = this.settings.useLegacyFunctionCalling; + if (useLegacyFunctionCalling && this.settings.parallelToolCalls === true) { + throw new UnsupportedFunctionalityError({ + functionality: "useLegacyFunctionCalling with parallelToolCalls" + }); + } + if (useLegacyFunctionCalling && this.supportsStructuredOutputs) { + throw new UnsupportedFunctionalityError({ + functionality: "structuredOutputs with useLegacyFunctionCalling" + }); + } + const { messages, warnings: messageWarnings } = convertToOpenAIChatMessages2( + { + prompt, + useLegacyFunctionCalling, + systemMessageMode: getSystemMessageMode2(this.modelId) + } + ); + warnings.push(...messageWarnings); + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + logit_bias: this.settings.logitBias, + logprobs: this.settings.logprobs === true || typeof this.settings.logprobs === "number" ? true : void 0, + top_logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0, + user: this.settings.user, + parallel_tool_calls: this.settings.parallelToolCalls, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? this.supportsStructuredOutputs && responseFormat.schema != null ? { + type: "json_schema", + json_schema: { + schema: responseFormat.schema, + strict: true, + name: (_a15 = responseFormat.name) != null ? _a15 : "response", + description: responseFormat.description + } + } : { type: "json_object" } : void 0, + stop: stopSequences, + seed, + // openai specific settings: + // TODO remove in next major version; we auto-map maxTokens now + max_completion_tokens: (_b = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _b.maxCompletionTokens, + store: (_c = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _c.store, + metadata: (_d = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _d.metadata, + prediction: (_e = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _e.prediction, + reasoning_effort: (_g = (_f = providerMetadata == null ? void 0 : providerMetadata.openai) == null ? void 0 : _f.reasoningEffort) != null ? _g : this.settings.reasoningEffort, + // messages: + messages + }; + if (isReasoningModel2(this.modelId)) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (baseArgs.top_p != null) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topP", + details: "topP is not supported for reasoning models" + }); + } + if (baseArgs.frequency_penalty != null) { + baseArgs.frequency_penalty = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty", + details: "frequencyPenalty is not supported for reasoning models" + }); + } + if (baseArgs.presence_penalty != null) { + baseArgs.presence_penalty = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty", + details: "presencePenalty is not supported for reasoning models" + }); + } + if (baseArgs.logit_bias != null) { + baseArgs.logit_bias = void 0; + warnings.push({ + type: "other", + message: "logitBias is not supported for reasoning models" + }); + } + if (baseArgs.logprobs != null) { + baseArgs.logprobs = void 0; + warnings.push({ + type: "other", + message: "logprobs is not supported for reasoning models" + }); + } + if (baseArgs.top_logprobs != null) { + baseArgs.top_logprobs = void 0; + warnings.push({ + type: "other", + message: "topLogprobs is not supported for reasoning models" + }); + } + if (baseArgs.max_tokens != null) { + if (baseArgs.max_completion_tokens == null) { + baseArgs.max_completion_tokens = baseArgs.max_tokens; + } + baseArgs.max_tokens = void 0; + } + } else if (this.modelId.startsWith("gpt-4o-search-preview") || this.modelId.startsWith("gpt-4o-mini-search-preview")) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for the search preview models and has been removed." + }); + } + } + switch (type) { + case "regular": { + const { tools, tool_choice, functions, function_call, toolWarnings } = prepareTools5({ + mode, + useLegacyFunctionCalling, + structuredOutputs: this.supportsStructuredOutputs + }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools, + tool_choice, + functions, + function_call + }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: this.supportsStructuredOutputs && mode.schema != null ? { + type: "json_schema", + json_schema: { + schema: mode.schema, + strict: true, + name: (_h = mode.name) != null ? _h : "response", + description: mode.description + } + } : { type: "json_object" } + }), + warnings + }; + } + case "object-tool": { + return { + args: useLegacyFunctionCalling ? __spreadProps(__spreadValues({}, baseArgs), { + function_call: { + name: mode.tool.name + }, + functions: [ + { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters + } + ] + }) : __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { + type: "function", + function: { name: mode.tool.name } + }, + tools: [ + { + type: "function", + function: { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters, + strict: this.supportsStructuredOutputs ? true : void 0 + } + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g, _h; + const { args: body, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + openaiChatResponseSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = body, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = response.choices[0]; + const completionTokenDetails = (_a15 = response.usage) == null ? void 0 : _a15.completion_tokens_details; + const promptTokenDetails = (_b = response.usage) == null ? void 0 : _b.prompt_tokens_details; + const providerMetadata = { openai: {} }; + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens) != null) { + providerMetadata.openai.reasoningTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.reasoning_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens) != null) { + providerMetadata.openai.acceptedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.accepted_prediction_tokens; + } + if ((completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens) != null) { + providerMetadata.openai.rejectedPredictionTokens = completionTokenDetails == null ? void 0 : completionTokenDetails.rejected_prediction_tokens; + } + if ((promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens) != null) { + providerMetadata.openai.cachedPromptTokens = promptTokenDetails == null ? void 0 : promptTokenDetails.cached_tokens; + } + return { + text: (_c = choice.message.content) != null ? _c : void 0, + toolCalls: this.settings.useLegacyFunctionCalling && choice.message.function_call ? [ + { + toolCallType: "function", + toolCallId: generateId(), + toolName: choice.message.function_call.name, + args: choice.message.function_call.arguments + } + ] : (_d = choice.message.tool_calls) == null ? void 0 : _d.map((toolCall) => { + var _a22; + return { + toolCallType: "function", + toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }; + }), + finishReason: mapOpenAIFinishReason2(choice.finish_reason), + usage: { + promptTokens: (_f = (_e = response.usage) == null ? void 0 : _e.prompt_tokens) != null ? _f : NaN, + completionTokens: (_h = (_g = response.usage) == null ? void 0 : _g.completion_tokens) != null ? _h : NaN + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + request: { body: JSON.stringify(body) }, + response: getResponseMetadata3(response), + warnings, + logprobs: mapOpenAIChatLogProbsOutput2(choice.logprobs), + providerMetadata + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + if (this.settings.simulateStreaming) { + const result = yield this.doGenerate(options); + const simulatedStream = new ReadableStream({ + start(controller) { + controller.enqueue(__spreadValues({ type: "response-metadata" }, result.response)); + if (result.text) { + controller.enqueue({ + type: "text-delta", + textDelta: result.text + }); + } + if (result.toolCalls) { + for (const toolCall of result.toolCalls) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + argsTextDelta: toolCall.args + }); + controller.enqueue(__spreadValues({ + type: "tool-call" + }, toolCall)); + } + } + controller.enqueue({ + type: "finish", + finishReason: result.finishReason, + usage: result.usage, + logprobs: result.logprobs, + providerMetadata: result.providerMetadata + }); + controller.close(); + } + }); + return { + stream: simulatedStream, + rawCall: result.rawCall, + rawResponse: result.rawResponse, + warnings: result.warnings + }; + } + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0 + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createEventSourceResponseHandler( + openaiChatChunkSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + const toolCalls = []; + let finishReason = "unknown"; + let usage = { + promptTokens: void 0, + completionTokens: void 0 + }; + let logprobs; + let isFirstChunk = true; + const { useLegacyFunctionCalling } = this.settings; + const providerMetadata = { openai: {} }; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata3(value))); + } + if (value.usage != null) { + const { + prompt_tokens, + completion_tokens, + prompt_tokens_details, + completion_tokens_details + } = value.usage; + usage = { + promptTokens: prompt_tokens != null ? prompt_tokens : void 0, + completionTokens: completion_tokens != null ? completion_tokens : void 0 + }; + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens) != null) { + providerMetadata.openai.reasoningTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.reasoning_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens) != null) { + providerMetadata.openai.acceptedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.accepted_prediction_tokens; + } + if ((completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens) != null) { + providerMetadata.openai.rejectedPredictionTokens = completion_tokens_details == null ? void 0 : completion_tokens_details.rejected_prediction_tokens; + } + if ((prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens) != null) { + providerMetadata.openai.cachedPromptTokens = prompt_tokens_details == null ? void 0 : prompt_tokens_details.cached_tokens; + } + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAIFinishReason2(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + if (delta.content != null) { + controller.enqueue({ + type: "text-delta", + textDelta: delta.content + }); + } + const mappedLogprobs = mapOpenAIChatLogProbsOutput2( + choice == null ? void 0 : choice.logprobs + ); + if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) { + if (logprobs === void 0) logprobs = []; + logprobs.push(...mappedLogprobs); + } + const mappedToolCalls = useLegacyFunctionCalling && delta.function_call != null ? [ + { + type: "function", + id: generateId(), + function: delta.function_call, + index: 0 + } + ] : delta.tool_calls; + if (mappedToolCalls != null) { + for (const toolCallDelta of mappedToolCalls) { + const index = toolCallDelta.index; + if (toolCalls[index] == null) { + if (toolCallDelta.type !== "function") { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function' type.` + }); + } + if (toolCallDelta.id == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'id' to be a string.` + }); + } + if (((_a16 = toolCallDelta.function) == null ? void 0 : _a16.name) == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function.name' to be a string.` + }); + } + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: (_b = toolCallDelta.function.arguments) != null ? _b : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if (((_c = toolCall2.function) == null ? void 0 : _c.name) != null && ((_d = toolCall2.function) == null ? void 0 : _d.arguments) != null) { + if (toolCall2.function.arguments.length > 0) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall2.id, + toolName: toolCall2.function.name, + argsTextDelta: toolCall2.function.arguments + }); + } + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_e = toolCall2.id) != null ? _e : generateId(), + toolName: toolCall2.function.name, + args: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (toolCall.hasFinished) { + continue; + } + if (((_f = toolCallDelta.function) == null ? void 0 : _f.arguments) != null) { + toolCall.function.arguments += (_h = (_g = toolCallDelta.function) == null ? void 0 : _g.arguments) != null ? _h : ""; + } + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + argsTextDelta: (_i = toolCallDelta.function.arguments) != null ? _i : "" + }); + if (((_j = toolCall.function) == null ? void 0 : _j.name) != null && ((_k = toolCall.function) == null ? void 0 : _k.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_l = toolCall.id) != null ? _l : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + }, + flush(controller) { + var _a16, _b; + controller.enqueue(__spreadValues({ + type: "finish", + finishReason, + logprobs, + usage: { + promptTokens: (_a16 = usage.promptTokens) != null ? _a16 : NaN, + completionTokens: (_b = usage.completionTokens) != null ? _b : NaN + } + }, providerMetadata != null ? { providerMetadata } : {})); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +var openaiTokenUsageSchema2 = import_zod23.z.object({ + prompt_tokens: import_zod23.z.number().nullish(), + completion_tokens: import_zod23.z.number().nullish(), + prompt_tokens_details: import_zod23.z.object({ + cached_tokens: import_zod23.z.number().nullish() + }).nullish(), + completion_tokens_details: import_zod23.z.object({ + reasoning_tokens: import_zod23.z.number().nullish(), + accepted_prediction_tokens: import_zod23.z.number().nullish(), + rejected_prediction_tokens: import_zod23.z.number().nullish() + }).nullish() +}).nullish(); +var openaiChatResponseSchema2 = import_zod23.z.object({ + id: import_zod23.z.string().nullish(), + created: import_zod23.z.number().nullish(), + model: import_zod23.z.string().nullish(), + choices: import_zod23.z.array( + import_zod23.z.object({ + message: import_zod23.z.object({ + role: import_zod23.z.literal("assistant").nullish(), + content: import_zod23.z.string().nullish(), + function_call: import_zod23.z.object({ + arguments: import_zod23.z.string(), + name: import_zod23.z.string() + }).nullish(), + tool_calls: import_zod23.z.array( + import_zod23.z.object({ + id: import_zod23.z.string().nullish(), + type: import_zod23.z.literal("function"), + function: import_zod23.z.object({ + name: import_zod23.z.string(), + arguments: import_zod23.z.string() + }) + }) + ).nullish() + }), + index: import_zod23.z.number(), + logprobs: import_zod23.z.object({ + content: import_zod23.z.array( + import_zod23.z.object({ + token: import_zod23.z.string(), + logprob: import_zod23.z.number(), + top_logprobs: import_zod23.z.array( + import_zod23.z.object({ + token: import_zod23.z.string(), + logprob: import_zod23.z.number() + }) + ) + }) + ).nullable() + }).nullish(), + finish_reason: import_zod23.z.string().nullish() + }) + ), + usage: openaiTokenUsageSchema2 +}); +var openaiChatChunkSchema2 = import_zod23.z.union([ + import_zod23.z.object({ + id: import_zod23.z.string().nullish(), + created: import_zod23.z.number().nullish(), + model: import_zod23.z.string().nullish(), + choices: import_zod23.z.array( + import_zod23.z.object({ + delta: import_zod23.z.object({ + role: import_zod23.z.enum(["assistant"]).nullish(), + content: import_zod23.z.string().nullish(), + function_call: import_zod23.z.object({ + name: import_zod23.z.string().optional(), + arguments: import_zod23.z.string().optional() + }).nullish(), + tool_calls: import_zod23.z.array( + import_zod23.z.object({ + index: import_zod23.z.number(), + id: import_zod23.z.string().nullish(), + type: import_zod23.z.literal("function").nullish(), + function: import_zod23.z.object({ + name: import_zod23.z.string().nullish(), + arguments: import_zod23.z.string().nullish() + }) + }) + ).nullish() + }).nullish(), + logprobs: import_zod23.z.object({ + content: import_zod23.z.array( + import_zod23.z.object({ + token: import_zod23.z.string(), + logprob: import_zod23.z.number(), + top_logprobs: import_zod23.z.array( + import_zod23.z.object({ + token: import_zod23.z.string(), + logprob: import_zod23.z.number() + }) + ) + }) + ).nullable() + }).nullish(), + finish_reason: import_zod23.z.string().nullish(), + index: import_zod23.z.number() + }) + ), + usage: openaiTokenUsageSchema2 + }), + openaiErrorDataSchema2 +]); +function isReasoningModel2(modelId) { + return modelId.startsWith("o"); +} +function isAudioModel2(modelId) { + return modelId.startsWith("gpt-4o-audio-preview"); +} +function getSystemMessageMode2(modelId) { + var _a15, _b; + if (!isReasoningModel2(modelId)) { + return "system"; + } + return (_b = (_a15 = reasoningModels2[modelId]) == null ? void 0 : _a15.systemMessageMode) != null ? _b : "developer"; +} +var reasoningModels2 = { + "o1-mini": { + systemMessageMode: "remove" + }, + "o1-mini-2024-09-12": { + systemMessageMode: "remove" + }, + "o1-preview": { + systemMessageMode: "remove" + }, + "o1-preview-2024-09-12": { + systemMessageMode: "remove" + }, + o3: { + systemMessageMode: "developer" + }, + "o3-2025-04-16": { + systemMessageMode: "developer" + }, + "o3-mini": { + systemMessageMode: "developer" + }, + "o3-mini-2025-01-31": { + systemMessageMode: "developer" + }, + "o4-mini": { + systemMessageMode: "developer" + }, + "o4-mini-2025-04-16": { + systemMessageMode: "developer" + } +}; +function convertToOpenAICompletionPrompt2({ + prompt, + inputFormat, + user = "user", + assistant = "assistant" +}) { + if (inputFormat === "prompt" && prompt.length === 1 && prompt[0].role === "user" && prompt[0].content.length === 1 && prompt[0].content[0].type === "text") { + return { prompt: prompt[0].content[0].text }; + } + let text = ""; + if (prompt[0].role === "system") { + text += `${prompt[0].content} + +`; + prompt = prompt.slice(1); + } + for (const { role, content } of prompt) { + switch (role) { + case "system": { + throw new InvalidPromptError({ + message: "Unexpected system message in prompt: ${content}", + prompt + }); + } + case "user": { + const userMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "image": { + throw new UnsupportedFunctionalityError({ + functionality: "images" + }); + } + } + }).join(""); + text += `${user}: +${userMessage} + +`; + break; + } + case "assistant": { + const assistantMessage = content.map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "tool-call": { + throw new UnsupportedFunctionalityError({ + functionality: "tool-call messages" + }); + } + } + }).join(""); + text += `${assistant}: +${assistantMessage} + +`; + break; + } + case "tool": { + throw new UnsupportedFunctionalityError({ + functionality: "tool messages" + }); + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + text += `${assistant}: +`; + return { + prompt: text, + stopSequences: [` +${user}:`] + }; +} +function mapOpenAICompletionLogProbs2(logprobs) { + return logprobs == null ? void 0 : logprobs.tokens.map((token, index) => ({ + token, + logprob: logprobs.token_logprobs[index], + topLogprobs: logprobs.top_logprobs ? Object.entries(logprobs.top_logprobs[index]).map( + ([token2, logprob]) => ({ + token: token2, + logprob + }) + ) : [] + })); +} +var OpenAICompletionLanguageModel2 = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = void 0; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + getArgs({ + mode, + inputFormat, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences: userStopSequences, + responseFormat, + seed + }) { + var _a15; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (responseFormat != null && responseFormat.type !== "text") { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format is not supported." + }); + } + const { prompt: completionPrompt, stopSequences } = convertToOpenAICompletionPrompt2({ prompt, inputFormat }); + const stop = [...stopSequences != null ? stopSequences : [], ...userStopSequences != null ? userStopSequences : []]; + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + echo: this.settings.echo, + logit_bias: this.settings.logitBias, + logprobs: typeof this.settings.logprobs === "number" ? this.settings.logprobs : typeof this.settings.logprobs === "boolean" ? this.settings.logprobs ? 0 : void 0 : void 0, + suffix: this.settings.suffix, + user: this.settings.user, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + seed, + // prompt: + prompt: completionPrompt, + // stop sequences: + stop: stop.length > 0 ? stop : void 0 + }; + switch (type) { + case "regular": { + if ((_a15 = mode.tools) == null ? void 0 : _a15.length) { + throw new UnsupportedFunctionalityError({ + functionality: "tools" + }); + } + if (mode.toolChoice) { + throw new UnsupportedFunctionalityError({ + functionality: "toolChoice" + }); + } + return { args: baseArgs, warnings }; + } + case "object-json": { + throw new UnsupportedFunctionalityError({ + functionality: "object-json mode" + }); + } + case "object-tool": { + throw new UnsupportedFunctionalityError({ + functionality: "object-tool mode" + }); + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + openaiCompletionResponseSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { prompt: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["prompt"]); + const choice = response.choices[0]; + return { + text: choice.text, + usage: { + promptTokens: response.usage.prompt_tokens, + completionTokens: response.usage.completion_tokens + }, + finishReason: mapOpenAIFinishReason2(choice.finish_reason), + logprobs: mapOpenAICompletionLogProbs2(choice.logprobs), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + response: getResponseMetadata3(response), + warnings, + request: { body: JSON.stringify(args) } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: true, + // only include stream_options when in strict compatibility mode: + stream_options: this.config.compatibility === "strict" ? { include_usage: true } : void 0 + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createEventSourceResponseHandler( + openaiCompletionChunkSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { prompt: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["prompt"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + let logprobs; + let isFirstChunk = true; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata3(value))); + } + if (value.usage != null) { + usage = { + promptTokens: value.usage.prompt_tokens, + completionTokens: value.usage.completion_tokens + }; + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapOpenAIFinishReason2(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.text) != null) { + controller.enqueue({ + type: "text-delta", + textDelta: choice.text + }); + } + const mappedLogprobs = mapOpenAICompletionLogProbs2( + choice == null ? void 0 : choice.logprobs + ); + if (mappedLogprobs == null ? void 0 : mappedLogprobs.length) { + if (logprobs === void 0) logprobs = []; + logprobs.push(...mappedLogprobs); + } + }, + flush(controller) { + controller.enqueue({ + type: "finish", + finishReason, + logprobs, + usage + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body: JSON.stringify(body) } + }; + }); + } +}; +var openaiCompletionResponseSchema2 = import_zod25.z.object({ + id: import_zod25.z.string().nullish(), + created: import_zod25.z.number().nullish(), + model: import_zod25.z.string().nullish(), + choices: import_zod25.z.array( + import_zod25.z.object({ + text: import_zod25.z.string(), + finish_reason: import_zod25.z.string(), + logprobs: import_zod25.z.object({ + tokens: import_zod25.z.array(import_zod25.z.string()), + token_logprobs: import_zod25.z.array(import_zod25.z.number()), + top_logprobs: import_zod25.z.array(import_zod25.z.record(import_zod25.z.string(), import_zod25.z.number())).nullable() + }).nullish() + }) + ), + usage: import_zod25.z.object({ + prompt_tokens: import_zod25.z.number(), + completion_tokens: import_zod25.z.number() + }) +}); +var openaiCompletionChunkSchema2 = import_zod25.z.union([ + import_zod25.z.object({ + id: import_zod25.z.string().nullish(), + created: import_zod25.z.number().nullish(), + model: import_zod25.z.string().nullish(), + choices: import_zod25.z.array( + import_zod25.z.object({ + text: import_zod25.z.string(), + finish_reason: import_zod25.z.string().nullish(), + index: import_zod25.z.number(), + logprobs: import_zod25.z.object({ + tokens: import_zod25.z.array(import_zod25.z.string()), + token_logprobs: import_zod25.z.array(import_zod25.z.number()), + top_logprobs: import_zod25.z.array(import_zod25.z.record(import_zod25.z.string(), import_zod25.z.number())).nullable() + }).nullish() + }) + ), + usage: import_zod25.z.object({ + prompt_tokens: import_zod25.z.number(), + completion_tokens: import_zod25.z.number() + }).nullish() + }), + openaiErrorDataSchema2 +]); +var OpenAIEmbeddingModel2 = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + var _a15; + return (_a15 = this.settings.maxEmbeddingsPerCall) != null ? _a15 : 2048; + } + get supportsParallelCalls() { + var _a15; + return (_a15 = this.settings.supportsParallelCalls) != null ? _a15 : true; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + values, + headers, + abortSignal + }) { + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + } + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/embeddings", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + input: values, + encoding_format: "float", + dimensions: this.settings.dimensions, + user: this.settings.user + }, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + openaiTextEmbeddingResponseSchema3 + ), + abortSignal, + fetch: this.config.fetch + }); + return { + embeddings: response.data.map((item) => item.embedding), + usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, + rawResponse: { headers: responseHeaders } + }; + }); + } +}; +var openaiTextEmbeddingResponseSchema3 = import_zod26.z.object({ + data: import_zod26.z.array(import_zod26.z.object({ embedding: import_zod26.z.array(import_zod26.z.number()) })), + usage: import_zod26.z.object({ prompt_tokens: import_zod26.z.number() }).nullish() +}); +var modelMaxImagesPerCall2 = { + "dall-e-3": 1, + "dall-e-2": 10, + "gpt-image-1": 10 +}; +var hasDefaultResponseFormat2 = /* @__PURE__ */ new Set(["gpt-image-1"]); +var OpenAIImageModel2 = class { + constructor(modelId, settings, config) { + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v1"; + } + get maxImagesPerCall() { + var _a15, _b; + return (_b = (_a15 = this.settings.maxImagesPerCall) != null ? _a15 : modelMaxImagesPerCall2[this.modelId]) != null ? _b : 1; + } + get provider() { + return this.config.provider; + } + doGenerate(_0) { + return __async(this, arguments, function* ({ + prompt, + n, + size, + aspectRatio, + seed, + providerOptions, + headers, + abortSignal + }) { + var _a15, _b, _c, _d; + const warnings = []; + if (aspectRatio != null) { + warnings.push({ + type: "unsupported-setting", + setting: "aspectRatio", + details: "This model does not support aspect ratio. Use `size` instead." + }); + } + if (seed != null) { + warnings.push({ type: "unsupported-setting", setting: "seed" }); + } + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { value: response, responseHeaders } = yield postJsonToApi({ + url: this.config.url({ + path: "/images/generations", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), headers), + body: __spreadValues(__spreadValues({ + model: this.modelId, + prompt, + n, + size + }, (_d = providerOptions.openai) != null ? _d : {}), !hasDefaultResponseFormat2.has(this.modelId) ? { response_format: "b64_json" } : {}), + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + openaiImageResponseSchema2 + ), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.data.map((item) => item.b64_json), + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + } + }; + }); + } +}; +var openaiImageResponseSchema2 = import_zod27.z.object({ + data: import_zod27.z.array(import_zod27.z.object({ b64_json: import_zod27.z.string() })) +}); +var openAIProviderOptionsSchema2 = import_zod28.z.object({ + include: import_zod28.z.array(import_zod28.z.string()).nullish(), + language: import_zod28.z.string().nullish(), + prompt: import_zod28.z.string().nullish(), + temperature: import_zod28.z.number().min(0).max(1).nullish().default(0), + timestampGranularities: import_zod28.z.array(import_zod28.z.enum(["word", "segment"])).nullish().default(["segment"]) +}); +var languageMap2 = { + afrikaans: "af", + arabic: "ar", + armenian: "hy", + azerbaijani: "az", + belarusian: "be", + bosnian: "bs", + bulgarian: "bg", + catalan: "ca", + chinese: "zh", + croatian: "hr", + czech: "cs", + danish: "da", + dutch: "nl", + english: "en", + estonian: "et", + finnish: "fi", + french: "fr", + galician: "gl", + german: "de", + greek: "el", + hebrew: "he", + hindi: "hi", + hungarian: "hu", + icelandic: "is", + indonesian: "id", + italian: "it", + japanese: "ja", + kannada: "kn", + kazakh: "kk", + korean: "ko", + latvian: "lv", + lithuanian: "lt", + macedonian: "mk", + malay: "ms", + marathi: "mr", + maori: "mi", + nepali: "ne", + norwegian: "no", + persian: "fa", + polish: "pl", + portuguese: "pt", + romanian: "ro", + russian: "ru", + serbian: "sr", + slovak: "sk", + slovenian: "sl", + spanish: "es", + swahili: "sw", + swedish: "sv", + tagalog: "tl", + tamil: "ta", + thai: "th", + turkish: "tr", + ukrainian: "uk", + urdu: "ur", + vietnamese: "vi", + welsh: "cy" +}; +var OpenAITranscriptionModel2 = class { + constructor(modelId, config) { + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v1"; + } + get provider() { + return this.config.provider; + } + getArgs({ + audio, + mediaType, + providerOptions + }) { + var _a15, _b, _c, _d, _e; + const warnings = []; + const openAIOptions = parseProviderOptions({ + provider: "openai", + providerOptions, + schema: openAIProviderOptionsSchema2 + }); + const formData = new FormData(); + const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]); + formData.append("model", this.modelId); + formData.append("file", new File([blob], "audio", { type: mediaType })); + if (openAIOptions) { + const transcriptionModelOptions = { + include: (_a15 = openAIOptions.include) != null ? _a15 : void 0, + language: (_b = openAIOptions.language) != null ? _b : void 0, + prompt: (_c = openAIOptions.prompt) != null ? _c : void 0, + temperature: (_d = openAIOptions.temperature) != null ? _d : void 0, + timestamp_granularities: (_e = openAIOptions.timestampGranularities) != null ? _e : void 0 + }; + for (const key in transcriptionModelOptions) { + const value = transcriptionModelOptions[key]; + if (value !== void 0) { + formData.append(key, String(value)); + } + } + } + return { + formData, + warnings + }; + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f; + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { formData, warnings } = this.getArgs(options); + const { + value: response, + responseHeaders, + rawValue: rawResponse + } = yield postFormDataToApi({ + url: this.config.url({ + path: "/audio/transcriptions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + formData, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + openaiTranscriptionResponseSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const language = response.language != null && response.language in languageMap2 ? languageMap2[response.language] : void 0; + return { + text: response.text, + segments: (_e = (_d = response.words) == null ? void 0 : _d.map((word) => ({ + text: word.word, + startSecond: word.start, + endSecond: word.end + }))) != null ? _e : [], + language, + durationInSeconds: (_f = response.duration) != null ? _f : void 0, + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + }); + } +}; +var openaiTranscriptionResponseSchema2 = import_zod28.z.object({ + text: import_zod28.z.string(), + language: import_zod28.z.string().nullish(), + duration: import_zod28.z.number().nullish(), + words: import_zod28.z.array( + import_zod28.z.object({ + word: import_zod28.z.string(), + start: import_zod28.z.number(), + end: import_zod28.z.number() + }) + ).nullish() +}); +var OpenAIProviderOptionsSchema2 = import_zod29.z.object({ + instructions: import_zod29.z.string().nullish(), + speed: import_zod29.z.number().min(0.25).max(4).default(1).nullish() +}); +function convertToOpenAIResponsesMessages2({ + prompt, + systemMessageMode +}) { + const messages = []; + const warnings = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + switch (systemMessageMode) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "developer": { + messages.push({ role: "developer", content }); + break; + } + case "remove": { + warnings.push({ + type: "other", + message: "system messages are removed for this model" + }); + break; + } + default: { + const _exhaustiveCheck = systemMessageMode; + throw new Error( + `Unsupported system message mode: ${_exhaustiveCheck}` + ); + } + } + break; + } + case "user": { + messages.push({ + role: "user", + content: content.map((part, index) => { + var _a15, _b, _c, _d; + switch (part.type) { + case "text": { + return { type: "input_text", text: part.text }; + } + case "image": { + return { + type: "input_image", + image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}`, + // OpenAI specific extension: image detail + detail: (_c = (_b = part.providerMetadata) == null ? void 0 : _b.openai) == null ? void 0 : _c.imageDetail + }; + } + case "file": { + if (part.data instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "File URLs in user messages" + }); + } + switch (part.mimeType) { + case "application/pdf": { + return { + type: "input_file", + filename: (_d = part.filename) != null ? _d : `part-${index}.pdf`, + file_data: `data:application/pdf;base64,${part.data}` + }; + } + default: { + throw new UnsupportedFunctionalityError({ + functionality: "Only PDF files are supported in user messages" + }); + } + } + } + } + }) + }); + break; + } + case "assistant": { + for (const part of content) { + switch (part.type) { + case "text": { + messages.push({ + role: "assistant", + content: [{ type: "output_text", text: part.text }] + }); + break; + } + case "tool-call": { + messages.push({ + type: "function_call", + call_id: part.toolCallId, + name: part.toolName, + arguments: JSON.stringify(part.args) + }); + break; + } + } + } + break; + } + case "tool": { + for (const part of content) { + messages.push({ + type: "function_call_output", + call_id: part.toolCallId, + output: JSON.stringify(part.result) + }); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return { messages, warnings }; +} +function mapOpenAIResponseFinishReason2({ + finishReason, + hasToolCalls +}) { + switch (finishReason) { + case void 0: + case null: + return hasToolCalls ? "tool-calls" : "stop"; + case "max_output_tokens": + return "length"; + case "content_filter": + return "content-filter"; + default: + return hasToolCalls ? "tool-calls" : "unknown"; + } +} +function prepareResponsesTools2({ + mode, + strict +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + const openaiTools2 = []; + for (const tool of tools) { + switch (tool.type) { + case "function": + openaiTools2.push({ + type: "function", + name: tool.name, + description: tool.description, + parameters: tool.parameters, + strict: strict ? true : void 0 + }); + break; + case "provider-defined": + switch (tool.id) { + case "openai.web_search_preview": + openaiTools2.push({ + type: "web_search_preview", + search_context_size: tool.args.searchContextSize, + user_location: tool.args.userLocation + }); + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + break; + default: + toolWarnings.push({ type: "unsupported-tool", tool }); + break; + } + } + if (toolChoice == null) { + return { tools: openaiTools2, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: openaiTools2, tool_choice: type, toolWarnings }; + case "tool": { + if (toolChoice.toolName === "web_search_preview") { + return { + tools: openaiTools2, + tool_choice: { + type: "web_search_preview" + }, + toolWarnings + }; + } + return { + tools: openaiTools2, + tool_choice: { + type: "function", + name: toolChoice.toolName + }, + toolWarnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var OpenAIResponsesLanguageModel2 = class { + constructor(modelId, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsStructuredOutputs = true; + this.modelId = modelId; + this.config = config; + } + get provider() { + return this.config.provider; + } + getArgs({ + mode, + maxTokens, + temperature, + stopSequences, + topP, + topK, + presencePenalty, + frequencyPenalty, + seed, + prompt, + providerMetadata, + responseFormat + }) { + var _a15, _b, _c; + const warnings = []; + const modelConfig = getResponsesModelConfig2(this.modelId); + const type = mode.type; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (seed != null) { + warnings.push({ + type: "unsupported-setting", + setting: "seed" + }); + } + if (presencePenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty" + }); + } + if (frequencyPenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty" + }); + } + if (stopSequences != null) { + warnings.push({ + type: "unsupported-setting", + setting: "stopSequences" + }); + } + const { messages, warnings: messageWarnings } = convertToOpenAIResponsesMessages2({ + prompt, + systemMessageMode: modelConfig.systemMessageMode + }); + warnings.push(...messageWarnings); + const openaiOptions = parseProviderOptions({ + provider: "openai", + providerOptions: providerMetadata, + schema: openaiResponsesProviderOptionsSchema2 + }); + const isStrict = (_a15 = openaiOptions == null ? void 0 : openaiOptions.strictSchemas) != null ? _a15 : true; + const baseArgs = __spreadValues(__spreadValues(__spreadProps(__spreadValues({ + model: this.modelId, + input: messages, + temperature, + top_p: topP, + max_output_tokens: maxTokens + }, (responseFormat == null ? void 0 : responseFormat.type) === "json" && { + text: { + format: responseFormat.schema != null ? { + type: "json_schema", + strict: isStrict, + name: (_b = responseFormat.name) != null ? _b : "response", + description: responseFormat.description, + schema: responseFormat.schema + } : { type: "json_object" } + } + }), { + // provider options: + metadata: openaiOptions == null ? void 0 : openaiOptions.metadata, + parallel_tool_calls: openaiOptions == null ? void 0 : openaiOptions.parallelToolCalls, + previous_response_id: openaiOptions == null ? void 0 : openaiOptions.previousResponseId, + store: openaiOptions == null ? void 0 : openaiOptions.store, + user: openaiOptions == null ? void 0 : openaiOptions.user, + instructions: openaiOptions == null ? void 0 : openaiOptions.instructions + }), modelConfig.isReasoningModel && ((openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null || (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null) && { + reasoning: __spreadValues(__spreadValues({}, (openaiOptions == null ? void 0 : openaiOptions.reasoningEffort) != null && { + effort: openaiOptions.reasoningEffort + }), (openaiOptions == null ? void 0 : openaiOptions.reasoningSummary) != null && { + summary: openaiOptions.reasoningSummary + }) + }), modelConfig.requiredAutoTruncation && { + truncation: "auto" + }); + if (modelConfig.isReasoningModel) { + if (baseArgs.temperature != null) { + baseArgs.temperature = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "temperature", + details: "temperature is not supported for reasoning models" + }); + } + if (baseArgs.top_p != null) { + baseArgs.top_p = void 0; + warnings.push({ + type: "unsupported-setting", + setting: "topP", + details: "topP is not supported for reasoning models" + }); + } + } + switch (type) { + case "regular": { + const { tools, tool_choice, toolWarnings } = prepareResponsesTools2({ + mode, + strict: isStrict + // TODO support provider options on tools + }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools, + tool_choice + }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + text: { + format: mode.schema != null ? { + type: "json_schema", + strict: isStrict, + name: (_c = mode.name) != null ? _c : "response", + description: mode.description, + schema: mode.schema + } : { type: "json_object" } + } + }), + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { type: "function", name: mode.tool.name }, + tools: [ + { + type: "function", + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters, + strict: isStrict + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g; + const { args: body, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/responses", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createJsonResponseHandler( + import_zod30.z.object({ + id: import_zod30.z.string(), + created_at: import_zod30.z.number(), + model: import_zod30.z.string(), + output: import_zod30.z.array( + import_zod30.z.discriminatedUnion("type", [ + import_zod30.z.object({ + type: import_zod30.z.literal("message"), + role: import_zod30.z.literal("assistant"), + content: import_zod30.z.array( + import_zod30.z.object({ + type: import_zod30.z.literal("output_text"), + text: import_zod30.z.string(), + annotations: import_zod30.z.array( + import_zod30.z.object({ + type: import_zod30.z.literal("url_citation"), + start_index: import_zod30.z.number(), + end_index: import_zod30.z.number(), + url: import_zod30.z.string(), + title: import_zod30.z.string() + }) + ) + }) + ) + }), + import_zod30.z.object({ + type: import_zod30.z.literal("function_call"), + call_id: import_zod30.z.string(), + name: import_zod30.z.string(), + arguments: import_zod30.z.string() + }), + import_zod30.z.object({ + type: import_zod30.z.literal("web_search_call") + }), + import_zod30.z.object({ + type: import_zod30.z.literal("computer_call") + }), + import_zod30.z.object({ + type: import_zod30.z.literal("reasoning"), + summary: import_zod30.z.array( + import_zod30.z.object({ + type: import_zod30.z.literal("summary_text"), + text: import_zod30.z.string() + }) + ) + }) + ]) + ), + incomplete_details: import_zod30.z.object({ reason: import_zod30.z.string() }).nullable(), + usage: usageSchema2 + }) + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const outputTextElements = response.output.filter((output) => output.type === "message").flatMap((output) => output.content).filter((content) => content.type === "output_text"); + const toolCalls = response.output.filter((output) => output.type === "function_call").map((output) => ({ + toolCallType: "function", + toolCallId: output.call_id, + toolName: output.name, + args: output.arguments + })); + const reasoningSummary = (_b = (_a15 = response.output.find((item) => item.type === "reasoning")) == null ? void 0 : _a15.summary) != null ? _b : null; + return { + text: outputTextElements.map((content) => content.text).join("\n"), + sources: outputTextElements.flatMap( + (content) => content.annotations.map((annotation) => { + var _a22, _b2, _c2; + return { + sourceType: "url", + id: (_c2 = (_b2 = (_a22 = this.config).generateId) == null ? void 0 : _b2.call(_a22)) != null ? _c2 : generateId(), + url: annotation.url, + title: annotation.title + }; + }) + ), + finishReason: mapOpenAIResponseFinishReason2({ + finishReason: (_c = response.incomplete_details) == null ? void 0 : _c.reason, + hasToolCalls: toolCalls.length > 0 + }), + toolCalls: toolCalls.length > 0 ? toolCalls : void 0, + reasoning: reasoningSummary ? reasoningSummary.map((summary) => ({ + type: "text", + text: summary.text + })) : void 0, + usage: { + promptTokens: response.usage.input_tokens, + completionTokens: response.usage.output_tokens + }, + rawCall: { + rawPrompt: void 0, + rawSettings: {} + }, + rawResponse: { + headers: responseHeaders, + body: rawResponse + }, + request: { + body: JSON.stringify(body) + }, + response: { + id: response.id, + timestamp: new Date(response.created_at * 1e3), + modelId: response.model + }, + providerMetadata: { + openai: { + responseId: response.id, + cachedPromptTokens: (_e = (_d = response.usage.input_tokens_details) == null ? void 0 : _d.cached_tokens) != null ? _e : null, + reasoningTokens: (_g = (_f = response.usage.output_tokens_details) == null ? void 0 : _f.reasoning_tokens) != null ? _g : null + } + }, + warnings + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args: body, warnings } = this.getArgs(options); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/responses", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: __spreadProps(__spreadValues({}, body), { + stream: true + }), + failedResponseHandler: openaiFailedResponseHandler2, + successfulResponseHandler: createEventSourceResponseHandler( + openaiResponsesChunkSchema2 + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const self = this; + let finishReason = "unknown"; + let promptTokens = NaN; + let completionTokens = NaN; + let cachedPromptTokens = null; + let reasoningTokens = null; + let responseId = null; + const ongoingToolCalls = {}; + let hasToolCalls = false; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a15, _b, _c, _d, _e, _f, _g, _h; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if (isResponseOutputItemAddedChunk2(value)) { + if (value.item.type === "function_call") { + ongoingToolCalls[value.output_index] = { + toolName: value.item.name, + toolCallId: value.item.call_id + }; + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: value.item.call_id, + toolName: value.item.name, + argsTextDelta: value.item.arguments + }); + } + } else if (isResponseFunctionCallArgumentsDeltaChunk2(value)) { + const toolCall = ongoingToolCalls[value.output_index]; + if (toolCall != null) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.toolCallId, + toolName: toolCall.toolName, + argsTextDelta: value.delta + }); + } + } else if (isResponseCreatedChunk2(value)) { + responseId = value.response.id; + controller.enqueue({ + type: "response-metadata", + id: value.response.id, + timestamp: new Date(value.response.created_at * 1e3), + modelId: value.response.model + }); + } else if (isTextDeltaChunk2(value)) { + controller.enqueue({ + type: "text-delta", + textDelta: value.delta + }); + } else if (isResponseReasoningSummaryTextDeltaChunk2(value)) { + controller.enqueue({ + type: "reasoning", + textDelta: value.delta + }); + } else if (isResponseOutputItemDoneChunk2(value) && value.item.type === "function_call") { + ongoingToolCalls[value.output_index] = void 0; + hasToolCalls = true; + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: value.item.call_id, + toolName: value.item.name, + args: value.item.arguments + }); + } else if (isResponseFinishedChunk2(value)) { + finishReason = mapOpenAIResponseFinishReason2({ + finishReason: (_a15 = value.response.incomplete_details) == null ? void 0 : _a15.reason, + hasToolCalls + }); + promptTokens = value.response.usage.input_tokens; + completionTokens = value.response.usage.output_tokens; + cachedPromptTokens = (_c = (_b = value.response.usage.input_tokens_details) == null ? void 0 : _b.cached_tokens) != null ? _c : cachedPromptTokens; + reasoningTokens = (_e = (_d = value.response.usage.output_tokens_details) == null ? void 0 : _d.reasoning_tokens) != null ? _e : reasoningTokens; + } else if (isResponseAnnotationAddedChunk2(value)) { + controller.enqueue({ + type: "source", + source: { + sourceType: "url", + id: (_h = (_g = (_f = self.config).generateId) == null ? void 0 : _g.call(_f)) != null ? _h : generateId(), + url: value.annotation.url, + title: value.annotation.title + } + }); + } + }, + flush(controller) { + controller.enqueue(__spreadValues({ + type: "finish", + finishReason, + usage: { promptTokens, completionTokens } + }, (cachedPromptTokens != null || reasoningTokens != null) && { + providerMetadata: { + openai: { + responseId, + cachedPromptTokens, + reasoningTokens + } + } + })); + } + }) + ), + rawCall: { + rawPrompt: void 0, + rawSettings: {} + }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +var usageSchema2 = import_zod30.z.object({ + input_tokens: import_zod30.z.number(), + input_tokens_details: import_zod30.z.object({ cached_tokens: import_zod30.z.number().nullish() }).nullish(), + output_tokens: import_zod30.z.number(), + output_tokens_details: import_zod30.z.object({ reasoning_tokens: import_zod30.z.number().nullish() }).nullish() +}); +var textDeltaChunkSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.output_text.delta"), + delta: import_zod30.z.string() +}); +var responseFinishedChunkSchema2 = import_zod30.z.object({ + type: import_zod30.z.enum(["response.completed", "response.incomplete"]), + response: import_zod30.z.object({ + incomplete_details: import_zod30.z.object({ reason: import_zod30.z.string() }).nullish(), + usage: usageSchema2 + }) +}); +var responseCreatedChunkSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.created"), + response: import_zod30.z.object({ + id: import_zod30.z.string(), + created_at: import_zod30.z.number(), + model: import_zod30.z.string() + }) +}); +var responseOutputItemDoneSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.output_item.done"), + output_index: import_zod30.z.number(), + item: import_zod30.z.discriminatedUnion("type", [ + import_zod30.z.object({ + type: import_zod30.z.literal("message") + }), + import_zod30.z.object({ + type: import_zod30.z.literal("function_call"), + id: import_zod30.z.string(), + call_id: import_zod30.z.string(), + name: import_zod30.z.string(), + arguments: import_zod30.z.string(), + status: import_zod30.z.literal("completed") + }) + ]) +}); +var responseFunctionCallArgumentsDeltaSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.function_call_arguments.delta"), + item_id: import_zod30.z.string(), + output_index: import_zod30.z.number(), + delta: import_zod30.z.string() +}); +var responseOutputItemAddedSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.output_item.added"), + output_index: import_zod30.z.number(), + item: import_zod30.z.discriminatedUnion("type", [ + import_zod30.z.object({ + type: import_zod30.z.literal("message") + }), + import_zod30.z.object({ + type: import_zod30.z.literal("function_call"), + id: import_zod30.z.string(), + call_id: import_zod30.z.string(), + name: import_zod30.z.string(), + arguments: import_zod30.z.string() + }) + ]) +}); +var responseAnnotationAddedSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.output_text.annotation.added"), + annotation: import_zod30.z.object({ + type: import_zod30.z.literal("url_citation"), + url: import_zod30.z.string(), + title: import_zod30.z.string() + }) +}); +var responseReasoningSummaryTextDeltaSchema2 = import_zod30.z.object({ + type: import_zod30.z.literal("response.reasoning_summary_text.delta"), + item_id: import_zod30.z.string(), + output_index: import_zod30.z.number(), + summary_index: import_zod30.z.number(), + delta: import_zod30.z.string() +}); +var openaiResponsesChunkSchema2 = import_zod30.z.union([ + textDeltaChunkSchema2, + responseFinishedChunkSchema2, + responseCreatedChunkSchema2, + responseOutputItemDoneSchema2, + responseFunctionCallArgumentsDeltaSchema2, + responseOutputItemAddedSchema2, + responseAnnotationAddedSchema2, + responseReasoningSummaryTextDeltaSchema2, + import_zod30.z.object({ type: import_zod30.z.string() }).passthrough() + // fallback for unknown chunks +]); +function isTextDeltaChunk2(chunk) { + return chunk.type === "response.output_text.delta"; +} +function isResponseOutputItemDoneChunk2(chunk) { + return chunk.type === "response.output_item.done"; +} +function isResponseFinishedChunk2(chunk) { + return chunk.type === "response.completed" || chunk.type === "response.incomplete"; +} +function isResponseCreatedChunk2(chunk) { + return chunk.type === "response.created"; +} +function isResponseFunctionCallArgumentsDeltaChunk2(chunk) { + return chunk.type === "response.function_call_arguments.delta"; +} +function isResponseOutputItemAddedChunk2(chunk) { + return chunk.type === "response.output_item.added"; +} +function isResponseAnnotationAddedChunk2(chunk) { + return chunk.type === "response.output_text.annotation.added"; +} +function isResponseReasoningSummaryTextDeltaChunk2(chunk) { + return chunk.type === "response.reasoning_summary_text.delta"; +} +function getResponsesModelConfig2(modelId) { + if (modelId.startsWith("o")) { + if (modelId.startsWith("o1-mini") || modelId.startsWith("o1-preview")) { + return { + isReasoningModel: true, + systemMessageMode: "remove", + requiredAutoTruncation: false + }; + } + return { + isReasoningModel: true, + systemMessageMode: "developer", + requiredAutoTruncation: false + }; + } + return { + isReasoningModel: false, + systemMessageMode: "system", + requiredAutoTruncation: false + }; +} +var openaiResponsesProviderOptionsSchema2 = import_zod30.z.object({ + metadata: import_zod30.z.any().nullish(), + parallelToolCalls: import_zod30.z.boolean().nullish(), + previousResponseId: import_zod30.z.string().nullish(), + store: import_zod30.z.boolean().nullish(), + user: import_zod30.z.string().nullish(), + reasoningEffort: import_zod30.z.string().nullish(), + strictSchemas: import_zod30.z.boolean().nullish(), + instructions: import_zod30.z.string().nullish(), + reasoningSummary: import_zod30.z.string().nullish() +}); + +// node_modules/.pnpm/@ai-sdk+azure@1.3.22_zod@3.25.67/node_modules/@ai-sdk/azure/dist/index.mjs +function createAzure(options = {}) { + var _a15; + const getHeaders = () => __spreadValues({ + "api-key": loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "AZURE_API_KEY", + description: "Azure OpenAI" + }) + }, options.headers); + const getResourceName = () => loadSetting({ + settingValue: options.resourceName, + settingName: "resourceName", + environmentVariableName: "AZURE_RESOURCE_NAME", + description: "Azure OpenAI resource name" + }); + const apiVersion = (_a15 = options.apiVersion) != null ? _a15 : "2025-03-01-preview"; + const url = ({ path: path4, modelId }) => { + if (path4 === "/responses") { + return options.baseURL ? `${options.baseURL}${path4}?api-version=${apiVersion}` : `https://${getResourceName()}.openai.azure.com/openai/responses?api-version=${apiVersion}`; + } + return options.baseURL ? `${options.baseURL}/${modelId}${path4}?api-version=${apiVersion}` : `https://${getResourceName()}.openai.azure.com/openai/deployments/${modelId}${path4}?api-version=${apiVersion}`; + }; + const createChatModel = (deploymentName, settings = {}) => new OpenAIChatLanguageModel2(deploymentName, settings, { + provider: "azure-openai.chat", + url, + headers: getHeaders, + compatibility: "strict", + fetch: options.fetch + }); + const createCompletionModel = (modelId, settings = {}) => new OpenAICompletionLanguageModel2(modelId, settings, { + provider: "azure-openai.completion", + url, + compatibility: "strict", + headers: getHeaders, + fetch: options.fetch + }); + const createEmbeddingModel = (modelId, settings = {}) => new OpenAIEmbeddingModel2(modelId, settings, { + provider: "azure-openai.embeddings", + headers: getHeaders, + url, + fetch: options.fetch + }); + const createResponsesModel = (modelId) => new OpenAIResponsesLanguageModel2(modelId, { + provider: "azure-openai.responses", + url, + headers: getHeaders, + fetch: options.fetch + }); + const createImageModel = (modelId, settings = {}) => new OpenAIImageModel2(modelId, settings, { + provider: "azure-openai.image", + url, + headers: getHeaders, + fetch: options.fetch + }); + const createTranscriptionModel = (modelId) => new OpenAITranscriptionModel2(modelId, { + provider: "azure-openai.transcription", + url, + headers: getHeaders, + fetch: options.fetch + }); + const provider = function(deploymentId, settings) { + if (new.target) { + throw new Error( + "The Azure OpenAI model function cannot be called with the new keyword." + ); + } + return createChatModel(deploymentId, settings); + }; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.completion = createCompletionModel; + provider.embedding = createEmbeddingModel; + provider.image = createImageModel; + provider.imageModel = createImageModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + provider.responses = createResponsesModel; + provider.transcription = createTranscriptionModel; + return provider; +} +var azure = createAzure(); + +// node_modules/.pnpm/@ai-sdk+groq@1.2.8_zod@3.25.67/node_modules/@ai-sdk/groq/dist/index.mjs +var import_zod31 = require("zod"); +var import_zod32 = require("zod"); +var import_zod33 = require("zod"); +function convertToGroqChatMessages(prompt) { + const messages = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "user": { + if (content.length === 1 && content[0].type === "text") { + messages.push({ role: "user", content: content[0].text }); + break; + } + messages.push({ + role: "user", + content: content.map((part) => { + var _a15; + switch (part.type) { + case "text": { + return { type: "text", text: part.text }; + } + case "image": { + return { + type: "image_url", + image_url: { + url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}` + } + }; + } + case "file": { + throw new UnsupportedFunctionalityError({ + functionality: "File content parts in user messages" + }); + } + } + }) + }); + break; + } + case "assistant": { + let text = ""; + const toolCalls = []; + for (const part of content) { + switch (part.type) { + case "text": { + text += part.text; + break; + } + case "tool-call": { + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.args) + } + }); + break; + } + } + } + messages.push({ + role: "assistant", + content: text, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + break; + } + case "tool": { + for (const toolResponse of content) { + messages.push({ + role: "tool", + tool_call_id: toolResponse.toolCallId, + content: JSON.stringify(toolResponse.result) + }); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return messages; +} +function getResponseMetadata4({ + id, + model, + created +}) { + return { + id: id != null ? id : void 0, + modelId: model != null ? model : void 0, + timestamp: created != null ? new Date(created * 1e3) : void 0 + }; +} +var groqErrorDataSchema = import_zod32.z.object({ + error: import_zod32.z.object({ + message: import_zod32.z.string(), + type: import_zod32.z.string() + }) +}); +var groqFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: groqErrorDataSchema, + errorToMessage: (data) => data.error.message +}); +function prepareTools6({ + mode +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const toolChoice = mode.toolChoice; + const groqTools = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + groqTools.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters + } + }); + } + } + if (toolChoice == null) { + return { tools: groqTools, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + case "required": + return { tools: groqTools, tool_choice: type, toolWarnings }; + case "tool": + return { + tools: groqTools, + tool_choice: { + type: "function", + function: { + name: toolChoice.toolName + } + }, + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +function mapGroqFinishReason(finishReason) { + switch (finishReason) { + case "stop": + return "stop"; + case "length": + return "length"; + case "content_filter": + return "content-filter"; + case "function_call": + case "tool_calls": + return "tool-calls"; + default: + return "unknown"; + } +} +var GroqChatLanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.supportsStructuredOutputs = false; + this.defaultObjectGenerationMode = "json"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get supportsImageUrls() { + return !this.settings.downloadImages; + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + stream, + providerMetadata + }) { + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format schema is not supported" + }); + } + const groqOptions = parseProviderOptions({ + provider: "groq", + providerOptions: providerMetadata, + schema: import_zod31.z.object({ + reasoningFormat: import_zod31.z.enum(["parsed", "raw", "hidden"]).nullish() + }) + }); + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + user: this.settings.user, + parallel_tool_calls: this.settings.parallelToolCalls, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + frequency_penalty: frequencyPenalty, + presence_penalty: presencePenalty, + stop: stopSequences, + seed, + // response format: + response_format: ( + // json object response format is not supported for streaming: + stream === false && (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0 + ), + // provider options: + reasoning_format: groqOptions == null ? void 0 : groqOptions.reasoningFormat, + // messages: + messages: convertToGroqChatMessages(prompt) + }; + switch (type) { + case "regular": { + const { tools, tool_choice, toolWarnings } = prepareTools6({ mode }); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tools, + tool_choice + }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: ( + // json object response format is not supported for streaming: + stream === false ? { type: "json_object" } : void 0 + ) + }), + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: { + type: "function", + function: { name: mode.tool.name } + }, + tools: [ + { + type: "function", + function: { + name: mode.tool.name, + description: mode.tool.description, + parameters: mode.tool.parameters + } + } + ] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g; + const { args, warnings } = this.getArgs(__spreadProps(__spreadValues({}, options), { stream: false })); + const body = JSON.stringify(args); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: groqFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + groqChatResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = response.choices[0]; + return { + text: (_a15 = choice.message.content) != null ? _a15 : void 0, + reasoning: (_b = choice.message.reasoning) != null ? _b : void 0, + toolCalls: (_c = choice.message.tool_calls) == null ? void 0 : _c.map((toolCall) => { + var _a22; + return { + toolCallType: "function", + toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }; + }), + finishReason: mapGroqFinishReason(choice.finish_reason), + usage: { + promptTokens: (_e = (_d = response.usage) == null ? void 0 : _d.prompt_tokens) != null ? _e : NaN, + completionTokens: (_g = (_f = response.usage) == null ? void 0 : _f.completion_tokens) != null ? _g : NaN + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + response: getResponseMetadata4(response), + warnings, + request: { body } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(__spreadProps(__spreadValues({}, options), { stream: true })); + const body = JSON.stringify(__spreadProps(__spreadValues({}, args), { stream: true })); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: this.config.url({ + path: "/chat/completions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + body: __spreadProps(__spreadValues({}, args), { + stream: true + }), + failedResponseHandler: groqFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler(groqChatChunkSchema), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + const toolCalls = []; + let finishReason = "unknown"; + let usage = { + promptTokens: void 0, + completionTokens: void 0 + }; + let isFirstChunk = true; + let providerMetadata; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o; + if (!chunk.success) { + finishReason = "error"; + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if ("error" in value) { + finishReason = "error"; + controller.enqueue({ type: "error", error: value.error }); + return; + } + if (isFirstChunk) { + isFirstChunk = false; + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata4(value))); + } + if (((_a16 = value.x_groq) == null ? void 0 : _a16.usage) != null) { + usage = { + promptTokens: (_b = value.x_groq.usage.prompt_tokens) != null ? _b : void 0, + completionTokens: (_c = value.x_groq.usage.completion_tokens) != null ? _c : void 0 + }; + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapGroqFinishReason(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + if (delta.reasoning != null && delta.reasoning.length > 0) { + controller.enqueue({ + type: "reasoning", + textDelta: delta.reasoning + }); + } + if (delta.content != null && delta.content.length > 0) { + controller.enqueue({ + type: "text-delta", + textDelta: delta.content + }); + } + if (delta.tool_calls != null) { + for (const toolCallDelta of delta.tool_calls) { + const index = toolCallDelta.index; + if (toolCalls[index] == null) { + if (toolCallDelta.type !== "function") { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function' type.` + }); + } + if (toolCallDelta.id == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'id' to be a string.` + }); + } + if (((_d = toolCallDelta.function) == null ? void 0 : _d.name) == null) { + throw new InvalidResponseDataError({ + data: toolCallDelta, + message: `Expected 'function.name' to be a string.` + }); + } + toolCalls[index] = { + id: toolCallDelta.id, + type: "function", + function: { + name: toolCallDelta.function.name, + arguments: (_e = toolCallDelta.function.arguments) != null ? _e : "" + }, + hasFinished: false + }; + const toolCall2 = toolCalls[index]; + if (((_f = toolCall2.function) == null ? void 0 : _f.name) != null && ((_g = toolCall2.function) == null ? void 0 : _g.arguments) != null) { + if (toolCall2.function.arguments.length > 0) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall2.id, + toolName: toolCall2.function.name, + argsTextDelta: toolCall2.function.arguments + }); + } + if (isParsableJson(toolCall2.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_h = toolCall2.id) != null ? _h : generateId(), + toolName: toolCall2.function.name, + args: toolCall2.function.arguments + }); + toolCall2.hasFinished = true; + } + } + continue; + } + const toolCall = toolCalls[index]; + if (toolCall.hasFinished) { + continue; + } + if (((_i = toolCallDelta.function) == null ? void 0 : _i.arguments) != null) { + toolCall.function.arguments += (_k = (_j = toolCallDelta.function) == null ? void 0 : _j.arguments) != null ? _k : ""; + } + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + argsTextDelta: (_l = toolCallDelta.function.arguments) != null ? _l : "" + }); + if (((_m = toolCall.function) == null ? void 0 : _m.name) != null && ((_n = toolCall.function) == null ? void 0 : _n.arguments) != null && isParsableJson(toolCall.function.arguments)) { + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: (_o = toolCall.id) != null ? _o : generateId(), + toolName: toolCall.function.name, + args: toolCall.function.arguments + }); + toolCall.hasFinished = true; + } + } + } + }, + flush(controller) { + var _a16, _b; + controller.enqueue(__spreadValues({ + type: "finish", + finishReason, + usage: { + promptTokens: (_a16 = usage.promptTokens) != null ? _a16 : NaN, + completionTokens: (_b = usage.completionTokens) != null ? _b : NaN + } + }, providerMetadata != null ? { providerMetadata } : {})); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + warnings, + request: { body } + }; + }); + } +}; +var groqChatResponseSchema = import_zod31.z.object({ + id: import_zod31.z.string().nullish(), + created: import_zod31.z.number().nullish(), + model: import_zod31.z.string().nullish(), + choices: import_zod31.z.array( + import_zod31.z.object({ + message: import_zod31.z.object({ + content: import_zod31.z.string().nullish(), + reasoning: import_zod31.z.string().nullish(), + tool_calls: import_zod31.z.array( + import_zod31.z.object({ + id: import_zod31.z.string().nullish(), + type: import_zod31.z.literal("function"), + function: import_zod31.z.object({ + name: import_zod31.z.string(), + arguments: import_zod31.z.string() + }) + }) + ).nullish() + }), + index: import_zod31.z.number(), + finish_reason: import_zod31.z.string().nullish() + }) + ), + usage: import_zod31.z.object({ + prompt_tokens: import_zod31.z.number().nullish(), + completion_tokens: import_zod31.z.number().nullish() + }).nullish() +}); +var groqChatChunkSchema = import_zod31.z.union([ + import_zod31.z.object({ + id: import_zod31.z.string().nullish(), + created: import_zod31.z.number().nullish(), + model: import_zod31.z.string().nullish(), + choices: import_zod31.z.array( + import_zod31.z.object({ + delta: import_zod31.z.object({ + content: import_zod31.z.string().nullish(), + reasoning: import_zod31.z.string().nullish(), + tool_calls: import_zod31.z.array( + import_zod31.z.object({ + index: import_zod31.z.number(), + id: import_zod31.z.string().nullish(), + type: import_zod31.z.literal("function").optional(), + function: import_zod31.z.object({ + name: import_zod31.z.string().nullish(), + arguments: import_zod31.z.string().nullish() + }) + }) + ).nullish() + }).nullish(), + finish_reason: import_zod31.z.string().nullable().optional(), + index: import_zod31.z.number() + }) + ), + x_groq: import_zod31.z.object({ + usage: import_zod31.z.object({ + prompt_tokens: import_zod31.z.number().nullish(), + completion_tokens: import_zod31.z.number().nullish() + }).nullish() + }).nullish() + }), + groqErrorDataSchema +]); +var groqProviderOptionsSchema = import_zod33.z.object({ + language: import_zod33.z.string().nullish(), + prompt: import_zod33.z.string().nullish(), + responseFormat: import_zod33.z.string().nullish(), + temperature: import_zod33.z.number().min(0).max(1).nullish(), + timestampGranularities: import_zod33.z.array(import_zod33.z.string()).nullish() +}); +var GroqTranscriptionModel = class { + constructor(modelId, config) { + this.modelId = modelId; + this.config = config; + this.specificationVersion = "v1"; + } + get provider() { + return this.config.provider; + } + getArgs({ + audio, + mediaType, + providerOptions + }) { + var _a15, _b, _c, _d, _e; + const warnings = []; + const groqOptions = parseProviderOptions({ + provider: "groq", + providerOptions, + schema: groqProviderOptionsSchema + }); + const formData = new FormData(); + const blob = audio instanceof Uint8Array ? new Blob([audio]) : new Blob([convertBase64ToUint8Array(audio)]); + formData.append("model", this.modelId); + formData.append("file", new File([blob], "audio", { type: mediaType })); + if (groqOptions) { + const transcriptionModelOptions = { + language: (_a15 = groqOptions.language) != null ? _a15 : void 0, + prompt: (_b = groqOptions.prompt) != null ? _b : void 0, + response_format: (_c = groqOptions.responseFormat) != null ? _c : void 0, + temperature: (_d = groqOptions.temperature) != null ? _d : void 0, + timestamp_granularities: (_e = groqOptions.timestampGranularities) != null ? _e : void 0 + }; + for (const key in transcriptionModelOptions) { + const value = transcriptionModelOptions[key]; + if (value !== void 0) { + formData.append(key, String(value)); + } + } + } + return { + formData, + warnings + }; + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e; + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const { formData, warnings } = this.getArgs(options); + const { + value: response, + responseHeaders, + rawValue: rawResponse + } = yield postFormDataToApi({ + url: this.config.url({ + path: "/audio/transcriptions", + modelId: this.modelId + }), + headers: combineHeaders(this.config.headers(), options.headers), + formData, + failedResponseHandler: groqFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + groqTranscriptionResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + return { + text: response.text, + segments: (_e = (_d = response.segments) == null ? void 0 : _d.map((segment) => ({ + text: segment.text, + startSecond: segment.start, + endSecond: segment.end + }))) != null ? _e : [], + language: response.language, + durationInSeconds: response.duration, + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders, + body: rawResponse + } + }; + }); + } +}; +var groqTranscriptionResponseSchema = import_zod33.z.object({ + task: import_zod33.z.string(), + language: import_zod33.z.string(), + duration: import_zod33.z.number(), + text: import_zod33.z.string(), + segments: import_zod33.z.array( + import_zod33.z.object({ + id: import_zod33.z.number(), + seek: import_zod33.z.number(), + start: import_zod33.z.number(), + end: import_zod33.z.number(), + text: import_zod33.z.string(), + tokens: import_zod33.z.array(import_zod33.z.number()), + temperature: import_zod33.z.number(), + avg_logprob: import_zod33.z.number(), + compression_ratio: import_zod33.z.number(), + no_speech_prob: import_zod33.z.number() + }) + ), + x_groq: import_zod33.z.object({ + id: import_zod33.z.string() + }) +}); +function createGroq(options = {}) { + var _a15; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.groq.com/openai/v1"; + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "GROQ_API_KEY", + description: "Groq" + })}` + }, options.headers); + const createChatModel = (modelId, settings = {}) => new GroqChatLanguageModel(modelId, settings, { + provider: "groq.chat", + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createLanguageModel = (modelId, settings) => { + if (new.target) { + throw new Error( + "The Groq model function cannot be called with the new keyword." + ); + } + return createChatModel(modelId, settings); + }; + const createTranscriptionModel = (modelId) => { + return new GroqTranscriptionModel(modelId, { + provider: "groq.transcription", + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + }; + const provider = function(modelId, settings) { + return createLanguageModel(modelId, settings); + }; + provider.languageModel = createLanguageModel; + provider.chat = createChatModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + provider.transcription = createTranscriptionModel; + return provider; +} +var groq = createGroq(); + +// node_modules/.pnpm/@ai-sdk+cerebras@0.2.13_zod@3.25.67/node_modules/@ai-sdk/cerebras/dist/index.mjs +var import_zod34 = require("zod"); +var cerebrasErrorSchema = import_zod34.z.object({ + message: import_zod34.z.string(), + type: import_zod34.z.string(), + param: import_zod34.z.string(), + code: import_zod34.z.string() +}); +var cerebrasErrorStructure = { + errorSchema: cerebrasErrorSchema, + errorToMessage: (data) => data.message +}; +function createCerebras(options = {}) { + var _a15; + const baseURL = withoutTrailingSlash( + (_a15 = options.baseURL) != null ? _a15 : "https://api.cerebras.ai/v1" + ); + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "CEREBRAS_API_KEY", + description: "Cerebras API key" + })}` + }, options.headers); + const createLanguageModel = (modelId, settings = {}) => { + return new OpenAICompatibleChatLanguageModel(modelId, settings, { + provider: `cerebras.chat`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch, + defaultObjectGenerationMode: "tool", + errorStructure: cerebrasErrorStructure + }); + }; + const provider = (modelId, settings) => createLanguageModel(modelId, settings); + provider.languageModel = createLanguageModel; + provider.chat = createLanguageModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + return provider; +} +var cerebras = createCerebras(); + +// node_modules/.pnpm/@ai-sdk+togetherai@0.2.13_zod@3.25.67/node_modules/@ai-sdk/togetherai/dist/index.mjs +var import_zod35 = require("zod"); +var TogetherAIImageModel = class { + constructor(modelId, settings, config) { + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v1"; + } + get provider() { + return this.config.provider; + } + get maxImagesPerCall() { + var _a15; + return (_a15 = this.settings.maxImagesPerCall) != null ? _a15 : 1; + } + doGenerate(_0) { + return __async(this, arguments, function* ({ + prompt, + n, + size, + seed, + providerOptions, + headers, + abortSignal + }) { + var _a15, _b, _c, _d; + const warnings = []; + if (size != null) { + warnings.push({ + type: "unsupported-setting", + setting: "aspectRatio", + details: "This model does not support the `aspectRatio` option. Use `size` instead." + }); + } + const currentDate = (_c = (_b = (_a15 = this.config._internal) == null ? void 0 : _a15.currentDate) == null ? void 0 : _b.call(_a15)) != null ? _c : /* @__PURE__ */ new Date(); + const splitSize = size == null ? void 0 : size.split("x"); + const { value: response, responseHeaders } = yield postJsonToApi({ + url: `${this.config.baseURL}/images/generations`, + headers: combineHeaders(this.config.headers(), headers), + body: __spreadValues(__spreadProps(__spreadValues({ + model: this.modelId, + prompt, + seed, + n + }, splitSize && { + width: parseInt(splitSize[0]), + height: parseInt(splitSize[1]) + }), { + response_format: "base64" + }), (_d = providerOptions.togetherai) != null ? _d : {}), + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: togetheraiErrorSchema, + errorToMessage: (data) => data.error.message + }), + successfulResponseHandler: createJsonResponseHandler( + togetheraiImageResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + images: response.data.map((item) => item.b64_json), + warnings, + response: { + timestamp: currentDate, + modelId: this.modelId, + headers: responseHeaders + } + }; + }); + } +}; +var togetheraiImageResponseSchema = import_zod35.z.object({ + data: import_zod35.z.array( + import_zod35.z.object({ + b64_json: import_zod35.z.string() + }) + ) +}); +var togetheraiErrorSchema = import_zod35.z.object({ + error: import_zod35.z.object({ + message: import_zod35.z.string() + }) +}); +function createTogetherAI(options = {}) { + var _a15; + const baseURL = withoutTrailingSlash( + (_a15 = options.baseURL) != null ? _a15 : "https://api.together.xyz/v1/" + ); + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "TOGETHER_AI_API_KEY", + description: "TogetherAI" + })}` + }, options.headers); + const getCommonModelConfig = (modelType) => ({ + provider: `togetherai.${modelType}`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch + }); + const createChatModel = (modelId, settings = {}) => { + return new OpenAICompatibleChatLanguageModel(modelId, settings, __spreadProps(__spreadValues({}, getCommonModelConfig("chat")), { + defaultObjectGenerationMode: "tool" + })); + }; + const createCompletionModel = (modelId, settings = {}) => new OpenAICompatibleCompletionLanguageModel( + modelId, + settings, + getCommonModelConfig("completion") + ); + const createTextEmbeddingModel = (modelId, settings = {}) => new OpenAICompatibleEmbeddingModel( + modelId, + settings, + getCommonModelConfig("embedding") + ); + const createImageModel = (modelId, settings = {}) => new TogetherAIImageModel(modelId, settings, __spreadProps(__spreadValues({}, getCommonModelConfig("image")), { + baseURL: baseURL != null ? baseURL : "https://api.together.xyz/v1/" + })); + const provider = (modelId, settings) => createChatModel(modelId, settings); + provider.completionModel = createCompletionModel; + provider.languageModel = createChatModel; + provider.chatModel = createChatModel; + provider.textEmbeddingModel = createTextEmbeddingModel; + provider.image = createImageModel; + provider.imageModel = createImageModel; + return provider; +} +var togetherai = createTogetherAI(); + +// node_modules/.pnpm/@ai-sdk+mistral@1.2.7_zod@3.25.67/node_modules/@ai-sdk/mistral/dist/index.mjs +var import_zod36 = require("zod"); +var import_zod37 = require("zod"); +var import_zod38 = require("zod"); +function convertToMistralChatMessages(prompt) { + const messages = []; + for (let i = 0; i < prompt.length; i++) { + const { role, content } = prompt[i]; + const isLastMessage = i === prompt.length - 1; + switch (role) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "user": { + messages.push({ + role: "user", + content: content.map((part) => { + var _a15; + switch (part.type) { + case "text": { + return { type: "text", text: part.text }; + } + case "image": { + return { + type: "image_url", + image_url: part.image instanceof URL ? part.image.toString() : `data:${(_a15 = part.mimeType) != null ? _a15 : "image/jpeg"};base64,${convertUint8ArrayToBase64(part.image)}` + }; + } + case "file": { + if (!(part.data instanceof URL)) { + throw new UnsupportedFunctionalityError({ + functionality: "File content parts in user messages" + }); + } + switch (part.mimeType) { + case "application/pdf": { + return { + type: "document_url", + document_url: part.data.toString() + }; + } + default: { + throw new UnsupportedFunctionalityError({ + functionality: "Only PDF files are supported in user messages" + }); + } + } + } + } + }) + }); + break; + } + case "assistant": { + let text = ""; + const toolCalls = []; + for (const part of content) { + switch (part.type) { + case "text": { + text += part.text; + break; + } + case "tool-call": { + toolCalls.push({ + id: part.toolCallId, + type: "function", + function: { + name: part.toolName, + arguments: JSON.stringify(part.args) + } + }); + break; + } + } + } + messages.push({ + role: "assistant", + content: text, + prefix: isLastMessage ? true : void 0, + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + break; + } + case "tool": { + for (const toolResponse of content) { + messages.push({ + role: "tool", + name: toolResponse.toolName, + content: JSON.stringify(toolResponse.result), + tool_call_id: toolResponse.toolCallId + }); + } + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return messages; +} +function mapMistralFinishReason(finishReason) { + switch (finishReason) { + case "stop": + return "stop"; + case "length": + case "model_length": + return "length"; + case "tool_calls": + return "tool-calls"; + default: + return "unknown"; + } +} +var mistralErrorDataSchema = import_zod37.z.object({ + object: import_zod37.z.literal("error"), + message: import_zod37.z.string(), + type: import_zod37.z.string(), + param: import_zod37.z.string().nullable(), + code: import_zod37.z.string().nullable() +}); +var mistralFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: mistralErrorDataSchema, + errorToMessage: (data) => data.message +}); +function getResponseMetadata5({ + id, + model, + created +}) { + return { + id: id != null ? id : void 0, + modelId: model != null ? model : void 0, + timestamp: created != null ? new Date(created * 1e3) : void 0 + }; +} +function prepareTools7(mode) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + if (tools == null) { + return { tools: void 0, tool_choice: void 0, toolWarnings }; + } + const mistralTools = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ type: "unsupported-tool", tool }); + } else { + mistralTools.push({ + type: "function", + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters + } + }); + } + } + const toolChoice = mode.toolChoice; + if (toolChoice == null) { + return { tools: mistralTools, tool_choice: void 0, toolWarnings }; + } + const type = toolChoice.type; + switch (type) { + case "auto": + case "none": + return { tools: mistralTools, tool_choice: type, toolWarnings }; + case "required": + return { tools: mistralTools, tool_choice: "any", toolWarnings }; + case "tool": + return { + tools: mistralTools.filter( + (tool) => tool.function.name === toolChoice.toolName + ), + tool_choice: "any", + toolWarnings + }; + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +var MistralChatLanguageModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsImageUrls = false; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + supportsUrl(url) { + return url.protocol === "https:"; + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15, _b; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (frequencyPenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "frequencyPenalty" + }); + } + if (presencePenalty != null) { + warnings.push({ + type: "unsupported-setting", + setting: "presencePenalty" + }); + } + if (stopSequences != null) { + warnings.push({ + type: "unsupported-setting", + setting: "stopSequences" + }); + } + if (responseFormat != null && responseFormat.type === "json" && responseFormat.schema != null) { + warnings.push({ + type: "unsupported-setting", + setting: "responseFormat", + details: "JSON response format schema is not supported" + }); + } + const baseArgs = { + // model id: + model: this.modelId, + // model specific settings: + safe_prompt: this.settings.safePrompt, + // standardized settings: + max_tokens: maxTokens, + temperature, + top_p: topP, + random_seed: seed, + // response format: + response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { type: "json_object" } : void 0, + // mistral-specific provider options: + document_image_limit: (_a15 = providerMetadata == null ? void 0 : providerMetadata.mistral) == null ? void 0 : _a15.documentImageLimit, + document_page_limit: (_b = providerMetadata == null ? void 0 : providerMetadata.mistral) == null ? void 0 : _b.documentPageLimit, + // messages: + messages: convertToMistralChatMessages(prompt) + }; + switch (type) { + case "regular": { + const { tools, tool_choice, toolWarnings } = prepareTools7(mode); + return { + args: __spreadProps(__spreadValues({}, baseArgs), { tools, tool_choice }), + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: { type: "json_object" } + }), + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + tool_choice: "any", + tools: [{ type: "function", function: mode.tool }] + }), + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15; + const { args, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: `${this.config.baseURL}/chat/completions`, + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: mistralFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + mistralChatResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = response.choices[0]; + let text = extractTextContent(choice.message.content); + const lastMessage = rawPrompt[rawPrompt.length - 1]; + if (lastMessage.role === "assistant" && (text == null ? void 0 : text.startsWith(lastMessage.content))) { + text = text.slice(lastMessage.content.length); + } + return { + text, + toolCalls: (_a15 = choice.message.tool_calls) == null ? void 0 : _a15.map((toolCall) => ({ + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + args: toolCall.function.arguments + })), + finishReason: mapMistralFinishReason(choice.finish_reason), + usage: { + promptTokens: response.usage.prompt_tokens, + completionTokens: response.usage.completion_tokens + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { + headers: responseHeaders, + body: rawResponse + }, + request: { body: JSON.stringify(args) }, + response: getResponseMetadata5(response), + warnings + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { stream: true }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: `${this.config.baseURL}/chat/completions`, + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: mistralFailedResponseHandler, + successfulResponseHandler: createEventSourceResponseHandler( + mistralChatChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + let chunkNumber = 0; + let trimLeadingSpace = false; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + if (!chunk.success) { + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + chunkNumber++; + const value = chunk.value; + if (chunkNumber === 1) { + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata5(value))); + } + if (value.usage != null) { + usage = { + promptTokens: value.usage.prompt_tokens, + completionTokens: value.usage.completion_tokens + }; + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapMistralFinishReason(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + const textContent = extractTextContent(delta.content); + if (chunkNumber <= 2) { + const lastMessage = rawPrompt[rawPrompt.length - 1]; + if (lastMessage.role === "assistant" && textContent === lastMessage.content.trimEnd()) { + if (textContent.length < lastMessage.content.length) { + trimLeadingSpace = true; + } + return; + } + } + if (textContent != null) { + controller.enqueue({ + type: "text-delta", + textDelta: trimLeadingSpace ? textContent.trimStart() : textContent + }); + trimLeadingSpace = false; + } + if (delta.tool_calls != null) { + for (const toolCall of delta.tool_calls) { + controller.enqueue({ + type: "tool-call-delta", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + argsTextDelta: toolCall.function.arguments + }); + controller.enqueue({ + type: "tool-call", + toolCallType: "function", + toolCallId: toolCall.id, + toolName: toolCall.function.name, + args: toolCall.function.arguments + }); + } + } + }, + flush(controller) { + controller.enqueue({ type: "finish", finishReason, usage }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +function extractTextContent(content) { + if (typeof content === "string") { + return content; + } + if (content == null) { + return void 0; + } + const textContent = []; + for (const chunk of content) { + const { type } = chunk; + switch (type) { + case "text": + textContent.push(chunk.text); + break; + case "image_url": + case "reference": + break; + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + return textContent.length ? textContent.join("") : void 0; +} +var mistralContentSchema = import_zod36.z.union([ + import_zod36.z.string(), + import_zod36.z.array( + import_zod36.z.discriminatedUnion("type", [ + import_zod36.z.object({ + type: import_zod36.z.literal("text"), + text: import_zod36.z.string() + }), + import_zod36.z.object({ + type: import_zod36.z.literal("image_url"), + image_url: import_zod36.z.union([ + import_zod36.z.string(), + import_zod36.z.object({ + url: import_zod36.z.string(), + detail: import_zod36.z.string().nullable() + }) + ]) + }), + import_zod36.z.object({ + type: import_zod36.z.literal("reference"), + reference_ids: import_zod36.z.array(import_zod36.z.number()) + }) + ]) + ) +]).nullish(); +var mistralChatResponseSchema = import_zod36.z.object({ + id: import_zod36.z.string().nullish(), + created: import_zod36.z.number().nullish(), + model: import_zod36.z.string().nullish(), + choices: import_zod36.z.array( + import_zod36.z.object({ + message: import_zod36.z.object({ + role: import_zod36.z.literal("assistant"), + content: mistralContentSchema, + tool_calls: import_zod36.z.array( + import_zod36.z.object({ + id: import_zod36.z.string(), + function: import_zod36.z.object({ name: import_zod36.z.string(), arguments: import_zod36.z.string() }) + }) + ).nullish() + }), + index: import_zod36.z.number(), + finish_reason: import_zod36.z.string().nullish() + }) + ), + object: import_zod36.z.literal("chat.completion"), + usage: import_zod36.z.object({ + prompt_tokens: import_zod36.z.number(), + completion_tokens: import_zod36.z.number() + }) +}); +var mistralChatChunkSchema = import_zod36.z.object({ + id: import_zod36.z.string().nullish(), + created: import_zod36.z.number().nullish(), + model: import_zod36.z.string().nullish(), + choices: import_zod36.z.array( + import_zod36.z.object({ + delta: import_zod36.z.object({ + role: import_zod36.z.enum(["assistant"]).optional(), + content: mistralContentSchema, + tool_calls: import_zod36.z.array( + import_zod36.z.object({ + id: import_zod36.z.string(), + function: import_zod36.z.object({ name: import_zod36.z.string(), arguments: import_zod36.z.string() }) + }) + ).nullish() + }), + finish_reason: import_zod36.z.string().nullish(), + index: import_zod36.z.number() + }) + ), + usage: import_zod36.z.object({ + prompt_tokens: import_zod36.z.number(), + completion_tokens: import_zod36.z.number() + }).nullish() +}); +var MistralEmbeddingModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + var _a15; + return (_a15 = this.settings.maxEmbeddingsPerCall) != null ? _a15 : 32; + } + get supportsParallelCalls() { + var _a15; + return (_a15 = this.settings.supportsParallelCalls) != null ? _a15 : false; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + values, + abortSignal, + headers + }) { + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + provider: this.provider, + modelId: this.modelId, + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + values + }); + } + const { responseHeaders, value: response } = yield postJsonToApi({ + url: `${this.config.baseURL}/embeddings`, + headers: combineHeaders(this.config.headers(), headers), + body: { + model: this.modelId, + input: values, + encoding_format: "float" + }, + failedResponseHandler: mistralFailedResponseHandler, + successfulResponseHandler: createJsonResponseHandler( + MistralTextEmbeddingResponseSchema + ), + abortSignal, + fetch: this.config.fetch + }); + return { + embeddings: response.data.map((item) => item.embedding), + usage: response.usage ? { tokens: response.usage.prompt_tokens } : void 0, + rawResponse: { headers: responseHeaders } + }; + }); + } +}; +var MistralTextEmbeddingResponseSchema = import_zod38.z.object({ + data: import_zod38.z.array(import_zod38.z.object({ embedding: import_zod38.z.array(import_zod38.z.number()) })), + usage: import_zod38.z.object({ prompt_tokens: import_zod38.z.number() }).nullish() +}); +function createMistral(options = {}) { + var _a15; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "https://api.mistral.ai/v1"; + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "MISTRAL_API_KEY", + description: "Mistral" + })}` + }, options.headers); + const createChatModel = (modelId, settings = {}) => new MistralChatLanguageModel(modelId, settings, { + provider: "mistral.chat", + baseURL, + headers: getHeaders, + fetch: options.fetch + }); + const createEmbeddingModel = (modelId, settings = {}) => new MistralEmbeddingModel(modelId, settings, { + provider: "mistral.embedding", + baseURL, + headers: getHeaders, + fetch: options.fetch + }); + const provider = function(modelId, settings) { + if (new.target) { + throw new Error( + "The Mistral model function cannot be called with the new keyword." + ); + } + return createChatModel(modelId, settings); + }; + provider.languageModel = createChatModel; + provider.chat = createChatModel; + provider.embedding = createEmbeddingModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + return provider; +} +var mistral = createMistral(); + +// node_modules/.pnpm/@ai-sdk+deepseek@0.2.13_zod@3.25.67/node_modules/@ai-sdk/deepseek/dist/index.mjs +var import_zod39 = require("zod"); +var buildDeepseekMetadata = (usage) => { + var _a15, _b; + return usage == null ? void 0 : { + deepseek: { + promptCacheHitTokens: (_a15 = usage.prompt_cache_hit_tokens) != null ? _a15 : NaN, + promptCacheMissTokens: (_b = usage.prompt_cache_miss_tokens) != null ? _b : NaN + } + }; +}; +var deepSeekMetadataExtractor = { + extractMetadata: ({ parsedBody }) => { + const parsed = safeValidateTypes({ + value: parsedBody, + schema: deepSeekResponseSchema + }); + return !parsed.success || parsed.value.usage == null ? void 0 : buildDeepseekMetadata(parsed.value.usage); + }, + createStreamExtractor: () => { + let usage; + return { + processChunk: (chunk) => { + var _a15, _b; + const parsed = safeValidateTypes({ + value: chunk, + schema: deepSeekStreamChunkSchema + }); + if (parsed.success && ((_b = (_a15 = parsed.value.choices) == null ? void 0 : _a15[0]) == null ? void 0 : _b.finish_reason) === "stop" && parsed.value.usage) { + usage = parsed.value.usage; + } + }, + buildMetadata: () => buildDeepseekMetadata(usage) + }; + } +}; +var deepSeekUsageSchema = import_zod39.z.object({ + prompt_cache_hit_tokens: import_zod39.z.number().nullish(), + prompt_cache_miss_tokens: import_zod39.z.number().nullish() +}); +var deepSeekResponseSchema = import_zod39.z.object({ + usage: deepSeekUsageSchema.nullish() +}); +var deepSeekStreamChunkSchema = import_zod39.z.object({ + choices: import_zod39.z.array( + import_zod39.z.object({ + finish_reason: import_zod39.z.string().nullish() + }) + ).nullish(), + usage: deepSeekUsageSchema.nullish() +}); +function createDeepSeek(options = {}) { + var _a15; + const baseURL = withoutTrailingSlash( + (_a15 = options.baseURL) != null ? _a15 : "https://api.deepseek.com/v1" + ); + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "DEEPSEEK_API_KEY", + description: "DeepSeek API key" + })}` + }, options.headers); + const createLanguageModel = (modelId, settings = {}) => { + return new OpenAICompatibleChatLanguageModel(modelId, settings, { + provider: `deepseek.chat`, + url: ({ path: path4 }) => `${baseURL}${path4}`, + headers: getHeaders, + fetch: options.fetch, + defaultObjectGenerationMode: "json", + metadataExtractor: deepSeekMetadataExtractor + }); + }; + const provider = (modelId, settings) => createLanguageModel(modelId, settings); + provider.languageModel = createLanguageModel; + provider.chat = createLanguageModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + return provider; +} +var deepseek = createDeepSeek(); + +// node_modules/.pnpm/@ai-sdk+perplexity@1.1.8_zod@3.25.67/node_modules/@ai-sdk/perplexity/dist/index.mjs +var import_zod40 = require("zod"); +function convertToPerplexityMessages(prompt) { + const messages = []; + for (const { role, content } of prompt) { + switch (role) { + case "system": { + messages.push({ role: "system", content }); + break; + } + case "user": + case "assistant": { + messages.push({ + role, + content: content.filter( + (part) => part.type !== "reasoning" && part.type !== "redacted-reasoning" + ).map((part) => { + switch (part.type) { + case "text": { + return part.text; + } + case "image": { + throw new UnsupportedFunctionalityError({ + functionality: "Image content parts in user messages" + }); + } + case "file": { + throw new UnsupportedFunctionalityError({ + functionality: "File content parts in user messages" + }); + } + case "tool-call": { + throw new UnsupportedFunctionalityError({ + functionality: "Tool calls in assistant messages" + }); + } + default: { + const _exhaustiveCheck = part; + throw new Error(`Unsupported part: ${_exhaustiveCheck}`); + } + } + }).join("") + }); + break; + } + case "tool": { + throw new UnsupportedFunctionalityError({ + functionality: "Tool messages" + }); + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return messages; +} +function mapPerplexityFinishReason(finishReason) { + switch (finishReason) { + case "stop": + case "length": + return finishReason; + default: + return "unknown"; + } +} +var PerplexityLanguageModel = class { + constructor(modelId, config) { + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsStructuredOutputs = true; + this.supportsImageUrls = false; + this.provider = "perplexity"; + this.modelId = modelId; + this.config = config; + } + getArgs({ + mode, + prompt, + maxTokens, + temperature, + topP, + topK, + frequencyPenalty, + presencePenalty, + stopSequences, + responseFormat, + seed, + providerMetadata + }) { + var _a15; + const type = mode.type; + const warnings = []; + if (topK != null) { + warnings.push({ + type: "unsupported-setting", + setting: "topK" + }); + } + if (stopSequences != null) { + warnings.push({ + type: "unsupported-setting", + setting: "stopSequences" + }); + } + if (seed != null) { + warnings.push({ + type: "unsupported-setting", + setting: "seed" + }); + } + const baseArgs = __spreadProps(__spreadValues({ + // model id: + model: this.modelId, + // standardized settings: + frequency_penalty: frequencyPenalty, + max_tokens: maxTokens, + presence_penalty: presencePenalty, + temperature, + top_k: topK, + top_p: topP, + // response format: + response_format: (responseFormat == null ? void 0 : responseFormat.type) === "json" ? { + type: "json_schema", + json_schema: { schema: responseFormat.schema } + } : void 0 + }, (_a15 = providerMetadata == null ? void 0 : providerMetadata.perplexity) != null ? _a15 : {}), { + // messages: + messages: convertToPerplexityMessages(prompt) + }); + switch (type) { + case "regular": { + return { args: baseArgs, warnings }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArgs), { + response_format: { + type: "json_schema", + json_schema: { schema: mode.schema } + } + }), + warnings + }; + } + case "object-tool": { + throw new UnsupportedFunctionalityError({ + functionality: "tool-mode object generation" + }); + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k; + const { args, warnings } = this.getArgs(options); + const { + responseHeaders, + value: response, + rawValue: rawResponse + } = yield postJsonToApi({ + url: `${this.config.baseURL}/chat/completions`, + headers: combineHeaders(this.config.headers(), options.headers), + body: args, + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: perplexityErrorSchema, + errorToMessage + }), + successfulResponseHandler: createJsonResponseHandler( + perplexityResponseSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a16 = args, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const choice = response.choices[0]; + const text = choice.message.content; + return { + text, + toolCalls: [], + finishReason: mapPerplexityFinishReason(choice.finish_reason), + usage: { + promptTokens: (_b = (_a15 = response.usage) == null ? void 0 : _a15.prompt_tokens) != null ? _b : Number.NaN, + completionTokens: (_d = (_c = response.usage) == null ? void 0 : _c.completion_tokens) != null ? _d : Number.NaN + }, + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders, body: rawResponse }, + request: { body: JSON.stringify(args) }, + response: getResponseMetadata6(response), + warnings, + sources: (_e = response.citations) == null ? void 0 : _e.map((url) => ({ + sourceType: "url", + id: this.config.generateId(), + url + })), + providerMetadata: { + perplexity: { + images: (_g = (_f = response.images) == null ? void 0 : _f.map((image) => ({ + imageUrl: image.image_url, + originUrl: image.origin_url, + height: image.height, + width: image.width + }))) != null ? _g : null, + usage: { + citationTokens: (_i = (_h = response.usage) == null ? void 0 : _h.citation_tokens) != null ? _i : null, + numSearchQueries: (_k = (_j = response.usage) == null ? void 0 : _j.num_search_queries) != null ? _k : null + } + } + } + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + const { args, warnings } = this.getArgs(options); + const body = __spreadProps(__spreadValues({}, args), { stream: true }); + const { responseHeaders, value: response } = yield postJsonToApi({ + url: `${this.config.baseURL}/chat/completions`, + headers: combineHeaders(this.config.headers(), options.headers), + body, + failedResponseHandler: createJsonErrorResponseHandler({ + errorSchema: perplexityErrorSchema, + errorToMessage + }), + successfulResponseHandler: createEventSourceResponseHandler( + perplexityChunkSchema + ), + abortSignal: options.abortSignal, + fetch: this.config.fetch + }); + const _a15 = args, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + let finishReason = "unknown"; + let usage = { + promptTokens: Number.NaN, + completionTokens: Number.NaN + }; + const providerMetadata = { + perplexity: { + usage: { + citationTokens: null, + numSearchQueries: null + }, + images: null + } + }; + let isFirstChunk = true; + const self = this; + return { + stream: response.pipeThrough( + new TransformStream({ + transform(chunk, controller) { + var _a16, _b, _c; + if (!chunk.success) { + controller.enqueue({ type: "error", error: chunk.error }); + return; + } + const value = chunk.value; + if (isFirstChunk) { + controller.enqueue(__spreadValues({ + type: "response-metadata" + }, getResponseMetadata6(value))); + (_a16 = value.citations) == null ? void 0 : _a16.forEach((url) => { + controller.enqueue({ + type: "source", + source: { + sourceType: "url", + id: self.config.generateId(), + url + } + }); + }); + isFirstChunk = false; + } + if (value.usage != null) { + usage = { + promptTokens: value.usage.prompt_tokens, + completionTokens: value.usage.completion_tokens + }; + providerMetadata.perplexity.usage = { + citationTokens: (_b = value.usage.citation_tokens) != null ? _b : null, + numSearchQueries: (_c = value.usage.num_search_queries) != null ? _c : null + }; + } + if (value.images != null) { + providerMetadata.perplexity.images = value.images.map((image) => ({ + imageUrl: image.image_url, + originUrl: image.origin_url, + height: image.height, + width: image.width + })); + } + const choice = value.choices[0]; + if ((choice == null ? void 0 : choice.finish_reason) != null) { + finishReason = mapPerplexityFinishReason(choice.finish_reason); + } + if ((choice == null ? void 0 : choice.delta) == null) { + return; + } + const delta = choice.delta; + const textContent = delta.content; + if (textContent != null) { + controller.enqueue({ + type: "text-delta", + textDelta: textContent + }); + } + }, + flush(controller) { + controller.enqueue({ + type: "finish", + finishReason, + usage, + providerMetadata + }); + } + }) + ), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + warnings + }; + }); + } +}; +function getResponseMetadata6({ + id, + model, + created +}) { + return { + id, + modelId: model, + timestamp: new Date(created * 1e3) + }; +} +var perplexityUsageSchema = import_zod40.z.object({ + prompt_tokens: import_zod40.z.number(), + completion_tokens: import_zod40.z.number(), + citation_tokens: import_zod40.z.number().nullish(), + num_search_queries: import_zod40.z.number().nullish() +}); +var perplexityImageSchema = import_zod40.z.object({ + image_url: import_zod40.z.string(), + origin_url: import_zod40.z.string(), + height: import_zod40.z.number(), + width: import_zod40.z.number() +}); +var perplexityResponseSchema = import_zod40.z.object({ + id: import_zod40.z.string(), + created: import_zod40.z.number(), + model: import_zod40.z.string(), + choices: import_zod40.z.array( + import_zod40.z.object({ + message: import_zod40.z.object({ + role: import_zod40.z.literal("assistant"), + content: import_zod40.z.string() + }), + finish_reason: import_zod40.z.string().nullish() + }) + ), + citations: import_zod40.z.array(import_zod40.z.string()).nullish(), + images: import_zod40.z.array(perplexityImageSchema).nullish(), + usage: perplexityUsageSchema.nullish() +}); +var perplexityChunkSchema = import_zod40.z.object({ + id: import_zod40.z.string(), + created: import_zod40.z.number(), + model: import_zod40.z.string(), + choices: import_zod40.z.array( + import_zod40.z.object({ + delta: import_zod40.z.object({ + role: import_zod40.z.literal("assistant"), + content: import_zod40.z.string() + }), + finish_reason: import_zod40.z.string().nullish() + }) + ), + citations: import_zod40.z.array(import_zod40.z.string()).nullish(), + images: import_zod40.z.array(perplexityImageSchema).nullish(), + usage: perplexityUsageSchema.nullish() +}); +var perplexityErrorSchema = import_zod40.z.object({ + error: import_zod40.z.object({ + code: import_zod40.z.number(), + message: import_zod40.z.string().nullish(), + type: import_zod40.z.string().nullish() + }) +}); +var errorToMessage = (data) => { + var _a15, _b; + return (_b = (_a15 = data.error.message) != null ? _a15 : data.error.type) != null ? _b : "unknown error"; +}; +function createPerplexity(options = {}) { + const getHeaders = () => __spreadValues({ + Authorization: `Bearer ${loadApiKey({ + apiKey: options.apiKey, + environmentVariableName: "PERPLEXITY_API_KEY", + description: "Perplexity" + })}` + }, options.headers); + const createLanguageModel = (modelId) => { + var _a15; + return new PerplexityLanguageModel(modelId, { + baseURL: withoutTrailingSlash( + (_a15 = options.baseURL) != null ? _a15 : "https://api.perplexity.ai" + ), + headers: getHeaders, + generateId, + fetch: options.fetch + }); + }; + const provider = (modelId) => createLanguageModel(modelId); + provider.languageModel = createLanguageModel; + provider.textEmbeddingModel = (modelId) => { + throw new NoSuchModelError({ modelId, modelType: "textEmbeddingModel" }); + }; + return provider; +} +var perplexity = createPerplexity(); + +// node_modules/.pnpm/ollama-ai-provider@1.2.0_zod@3.25.67/node_modules/ollama-ai-provider/dist/index.mjs +var import_zod41 = require("zod"); +var import_partial_json = __toESM(require_dist(), 1); +var import_zod42 = require("zod"); +var import_zod43 = require("zod"); +function convertToOllamaChatMessages(prompt) { + const messages = []; + for (const { content, role } of prompt) { + switch (role) { + case "system": { + messages.push({ content, role: "system" }); + break; + } + case "user": { + messages.push(__spreadProps(__spreadValues({}, content.reduce( + (previous, current) => { + if (current.type === "text") { + previous.content += current.text; + } else if (current.type === "image" && current.image instanceof URL) { + throw new UnsupportedFunctionalityError({ + functionality: "Image URLs in user messages" + }); + } else if (current.type === "image" && current.image instanceof Uint8Array) { + previous.images = previous.images || []; + previous.images.push(convertUint8ArrayToBase64(current.image)); + } + return previous; + }, + { content: "" } + )), { + role: "user" + })); + break; + } + case "assistant": { + const text = []; + const toolCalls = []; + for (const part of content) { + switch (part.type) { + case "text": { + text.push(part.text); + break; + } + case "tool-call": { + toolCalls.push({ + function: { + arguments: part.args, + name: part.toolName + }, + id: part.toolCallId, + type: "function" + }); + break; + } + default: { + const _exhaustiveCheck = part; + throw new Error(`Unsupported part: ${_exhaustiveCheck}`); + } + } + } + messages.push({ + content: text.join(","), + role: "assistant", + tool_calls: toolCalls.length > 0 ? toolCalls : void 0 + }); + break; + } + case "tool": { + messages.push( + ...content.map((part) => ({ + // Non serialized contents are not accepted by ollama, triggering the following error: + // "json: cannot unmarshal array into Go struct field ChatRequest.messages of type string" + content: typeof part.result === "object" ? JSON.stringify(part.result) : `${part.result}`, + role: "tool", + tool_call_id: part.toolCallId + })) + ); + break; + } + default: { + const _exhaustiveCheck = role; + throw new Error(`Unsupported role: ${_exhaustiveCheck}`); + } + } + } + return messages; +} +var InferToolCallsFromStream = class { + constructor({ + tools, + type + }) { + this._firstMessage = true; + this._tools = tools; + this._toolPartial = ""; + this._toolCalls = []; + this._type = type; + this._detectedToolCall = false; + } + get toolCalls() { + return this._toolCalls; + } + get detectedToolCall() { + return this._detectedToolCall; + } + parse({ + controller, + delta + }) { + var _a15; + this.detectToolCall(delta); + if (!this._detectedToolCall) { + return false; + } + this._toolPartial += delta; + let parsedFunctions = (0, import_partial_json.parse)(this._toolPartial); + if (!Array.isArray(parsedFunctions)) { + parsedFunctions = [parsedFunctions]; + } + for (const [index, parsedFunction] of parsedFunctions.entries()) { + const parsedArguments = (_a15 = JSON.stringify(parsedFunction == null ? void 0 : parsedFunction.parameters)) != null ? _a15 : ""; + if (parsedArguments === "") { + continue; + } + if (!this._toolCalls[index]) { + this._toolCalls[index] = { + function: { + arguments: "", + name: parsedFunction.name + }, + id: generateId(), + type: "function" + }; + } + const toolCall = this._toolCalls[index]; + toolCall.function.arguments = parsedArguments; + controller.enqueue({ + argsTextDelta: delta, + toolCallId: toolCall.id, + toolCallType: "function", + toolName: toolCall.function.name, + type: "tool-call-delta" + }); + } + return true; + } + finish({ + controller + }) { + for (const toolCall of this.toolCalls) { + controller.enqueue({ + args: toolCall.function.arguments, + toolCallId: toolCall.id, + toolCallType: "function", + toolName: toolCall.function.name, + type: "tool-call" + }); + } + return this.finishReason(); + } + detectToolCall(delta) { + if (!this._tools || this._tools.length === 0) { + return; + } + if (this._firstMessage) { + if (this._type === "object-tool") { + this._detectedToolCall = true; + } else if (this._type === "regular" && (delta.trim().startsWith("{") || delta.trim().startsWith("["))) { + this._detectedToolCall = true; + } + this._firstMessage = false; + } + } + finishReason() { + if (!this.detectedToolCall) { + return "stop"; + } + return this._type === "object-tool" ? "stop" : "tool-calls"; + } +}; +function mapOllamaFinishReason({ + finishReason, + hasToolCalls +}) { + switch (finishReason) { + case "stop": { + return hasToolCalls ? "tool-calls" : "stop"; + } + default: { + return "other"; + } + } +} +var ollamaErrorDataSchema = import_zod42.z.object({ + error: import_zod42.z.object({ + code: import_zod42.z.string().nullable(), + message: import_zod42.z.string(), + param: import_zod42.z.any().nullable(), + type: import_zod42.z.string() + }) +}); +var ollamaFailedResponseHandler = createJsonErrorResponseHandler({ + errorSchema: ollamaErrorDataSchema, + errorToMessage: (data) => data.error.message +}); +function prepareTools8({ + mode +}) { + var _a15; + const tools = ((_a15 = mode.tools) == null ? void 0 : _a15.length) ? mode.tools : void 0; + const toolWarnings = []; + const toolChoice = mode.toolChoice; + if (tools === void 0) { + return { + tools: void 0, + toolWarnings + }; + } + const ollamaTools = []; + for (const tool of tools) { + if (tool.type === "provider-defined") { + toolWarnings.push({ tool, type: "unsupported-tool" }); + } else { + ollamaTools.push({ + function: { + description: tool.description, + name: tool.name, + parameters: tool.parameters + }, + type: "function" + }); + } + } + if (toolChoice === void 0) { + return { + tools: ollamaTools, + toolWarnings + }; + } + const type = toolChoice.type; + switch (type) { + case "auto": { + return { + tools: ollamaTools, + toolWarnings + }; + } + case "none": { + return { + tools: void 0, + toolWarnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new UnsupportedFunctionalityError({ + functionality: `Unsupported tool choice type: ${_exhaustiveCheck}` + }); + } + } +} +function removeUndefined(object) { + return Object.fromEntries( + Object.entries(object).filter(([, v]) => v !== void 0) + ); +} +var TextLineStream = class extends TransformStream { + constructor() { + super({ + flush: (controller) => { + if (this.buffer.length === 0) return; + controller.enqueue(this.buffer); + }, + transform: (chunkText, controller) => { + chunkText = this.buffer + chunkText; + while (true) { + const EOL = chunkText.indexOf("\n"); + if (EOL === -1) break; + controller.enqueue(chunkText.slice(0, EOL)); + chunkText = chunkText.slice(EOL + 1); + } + this.buffer = chunkText; + } + }); + this.buffer = ""; + } +}; +var createJsonStreamResponseHandler = (chunkSchema2) => (_0) => __async(null, [_0], function* ({ response }) { + const responseHeaders = extractResponseHeaders(response); + if (response.body === null) { + throw new EmptyResponseBodyError({}); + } + return { + responseHeaders, + value: response.body.pipeThrough(new TextDecoderStream()).pipeThrough(new TextLineStream()).pipeThrough( + new TransformStream({ + transform(chunkText, controller) { + controller.enqueue( + safeParseJSON({ + schema: chunkSchema2, + text: chunkText + }) + ); + } + }) + ) + }; +}); +var OllamaChatLanguageModel = class { + constructor(modelId, settings, config) { + this.modelId = modelId; + this.settings = settings; + this.config = config; + this.specificationVersion = "v1"; + this.defaultObjectGenerationMode = "json"; + this.supportsImageUrls = false; + } + get supportsStructuredOutputs() { + var _a15; + return (_a15 = this.settings.structuredOutputs) != null ? _a15 : false; + } + get provider() { + return this.config.provider; + } + getArguments({ + frequencyPenalty, + maxTokens, + mode, + presencePenalty, + prompt, + responseFormat, + seed, + stopSequences, + temperature, + topK, + topP + }) { + const type = mode.type; + const warnings = []; + if (responseFormat !== void 0 && responseFormat.type === "json" && responseFormat.schema !== void 0 && !this.supportsStructuredOutputs) { + warnings.push({ + details: "JSON response format schema is only supported with structuredOutputs", + setting: "responseFormat", + type: "unsupported-setting" + }); + } + const baseArguments = { + format: responseFormat == null ? void 0 : responseFormat.type, + model: this.modelId, + options: removeUndefined({ + f16_kv: this.settings.f16Kv, + frequency_penalty: frequencyPenalty, + low_vram: this.settings.lowVram, + main_gpu: this.settings.mainGpu, + min_p: this.settings.minP, + mirostat: this.settings.mirostat, + mirostat_eta: this.settings.mirostatEta, + mirostat_tau: this.settings.mirostatTau, + num_batch: this.settings.numBatch, + num_ctx: this.settings.numCtx, + num_gpu: this.settings.numGpu, + num_keep: this.settings.numKeep, + num_predict: maxTokens, + num_thread: this.settings.numThread, + numa: this.settings.numa, + penalize_newline: this.settings.penalizeNewline, + presence_penalty: presencePenalty, + repeat_last_n: this.settings.repeatLastN, + repeat_penalty: this.settings.repeatPenalty, + seed, + stop: stopSequences, + temperature, + tfs_z: this.settings.tfsZ, + top_k: topK, + top_p: topP, + typical_p: this.settings.typicalP, + use_mlock: this.settings.useMlock, + use_mmap: this.settings.useMmap, + vocab_only: this.settings.vocabOnly + }) + }; + switch (type) { + case "regular": { + const { tools, toolWarnings } = prepareTools8({ + mode + }); + return { + args: __spreadProps(__spreadValues({}, baseArguments), { + messages: convertToOllamaChatMessages(prompt), + tools + }), + type, + warnings: [...warnings, ...toolWarnings] + }; + } + case "object-json": { + return { + args: __spreadProps(__spreadValues({}, baseArguments), { + format: this.supportsStructuredOutputs && mode.schema !== void 0 ? mode.schema : "json", + messages: convertToOllamaChatMessages(prompt) + }), + type, + warnings + }; + } + case "object-tool": { + return { + args: __spreadProps(__spreadValues({}, baseArguments), { + messages: convertToOllamaChatMessages(prompt), + tool_choice: { + function: { name: mode.tool.name }, + type: "function" + }, + tools: [ + { + function: { + description: mode.tool.description, + name: mode.tool.name, + parameters: mode.tool.parameters + }, + type: "function" + } + ] + }), + type, + warnings + }; + } + default: { + const _exhaustiveCheck = type; + throw new Error(`Unsupported type: ${_exhaustiveCheck}`); + } + } + } + doGenerate(options) { + return __async(this, null, function* () { + var _a15, _b; + const { args, warnings } = this.getArguments(options); + const body = __spreadProps(__spreadValues({}, args), { + stream: false + }); + const { responseHeaders, value: response } = yield postJsonToApi({ + abortSignal: options.abortSignal, + body, + failedResponseHandler: ollamaFailedResponseHandler, + fetch: this.config.fetch, + headers: combineHeaders(this.config.headers(), options.headers), + successfulResponseHandler: createJsonResponseHandler( + ollamaChatResponseSchema + ), + url: `${this.config.baseURL}/chat` + }); + const _a16 = body, { messages: rawPrompt } = _a16, rawSettings = __objRest(_a16, ["messages"]); + const toolCalls = (_a15 = response.message.tool_calls) == null ? void 0 : _a15.map((toolCall) => { + var _a22; + return { + args: JSON.stringify(toolCall.function.arguments), + toolCallId: (_a22 = toolCall.id) != null ? _a22 : generateId(), + toolCallType: "function", + toolName: toolCall.function.name + }; + }); + return { + finishReason: mapOllamaFinishReason({ + finishReason: response.done_reason, + hasToolCalls: toolCalls !== void 0 && toolCalls.length > 0 + }), + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + text: (_b = response.message.content) != null ? _b : void 0, + toolCalls, + usage: { + completionTokens: response.eval_count || 0, + promptTokens: response.prompt_eval_count || 0 + }, + warnings + }; + }); + } + doStream(options) { + return __async(this, null, function* () { + if (this.settings.simulateStreaming) { + const result = yield this.doGenerate(options); + const simulatedStream = new ReadableStream({ + start(controller) { + controller.enqueue(__spreadValues({ type: "response-metadata" }, result.response)); + if (result.text) { + controller.enqueue({ + textDelta: result.text, + type: "text-delta" + }); + } + if (result.toolCalls) { + for (const toolCall of result.toolCalls) { + controller.enqueue({ + argsTextDelta: toolCall.args, + toolCallId: toolCall.toolCallId, + toolCallType: "function", + toolName: toolCall.toolName, + type: "tool-call-delta" + }); + controller.enqueue(__spreadValues({ + type: "tool-call" + }, toolCall)); + } + } + controller.enqueue({ + finishReason: result.finishReason, + logprobs: result.logprobs, + providerMetadata: result.providerMetadata, + type: "finish", + usage: result.usage + }); + controller.close(); + } + }); + return { + rawCall: result.rawCall, + rawResponse: result.rawResponse, + stream: simulatedStream, + warnings: result.warnings + }; + } + const { args: body, type, warnings } = this.getArguments(options); + const { responseHeaders, value: response } = yield postJsonToApi({ + abortSignal: options.abortSignal, + body, + failedResponseHandler: ollamaFailedResponseHandler, + fetch: this.config.fetch, + headers: combineHeaders(this.config.headers(), options.headers), + successfulResponseHandler: createJsonStreamResponseHandler( + ollamaChatStreamChunkSchema + ), + url: `${this.config.baseURL}/chat` + }); + const _a15 = body, { messages: rawPrompt } = _a15, rawSettings = __objRest(_a15, ["messages"]); + const tools = options.mode.type === "regular" ? options.mode.tools : options.mode.type === "object-tool" ? [options.mode.tool] : void 0; + const inferToolCallsFromStream = new InferToolCallsFromStream({ + tools, + type + }); + let finishReason = "other"; + let usage = { + completionTokens: Number.NaN, + promptTokens: Number.NaN + }; + const { experimentalStreamTools = true } = this.settings; + return { + rawCall: { rawPrompt, rawSettings }, + rawResponse: { headers: responseHeaders }, + request: { body: JSON.stringify(body) }, + stream: response.pipeThrough( + new TransformStream({ + flush(controller) { + return __async(this, null, function* () { + controller.enqueue({ + finishReason, + type: "finish", + usage + }); + }); + }, + transform(chunk, controller) { + return __async(this, null, function* () { + if (!chunk.success) { + controller.enqueue({ error: chunk.error, type: "error" }); + return; + } + const value = chunk.value; + if (value.done) { + finishReason = inferToolCallsFromStream.finish({ controller }); + usage = { + completionTokens: value.eval_count, + promptTokens: value.prompt_eval_count || 0 + }; + return; + } + if (experimentalStreamTools) { + const isToolCallStream = inferToolCallsFromStream.parse({ + controller, + delta: value.message.content + }); + if (isToolCallStream) { + return; + } + } + if (value.message.content !== null) { + controller.enqueue({ + textDelta: value.message.content, + type: "text-delta" + }); + } + }); + } + }) + ), + warnings + }; + }); + } +}; +var ollamaChatResponseSchema = import_zod41.z.object({ + created_at: import_zod41.z.string(), + done: import_zod41.z.literal(true), + done_reason: import_zod41.z.string().optional().nullable(), + eval_count: import_zod41.z.number(), + eval_duration: import_zod41.z.number(), + load_duration: import_zod41.z.number().optional(), + message: import_zod41.z.object({ + content: import_zod41.z.string(), + role: import_zod41.z.string(), + tool_calls: import_zod41.z.array( + import_zod41.z.object({ + function: import_zod41.z.object({ + arguments: import_zod41.z.record(import_zod41.z.any()), + name: import_zod41.z.string() + }), + id: import_zod41.z.string().optional() + }) + ).optional().nullable() + }), + model: import_zod41.z.string(), + prompt_eval_count: import_zod41.z.number().optional(), + prompt_eval_duration: import_zod41.z.number().optional(), + total_duration: import_zod41.z.number() +}); +var ollamaChatStreamChunkSchema = import_zod41.z.discriminatedUnion("done", [ + import_zod41.z.object({ + created_at: import_zod41.z.string(), + done: import_zod41.z.literal(false), + message: import_zod41.z.object({ + content: import_zod41.z.string(), + role: import_zod41.z.string() + }), + model: import_zod41.z.string() + }), + import_zod41.z.object({ + created_at: import_zod41.z.string(), + done: import_zod41.z.literal(true), + eval_count: import_zod41.z.number(), + eval_duration: import_zod41.z.number(), + load_duration: import_zod41.z.number().optional(), + model: import_zod41.z.string(), + prompt_eval_count: import_zod41.z.number().optional(), + prompt_eval_duration: import_zod41.z.number().optional(), + total_duration: import_zod41.z.number() + }) +]); +var OllamaEmbeddingModel = class { + constructor(modelId, settings, config) { + this.specificationVersion = "v1"; + this.modelId = modelId; + this.settings = settings; + this.config = config; + } + get provider() { + return this.config.provider; + } + get maxEmbeddingsPerCall() { + var _a15; + return (_a15 = this.settings.maxEmbeddingsPerCall) != null ? _a15 : 2048; + } + get supportsParallelCalls() { + return false; + } + doEmbed(_0) { + return __async(this, arguments, function* ({ + abortSignal, + values + }) { + if (values.length > this.maxEmbeddingsPerCall) { + throw new TooManyEmbeddingValuesForCallError({ + maxEmbeddingsPerCall: this.maxEmbeddingsPerCall, + modelId: this.modelId, + provider: this.provider, + values + }); + } + const { responseHeaders, value: response } = yield postJsonToApi({ + abortSignal, + body: { + input: values, + model: this.modelId + }, + failedResponseHandler: ollamaFailedResponseHandler, + fetch: this.config.fetch, + headers: this.config.headers(), + successfulResponseHandler: createJsonResponseHandler( + ollamaTextEmbeddingResponseSchema + ), + url: `${this.config.baseURL}/embed` + }); + return { + embeddings: response.embeddings, + rawResponse: { headers: responseHeaders }, + usage: response.prompt_eval_count ? { tokens: response.prompt_eval_count } : void 0 + }; + }); + } +}; +var ollamaTextEmbeddingResponseSchema = import_zod43.z.object({ + embeddings: import_zod43.z.array(import_zod43.z.array(import_zod43.z.number())), + prompt_eval_count: import_zod43.z.number().nullable() +}); +function createOllama(options = {}) { + var _a15; + const baseURL = (_a15 = withoutTrailingSlash(options.baseURL)) != null ? _a15 : "http://127.0.0.1:11434/api"; + const getHeaders = () => __spreadValues({}, options.headers); + const createChatModel = (modelId, settings = {}) => new OllamaChatLanguageModel(modelId, settings, { + baseURL, + fetch: options.fetch, + headers: getHeaders, + provider: "ollama.chat" + }); + const createEmbeddingModel = (modelId, settings = {}) => new OllamaEmbeddingModel(modelId, settings, { + baseURL, + fetch: options.fetch, + headers: getHeaders, + provider: "ollama.embedding" + }); + const provider = function(modelId, settings) { + if (new.target) { + throw new Error( + "The Ollama model function cannot be called with the new keyword." + ); + } + return createChatModel(modelId, settings); + }; + provider.chat = createChatModel; + provider.embedding = createEmbeddingModel; + provider.languageModel = createChatModel; + provider.textEmbedding = createEmbeddingModel; + provider.textEmbeddingModel = createEmbeddingModel; + return provider; +} +var ollama = createOllama(); + +// lib/llm/LLMProvider.ts +var AISDKProviders = { + openai, + anthropic, + google, + xai, + azure, + groq, + cerebras, + togetherai, + mistral, + deepseek, + perplexity, + ollama +}; +var AISDKProvidersWithAPIKey = { + openai: createOpenAI, + anthropic: createAnthropic, + google: createGoogleGenerativeAI, + xai: createXai, + azure: createAzure, + groq: createGroq, + cerebras: createCerebras, + togetherai: createTogetherAI, + mistral: createMistral, + deepseek: createDeepSeek, + perplexity: createPerplexity +}; +var modelToProviderMap = { + "gpt-4.1": "openai", + "gpt-4.1-mini": "openai", + "gpt-4.1-nano": "openai", + "o4-mini": "openai", + //prettier-ignore + "o3": "openai", + "o3-mini": "openai", + //prettier-ignore + "o1": "openai", + "o1-mini": "openai", + "gpt-4o": "openai", + "gpt-4o-mini": "openai", + "gpt-4o-2024-08-06": "openai", + "gpt-4.5-preview": "openai", + "o1-preview": "openai", + "claude-3-5-sonnet-latest": "anthropic", + "claude-3-5-sonnet-20240620": "anthropic", + "claude-3-5-sonnet-20241022": "anthropic", + "claude-3-7-sonnet-20250219": "anthropic", + "claude-3-7-sonnet-latest": "anthropic", + "cerebras-llama-3.3-70b": "cerebras", + "cerebras-llama-3.1-8b": "cerebras", + "groq-llama-3.3-70b-versatile": "groq", + "groq-llama-3.3-70b-specdec": "groq", + "moonshotai/kimi-k2-instruct": "groq", + "gemini-1.5-flash": "google", + "gemini-1.5-pro": "google", + "gemini-1.5-flash-8b": "google", + "gemini-2.0-flash-lite": "google", + "gemini-2.0-flash": "google", + "gemini-2.5-flash-preview-04-17": "google", + "gemini-2.5-pro-preview-03-25": "google" +}; +function getAISDKLanguageModel(subProvider, subModelName, apiKey) { + if (apiKey) { + const creator = AISDKProvidersWithAPIKey[subProvider]; + if (!creator) { + throw new UnsupportedAISDKModelProviderError( + subProvider, + Object.keys(AISDKProvidersWithAPIKey) + ); + } + const provider = creator({ apiKey }); + return provider(subModelName); + } else { + const provider = AISDKProviders[subProvider]; + if (!provider) { + throw new UnsupportedAISDKModelProviderError( + subProvider, + Object.keys(AISDKProviders) + ); + } + return provider(subModelName); + } +} +var LLMProvider = class { + constructor(logger, enableCaching) { + this.logger = logger; + this.enableCaching = enableCaching; + this.cache = enableCaching ? new LLMCache(logger) : void 0; + } + cleanRequestCache(requestId) { + if (!this.enableCaching) { + return; + } + this.logger({ + category: "llm_cache", + message: "cleaning up cache", + level: 1, + auxiliary: { + requestId: { + value: requestId, + type: "string" + } + } + }); + this.cache.deleteCacheForRequestId(requestId); + } + getClient(modelName, clientOptions) { + if (modelName.includes("/")) { + const firstSlashIndex = modelName.indexOf("/"); + const subProvider = modelName.substring(0, firstSlashIndex); + const subModelName = modelName.substring(firstSlashIndex + 1); + const languageModel = getAISDKLanguageModel( + subProvider, + subModelName, + clientOptions == null ? void 0 : clientOptions.apiKey + ); + return new AISdkClient({ + model: languageModel, + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache + }); + } + const provider = modelToProviderMap[modelName]; + if (!provider) { + throw new UnsupportedModelError(Object.keys(modelToProviderMap)); + } + const availableModel = modelName; + switch (provider) { + case "openai": + return new OpenAIClient({ + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache, + modelName: availableModel, + clientOptions + }); + case "anthropic": + return new AnthropicClient({ + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache, + modelName: availableModel, + clientOptions + }); + case "cerebras": + return new CerebrasClient({ + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache, + modelName: availableModel, + clientOptions + }); + case "groq": + return new GroqClient({ + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache, + modelName: availableModel, + clientOptions + }); + case "google": + return new GoogleClient({ + logger: this.logger, + enableCaching: this.enableCaching, + cache: this.cache, + modelName: availableModel, + clientOptions + }); + default: + throw new UnsupportedModelProviderError([ + ...new Set(Object.values(modelToProviderMap)) + ]); + } + } + static getModelProvider(modelName) { + if (modelName.includes("/")) { + const firstSlashIndex = modelName.indexOf("/"); + const subProvider = modelName.substring(0, firstSlashIndex); + if (AISDKProviders[subProvider]) { + return "aisdk"; + } + } + const provider = modelToProviderMap[modelName]; + return provider; + } +}; + +// lib/agent/OpenAICUAClient.ts +var import_openai5 = __toESM(require("openai")); + +// lib/agent/AgentClient.ts +var AgentClient = class { + constructor(type, modelName, userProvidedInstructions) { + this.type = type; + this.modelName = modelName; + this.userProvidedInstructions = userProvidedInstructions; + this.clientOptions = {}; + } +}; + +// lib/agent/utils/imageCompression.ts +function findAnthropicItemsWithImages(items) { + const itemsWithImages = []; + items.forEach((item, index) => { + let hasImage = false; + if (Array.isArray(item.content)) { + hasImage = item.content.some( + (contentItem) => contentItem.type === "tool_result" && "content" in contentItem && Array.isArray(contentItem.content) && contentItem.content.some( + (nestedItem) => nestedItem.type === "image" + ) + ); + } + if (hasImage) { + itemsWithImages.push(index); + } + }); + return itemsWithImages; +} +function findOpenAIItemsWithImages(items) { + const itemsWithImages = []; + items.forEach((item, index) => { + let hasImage = false; + if ("type" in item && item.type === "computer_call_output" && "output" in item) { + const output = item.output; + hasImage = (output == null ? void 0 : output.type) === "input_image" && !!(output == null ? void 0 : output.image_url); + } + if (hasImage) { + itemsWithImages.push(index); + } + }); + return itemsWithImages; +} +function findGoogleItemsWithImages(items) { + const itemsWithImages = []; + items.forEach((item, index) => { + let hasImage = false; + if (item.parts && Array.isArray(item.parts)) { + hasImage = item.parts.some((part) => { + var _a15, _b, _c, _d; + if ((_b = (_a15 = part.functionResponse) == null ? void 0 : _a15.response) == null ? void 0 : _b.data) { + const data = part.functionResponse.response.data; + return data.some( + (dataItem) => { + var _a16, _b2; + return (_b2 = (_a16 = dataItem.inlineData) == null ? void 0 : _a16.mimeType) == null ? void 0 : _b2.startsWith("image/"); + } + ); + } + return (_d = (_c = part.inlineData) == null ? void 0 : _c.mimeType) == null ? void 0 : _d.startsWith("image/"); + }); + } + if (hasImage) { + itemsWithImages.push(index); + } + }); + return itemsWithImages; +} +function compressAnthropicConversationImages(items, keepMostRecentCount = 2) { + const itemsWithImages = findAnthropicItemsWithImages(items); + items.forEach((item, index) => { + const imageIndex = itemsWithImages.indexOf(index); + const shouldCompress = imageIndex >= 0 && imageIndex < itemsWithImages.length - keepMostRecentCount; + if (shouldCompress) { + if (Array.isArray(item.content)) { + item.content = item.content.map( + (contentItem) => { + if (contentItem.type === "tool_result" && "content" in contentItem && Array.isArray(contentItem.content) && contentItem.content.some( + (nestedItem) => nestedItem.type === "image" + )) { + return __spreadProps(__spreadValues({}, contentItem), { + content: "screenshot taken" + }); + } + return contentItem; + } + ); + } + } + }); + return { + items + }; +} +function compressOpenAIConversationImages(items, keepMostRecentCount = 2) { + const itemsWithImages = findOpenAIItemsWithImages(items); + items.forEach((item, index) => { + const imageIndex = itemsWithImages.indexOf(index); + const shouldCompress = imageIndex >= 0 && imageIndex < itemsWithImages.length - keepMostRecentCount; + if (shouldCompress) { + if ("type" in item && item.type === "computer_call_output" && "output" in item) { + const output = item.output; + if ((output == null ? void 0 : output.type) === "input_image") { + item.output = "screenshot taken"; + } + } + } + }); + return { + items + }; +} +function compressGoogleConversationImages(items, keepMostRecentCount = 2) { + const itemsWithImages = findGoogleItemsWithImages(items); + items.forEach((item, index) => { + const imageIndex = itemsWithImages.indexOf(index); + const shouldCompress = imageIndex >= 0 && imageIndex < itemsWithImages.length - keepMostRecentCount; + if (shouldCompress && item.parts && Array.isArray(item.parts)) { + item.parts = item.parts.map((part) => { + var _a15, _b, _c, _d; + if ((_b = (_a15 = part.functionResponse) == null ? void 0 : _a15.response) == null ? void 0 : _b.data) { + const data = part.functionResponse.response.data; + const hasImage = data.some( + (dataItem) => { + var _a16, _b2; + return (_b2 = (_a16 = dataItem.inlineData) == null ? void 0 : _a16.mimeType) == null ? void 0 : _b2.startsWith("image/"); + } + ); + if (hasImage) { + return __spreadProps(__spreadValues({}, part), { + functionResponse: __spreadProps(__spreadValues({}, part.functionResponse), { + data: [], + response: __spreadProps(__spreadValues({}, part.functionResponse.response), { + compressed: "screenshot taken" + }) + }) + }); + } + } + if ((_d = (_c = part.inlineData) == null ? void 0 : _c.mimeType) == null ? void 0 : _d.startsWith("image/")) { + return { + text: "screenshot taken" + }; + } + return part; + }); + } + }); + return { + items + }; +} + +// lib/agent/utils/cuaKeyMapping.ts +var KEY_MAP = { + ENTER: "Enter", + RETURN: "Enter", + ESCAPE: "Escape", + ESC: "Escape", + BACKSPACE: "Backspace", + TAB: "Tab", + SPACE: " ", + DELETE: "Delete", + DEL: "Delete", + ARROWUP: "ArrowUp", + ARROWDOWN: "ArrowDown", + ARROWLEFT: "ArrowLeft", + ARROWRIGHT: "ArrowRight", + ARROW_UP: "ArrowUp", + ARROW_DOWN: "ArrowDown", + ARROW_LEFT: "ArrowLeft", + ARROW_RIGHT: "ArrowRight", + UP: "ArrowUp", + DOWN: "ArrowDown", + LEFT: "ArrowLeft", + RIGHT: "ArrowRight", + SHIFT: "Shift", + CONTROL: "Control", + CTRL: "Control", + ALT: "Alt", + OPTION: "Alt", + // macOS alternative name + META: "Meta", + COMMAND: "Meta", + // macOS + CMD: "Meta", + // macOS shorthand + SUPER: "Meta", + // Linux + WINDOWS: "Meta", + // Windows + WIN: "Meta", + // Windows shorthand + HOME: "Home", + END: "End", + PAGEUP: "PageUp", + PAGEDOWN: "PageDown", + PAGE_UP: "PageUp", + PAGE_DOWN: "PageDown", + PGUP: "PageUp", + PGDN: "PageDown" +}; +function mapKeyToPlaywright(key) { + if (!key) return key; + const upperKey = key.toUpperCase(); + return KEY_MAP[upperKey] || key; +} + +// lib/agent/OpenAICUAClient.ts +var OpenAICUAClient = class extends AgentClient { + // "browser", "mac", "windows", or "ubuntu" + constructor(type, modelName, userProvidedInstructions, clientOptions) { + super(type, modelName, userProvidedInstructions); + this.currentViewport = { width: 1288, height: 711 }; + this.reasoningItems = /* @__PURE__ */ new Map(); + this.environment = "browser"; + this.apiKey = (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.OPENAI_API_KEY || ""; + this.organization = (clientOptions == null ? void 0 : clientOptions.organization) || process.env.OPENAI_ORG; + if ((clientOptions == null ? void 0 : clientOptions.environment) && typeof clientOptions.environment === "string") { + this.environment = clientOptions.environment; + } + this.clientOptions = { + apiKey: this.apiKey + }; + this.client = new import_openai5.default(this.clientOptions); + } + setViewport(width, height) { + this.currentViewport = { width, height }; + } + setCurrentUrl(url) { + this.currentUrl = url; + } + setScreenshotProvider(provider) { + this.screenshotProvider = provider; + } + setActionHandler(handler) { + this.actionHandler = handler; + } + /** + * Execute a task with the OpenAI CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions) { + return __async(this, null, function* () { + const { options, logger } = executionOptions; + const { instruction } = options; + const maxSteps = options.maxSteps || 10; + let currentStep = 0; + let completed = false; + const actions = []; + const messageList = []; + let finalMessage = ""; + this.reasoningItems.clear(); + let inputItems = this.createInitialInputItems(instruction); + let previousResponseId = void 0; + let totalInputTokens = 0; + let totalOutputTokens = 0; + let totalInferenceTime = 0; + try { + while (!completed && currentStep < maxSteps) { + logger({ + category: "agent", + message: `Executing step ${currentStep + 1}/${maxSteps}`, + level: 2 + }); + const result = yield this.executeStep( + inputItems, + previousResponseId, + logger + ); + totalInputTokens += result.usage.input_tokens; + totalOutputTokens += result.usage.output_tokens; + totalInferenceTime += result.usage.inference_time_ms; + actions.push(...result.actions); + completed = result.completed; + previousResponseId = result.responseId; + if (!completed) { + inputItems = result.nextInputItems; + } + if (result.message) { + messageList.push(result.message); + finalMessage = result.message; + } + currentStep++; + } + return { + success: completed, + actions, + message: finalMessage, + completed, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing agent task: ${errorMessage}`, + level: 0 + }); + return { + success: false, + actions, + message: `Failed to execute task: ${errorMessage}`, + completed: false, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } + }); + } + /** + * Execute a single step of the agent + * This coordinates the flow: Request → Get Action → Execute Action + */ + executeStep(inputItems, previousResponseId, logger) { + return __async(this, null, function* () { + try { + const compressedResult = compressOpenAIConversationImages(inputItems, 2); + const compressedInputItems = compressedResult.items; + const result = yield this.getAction( + compressedInputItems, + previousResponseId + ); + const output = result.output; + const responseId = result.responseId; + const usage = { + input_tokens: result.usage.input_tokens, + output_tokens: result.usage.output_tokens, + inference_time_ms: result.usage.inference_time_ms + }; + for (const item of output) { + if (item.type === "reasoning") { + this.reasoningItems.set(item.id, item); + logger({ + category: "agent", + message: `Reasoning: ${String(item.content || "")}`, + level: 1 + }); + } + } + const stepActions = []; + for (const item of output) { + if (item.type === "computer_call" && this.isComputerCallItem(item)) { + logger({ + category: "agent", + message: `Found computer_call: ${item.action.type}, call_id: ${item.call_id}`, + level: 2 + }); + const action = this.convertComputerCallToAction(item); + if (action) { + stepActions.push(action); + logger({ + category: "agent", + message: `Converted computer_call to action: ${action.type}`, + level: 2 + }); + } + } else if (item.type === "function_call" && this.isFunctionCallItem(item)) { + logger({ + category: "agent", + message: `Found function_call: ${item.name}, call_id: ${item.call_id}`, + level: 2 + }); + const action = this.convertFunctionCallToAction(item); + if (action) { + stepActions.push(action); + logger({ + category: "agent", + message: `Converted function_call to action: ${action.type}`, + level: 2 + }); + } + } + } + let message = ""; + for (const item of output) { + if (item.type === "message") { + logger({ + category: "agent", + message: `Found message block`, + level: 2 + }); + if (item.content && Array.isArray(item.content)) { + for (const content of item.content) { + if (content.type === "output_text" && content.text) { + message += content.text + "\n"; + logger({ + category: "agent", + message: `Message text: ${String(content.text || "")}`, + level: 1 + }); + } + } + } + } + } + const nextInputItems = yield this.takeAction(output, logger); + const completed = output.length === 0 || output.every( + (item) => item.type === "message" || item.type === "reasoning" + ); + return { + actions: stepActions, + message: message.trim(), + completed, + nextInputItems, + responseId, + usage + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing step: ${errorMessage}`, + level: 0 + }); + throw error; + } + }); + } + isComputerCallItem(item) { + return item.type === "computer_call" && "call_id" in item && "action" in item && typeof item.action === "object"; + } + isFunctionCallItem(item) { + return item.type === "function_call" && "call_id" in item && "name" in item && "arguments" in item; + } + createInitialInputItems(instruction) { + return [ + { + role: "system", + content: this.userProvidedInstructions + }, + { + role: "user", + content: instruction + } + ]; + } + getAction(inputItems, previousResponseId) { + return __async(this, null, function* () { + try { + const requestParams = { + model: this.modelName, + tools: [ + { + type: "computer_use_preview", + display_width: this.currentViewport.width, + display_height: this.currentViewport.height, + environment: this.environment + } + ], + input: inputItems, + truncation: "auto" + }; + if (previousResponseId) { + requestParams.previous_response_id = previousResponseId; + } + const startTime = Date.now(); + const response = yield this.client.responses.create(requestParams); + const endTime = Date.now(); + const elapsedMs = endTime - startTime; + const usage = { + input_tokens: response.usage.input_tokens, + output_tokens: response.usage.output_tokens, + inference_time_ms: elapsedMs + }; + this.lastResponseId = response.id; + return { + output: response.output, + responseId: response.id, + usage + }; + } catch (error) { + console.error("Error getting action from OpenAI:", error); + throw error; + } + }); + } + takeAction(output, logger) { + return __async(this, null, function* () { + const nextInputItems = []; + for (const item of output) { + if (item.type === "computer_call" && this.isComputerCallItem(item)) { + try { + const action = this.convertComputerCallToAction(item); + if (action && this.actionHandler) { + logger({ + category: "agent", + message: `Executing computer action: ${action.type}`, + level: 1 + }); + yield this.actionHandler(action); + } + const screenshot = yield this.captureScreenshot(); + const outputItem = { + type: "computer_call_output", + call_id: item.call_id, + output: { + type: "input_image", + image_url: screenshot + } + }; + logger({ + category: "agent", + message: `Added computer_call_output for call_id: ${item.call_id}`, + level: 2 + }); + if (this.currentUrl) { + const computerCallOutput = outputItem; + computerCallOutput.output.current_url = this.currentUrl; + } + if (item.pending_safety_checks && item.pending_safety_checks.length > 0) { + const computerCallOutput = outputItem; + computerCallOutput.acknowledged_safety_checks = item.pending_safety_checks; + } + nextInputItems.push(outputItem); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing computer call: ${errorMessage}`, + level: 0 + }); + try { + const screenshot = yield this.captureScreenshot(); + const errorOutputItem = { + type: "computer_call_output", + call_id: item.call_id, + output: { + type: "input_image", + image_url: screenshot, + error: errorMessage + } + }; + if (this.currentUrl) { + const computerCallOutput = errorOutputItem; + computerCallOutput.output.current_url = this.currentUrl; + } + if (item.pending_safety_checks && item.pending_safety_checks.length > 0) { + const computerCallOutput = errorOutputItem; + computerCallOutput.acknowledged_safety_checks = item.pending_safety_checks; + } + nextInputItems.push(errorOutputItem); + } catch (screenshotError) { + logger({ + category: "agent", + message: `Error capturing screenshot: ${String(screenshotError)}`, + level: 0 + }); + nextInputItems.push({ + type: "computer_call_output", + call_id: item.call_id, + output: `Error: ${errorMessage}` + }); + } + } + } else if (item.type === "function_call" && this.isFunctionCallItem(item)) { + try { + const action = this.convertFunctionCallToAction(item); + if (action && this.actionHandler) { + yield this.actionHandler(action); + } + nextInputItems.push({ + type: "function_call_output", + call_id: item.call_id, + output: "success" + }); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing function call: ${errorMessage}`, + level: 0 + }); + nextInputItems.push({ + type: "function_call_output", + call_id: item.call_id, + output: `Error: ${errorMessage}` + }); + } + } + } + return nextInputItems; + }); + } + convertComputerCallToAction(call) { + const { action } = call; + if (action.type === "keypress") { + action.keys = action.keys.map( + (key) => mapKeyToPlaywright(key) + ); + } + return __spreadValues({ + type: action.type + }, action); + } + convertFunctionCallToAction(call) { + try { + const args = JSON.parse(call.arguments); + return { + type: call.name, + params: args + }; + } catch (error) { + console.error("Error parsing function call arguments:", error); + return null; + } + } + captureScreenshot(options) { + return __async(this, null, function* () { + if (options == null ? void 0 : options.base64Image) { + return `data:image/png;base64,${options.base64Image}`; + } + if (this.screenshotProvider) { + try { + const base64Image = yield this.screenshotProvider(); + return `data:image/png;base64,${base64Image}`; + } catch (error) { + console.error("Error capturing screenshot:", error); + throw error; + } + } + throw new AgentScreenshotProviderError( + "`screenshotProvider` has not been set. Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image" + ); + }); + } +}; + +// lib/agent/AnthropicCUAClient.ts +var import_sdk2 = __toESM(require("@anthropic-ai/sdk")); +var AnthropicCUAClient = class extends AgentClient { + constructor(type, modelName, userProvidedInstructions, clientOptions, experimental) { + super(type, modelName, userProvidedInstructions); + this.currentViewport = { width: 1288, height: 711 }; + this.thinkingBudget = null; + this.experimental = false; + this.apiKey = (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.ANTHROPIC_API_KEY || ""; + this.baseURL = (clientOptions == null ? void 0 : clientOptions.baseURL) || void 0; + if ((clientOptions == null ? void 0 : clientOptions.thinkingBudget) && typeof clientOptions.thinkingBudget === "number") { + this.thinkingBudget = clientOptions.thinkingBudget; + } + this.experimental = experimental || false; + this.clientOptions = { + apiKey: this.apiKey + }; + if (this.baseURL) { + this.clientOptions.baseUrl = this.baseURL; + } + this.client = new import_sdk2.default(this.clientOptions); + } + setViewport(width, height) { + this.currentViewport = { width, height }; + } + setCurrentUrl(url) { + this.currentUrl = url; + } + setScreenshotProvider(provider) { + this.screenshotProvider = provider; + } + setActionHandler(handler) { + this.actionHandler = handler; + } + /** + * Execute a task with the Anthropic CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions) { + return __async(this, null, function* () { + const { options, logger } = executionOptions; + const { instruction } = options; + const maxSteps = options.maxSteps || 10; + let currentStep = 0; + let completed = false; + const actions = []; + const messageList = []; + let finalMessage = ""; + let inputItems = this.createInitialInputItems(instruction); + logger({ + category: "agent", + message: `Starting Anthropic agent execution with instruction: ${instruction}`, + level: 1 + }); + let totalInputTokens = 0; + let totalOutputTokens = 0; + let totalInferenceTime = 0; + try { + while (!completed && currentStep < maxSteps) { + logger({ + category: "agent", + message: `Executing step ${currentStep + 1}/${maxSteps}`, + level: 2 + }); + const result = yield this.executeStep(inputItems, logger); + totalInputTokens += result.usage.input_tokens; + totalOutputTokens += result.usage.output_tokens; + totalInferenceTime += result.usage.inference_time_ms; + if (result.actions.length > 0) { + logger({ + category: "agent", + message: `Step ${currentStep + 1} performed ${result.actions.length} actions`, + level: 2 + }); + actions.push(...result.actions); + } + completed = result.completed; + if (!completed) { + inputItems = result.nextInputItems; + } + if (result.message) { + messageList.push(result.message); + finalMessage = result.message; + } + currentStep++; + } + logger({ + category: "agent", + message: `Anthropic agent execution completed: ${completed}, with ${actions.length} total actions performed`, + level: 1 + }); + return { + success: completed, + actions, + message: finalMessage, + completed, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing agent task: ${errorMessage}`, + level: 0 + }); + return { + success: false, + actions, + message: `Failed to execute task: ${errorMessage}`, + completed: false, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } + }); + } + executeStep(inputItems, logger) { + return __async(this, null, function* () { + try { + const result = yield this.getAction(inputItems); + const content = result.content; + const usage = { + input_tokens: result.usage.input_tokens, + output_tokens: result.usage.output_tokens, + inference_time_ms: result.usage.inference_time_ms + }; + logger({ + category: "agent", + message: `Received response with ${content.length} content blocks`, + level: 2 + }); + const stepActions = []; + const toolUseItems = []; + let message = ""; + for (const block of content) { + console.log("Processing block:", JSON.stringify(block, null, 2)); + logger({ + category: "agent", + message: `Processing block type: ${block.type}, id: ${block.id || "unknown"}`, + level: 2 + }); + if (block.type === "tool_use") { + logger({ + category: "agent", + message: `Found tool_use block: ${JSON.stringify(block)}`, + level: 2 + }); + const toolUseItem = block; + toolUseItems.push(toolUseItem); + logger({ + category: "agent", + message: `Added tool_use item: ${toolUseItem.name}, action: ${JSON.stringify(toolUseItem.input)}`, + level: 2 + }); + const action = this.convertToolUseToAction(toolUseItem); + if (action) { + logger({ + category: "agent", + message: `Created action from tool_use: ${toolUseItem.name}, action: ${action.type}`, + level: 2 + }); + stepActions.push(action); + } + } else if (block.type === "text") { + const textBlock = block; + message += textBlock.text + "\n"; + logger({ + category: "agent", + message: `Found text block: ${textBlock.text}`, + level: 2 + }); + } else { + logger({ + category: "agent", + message: `Found unknown block type: ${block.type}`, + level: 2 + }); + } + } + if (this.actionHandler && stepActions.length > 0) { + for (const action of stepActions) { + try { + logger({ + category: "agent", + message: `Executing action: ${action.type}`, + level: 1 + }); + yield this.actionHandler(action); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing action ${action.type}: ${errorMessage}`, + level: 0 + }); + } + } + } + const assistantMessage = { + role: "assistant", + content + }; + const nextInputItems = [...inputItems]; + if (this.experimental) { + compressAnthropicConversationImages(nextInputItems); + } + nextInputItems.push(assistantMessage); + if (toolUseItems.length > 0) { + const toolResults = yield this.takeAction(toolUseItems, logger); + if (toolResults.length > 0) { + const userToolResultsMessage = { + role: "user", + content: toolResults + }; + nextInputItems.push(userToolResultsMessage); + } + } + const completed = toolUseItems.length === 0; + logger({ + category: "agent", + message: `Step processed ${toolUseItems.length} tool use items, completed: ${completed}`, + level: 2 + }); + return { + actions: stepActions, + message: message.trim(), + completed, + nextInputItems, + usage + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing step: ${errorMessage}`, + level: 0 + }); + throw error; + } + }); + } + createInitialInputItems(instruction) { + return [ + { + role: "system", + content: this.userProvidedInstructions + }, + { + role: "user", + content: instruction + } + ]; + } + getAction(inputItems) { + return __async(this, null, function* () { + try { + const messages = []; + for (const item of inputItems) { + if ("role" in item) { + if (item.role !== "system") { + messages.push(item); + } + } + } + const thinking = this.thinkingBudget ? { type: "enabled", budget_tokens: this.thinkingBudget } : void 0; + const requestParams = { + model: this.modelName, + max_tokens: 4096, + messages, + tools: [ + { + type: "computer_20250124", + // Use the latest version for Claude 3.7 Sonnet + name: "computer", + display_width_px: this.currentViewport.width, + display_height_px: this.currentViewport.height, + display_number: 1 + } + ], + betas: ["computer-use-2025-01-24"] + }; + if (this.userProvidedInstructions) { + requestParams.system = this.userProvidedInstructions; + } + if (thinking) { + requestParams.thinking = thinking; + } + if (messages.length > 0) { + const firstMessage = messages[0]; + const contentPreview = typeof firstMessage.content === "string" ? firstMessage.content.substring(0, 50) : "complex content"; + console.log( + `Sending request to Anthropic with ${messages.length} messages and ${messages.length > 0 ? `first message role: ${messages[0].role}, content: ${contentPreview}...` : "no messages"}` + ); + } + const startTime = Date.now(); + const response = yield this.client.beta.messages.create(requestParams); + const endTime = Date.now(); + const elapsedMs = endTime - startTime; + const usage = { + input_tokens: response.usage.input_tokens, + output_tokens: response.usage.output_tokens, + inference_time_ms: elapsedMs + }; + this.lastMessageId = response.id; + return { + // Cast the response content to our internal type + content: response.content, + id: response.id, + usage + }; + } catch (error) { + console.error("Error getting action from Anthropic:", error); + throw error; + } + }); + } + takeAction(toolUseItems, logger) { + return __async(this, null, function* () { + const nextInputItems = []; + logger({ + category: "agent", + message: `Taking action on ${toolUseItems.length} tool use items`, + level: 2 + }); + for (const item of toolUseItems) { + try { + logger({ + category: "agent", + message: `Processing tool use: ${item.name}, id: ${item.id}, action: ${JSON.stringify(item.input)}`, + level: 2 + }); + if (item.name === "computer") { + const action = item.input.action; + logger({ + category: "agent", + message: `Computer action type: ${action}`, + level: 2 + }); + const screenshot = yield this.captureScreenshot(); + logger({ + category: "agent", + message: `Screenshot captured, length: ${screenshot.length}`, + level: 2 + }); + const imageContent = [ + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: screenshot.replace(/^data:image\/png;base64,/, "") + } + } + ]; + if (this.currentUrl) { + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: [ + ...imageContent, + { + type: "text", + text: `Current URL: ${this.currentUrl}` + } + ] + }); + } else { + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: imageContent + }); + } + logger({ + category: "agent", + message: `Added computer tool result for tool_use_id: ${item.id}`, + level: 2 + }); + } else { + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: "Tool executed successfully" + }); + logger({ + category: "agent", + message: `Added generic tool result for tool ${item.name}, tool_use_id: ${item.id}`, + level: 2 + }); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing tool use: ${errorMessage}`, + level: 0 + }); + try { + if (item.name === "computer") { + const screenshot = yield this.captureScreenshot(); + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: [ + { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: screenshot.replace(/^data:image\/png;base64,/, "") + } + }, + { + type: "text", + text: `Error: ${errorMessage}` + } + ] + }); + logger({ + category: "agent", + message: `Added error tool result with screenshot for tool_use_id: ${item.id}`, + level: 1 + }); + } else { + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: `Error: ${errorMessage}` + }); + logger({ + category: "agent", + message: `Added error tool result for tool_use_id: ${item.id}`, + level: 1 + }); + } + } catch (screenshotError) { + logger({ + category: "agent", + message: `Error capturing screenshot: ${String(screenshotError)}`, + level: 0 + }); + nextInputItems.push({ + type: "tool_result", + tool_use_id: item.id, + content: `Error: ${errorMessage}` + }); + logger({ + category: "agent", + message: `Added text error tool result for tool_use_id: ${item.id}`, + level: 1 + }); + } + } + } + logger({ + category: "agent", + message: `Prepared ${nextInputItems.length} input items for next request`, + level: 2 + }); + return nextInputItems; + }); + } + convertToolUseToAction(item) { + try { + const { name: name14, input } = item; + if (name14 === "computer") { + const action = input.action; + if (!action) { + console.warn("Missing action in tool use item:", item); + return null; + } + if (action === "screenshot") { + return __spreadValues({ + type: "screenshot" + }, input); + } else if (action === "click") { + return __spreadValues({ + type: "click", + x: input.x, + y: input.y, + button: input.button || "left" + }, input); + } else if (action === "type") { + return __spreadValues({ + type: "type", + text: input.text + }, input); + } else if (action === "keypress" || action === "key") { + const key = action === "key" ? input.text : input.keys; + const keys = key.split("+"); + return __spreadValues({ + type: "keypress", + keys: keys.map((key2) => mapKeyToPlaywright(key2)) + }, input); + } else if (action === "double_click" || action === "doubleClick") { + return __spreadValues({ + type: action, + x: input.x, + y: input.y + }, input); + } else if (action === "triple_click" || action === "tripleClick") { + return __spreadValues({ + type: action, + x: input.x, + y: input.y + }, input); + } else if (action === "scroll") { + const x = input.x || (input.coordinate ? input.coordinate[0] : 0); + const y = input.y || (input.coordinate ? input.coordinate[1] : 0); + let scroll_x = 0; + let scroll_y = 0; + const scrollAmount = input.scroll_amount || 5; + const scrollMultiplier = 100; + if (input.scroll_direction) { + const direction = input.scroll_direction; + if (direction === "down") { + scroll_y = scrollAmount * scrollMultiplier; + } else if (direction === "up") { + scroll_y = -scrollAmount * scrollMultiplier; + } else if (direction === "right") { + scroll_x = scrollAmount * scrollMultiplier; + } else if (direction === "left") { + scroll_x = -scrollAmount * scrollMultiplier; + } + } else { + scroll_x = input.scroll_x || 0; + scroll_y = input.scroll_y || 0; + } + return __spreadValues({ + type: "scroll", + x, + y, + scroll_x, + scroll_y + }, input); + } else if (action === "move") { + const coordinates = input.coordinate; + const x = coordinates ? coordinates[0] : input.x || 0; + const y = coordinates ? coordinates[1] : input.y || 0; + return __spreadValues({ + type: "move", + x, + y + }, input); + } else if (action === "drag" || action === "left_click_drag") { + const path4 = input.path || (input.coordinate ? [ + { + x: input.start_coordinate[0], + y: input.start_coordinate[1] + }, + { + x: input.coordinate[0], + y: input.coordinate[1] + } + ] : []); + return __spreadValues({ + type: "drag", + path: path4 + }, input); + } else if (action === "wait") { + return __spreadValues({ + type: "wait" + }, input); + } else if (action === "left_click") { + const coordinates = input.coordinate; + const x = coordinates ? coordinates[0] : input.x || 0; + const y = coordinates ? coordinates[1] : input.y || 0; + return __spreadValues({ + type: "click", + x, + y, + button: "left" + }, input); + } else { + console.log(`Using default action mapping for ${action}`); + return __spreadValues({ + type: action + }, input); + } + } else if (name14 === "str_replace_editor" || name14 === "bash") { + return { + type: name14, + params: input + }; + } + console.warn(`Unknown tool name: ${name14}`); + return null; + } catch (error) { + console.error("Error converting tool use to action:", error); + return null; + } + } + captureScreenshot(options) { + return __async(this, null, function* () { + if (options == null ? void 0 : options.base64Image) { + return `data:image/png;base64,${options.base64Image}`; + } + if (this.screenshotProvider) { + try { + const base64Image = yield this.screenshotProvider(); + return `data:image/png;base64,${base64Image}`; + } catch (error) { + console.error("Error capturing screenshot:", error); + throw error; + } + } + throw new AgentScreenshotProviderError( + "`screenshotProvider` has not been set. Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image" + ); + }); + } +}; + +// lib/agent/GoogleCUAClient.ts +var import_genai3 = require("@google/genai"); +var GoogleCUAClient = class extends AgentClient { + constructor(type, modelName, userProvidedInstructions, clientOptions) { + super(type, modelName, userProvidedInstructions); + this.currentViewport = { width: 1288, height: 711 }; + this.history = []; + this.environment = "ENVIRONMENT_BROWSER"; + this.apiKey = (clientOptions == null ? void 0 : clientOptions.apiKey) || process.env.GEMINI_API_KEY || ""; + this.client = new import_genai3.GoogleGenAI({ + apiKey: this.apiKey + }); + if ((clientOptions == null ? void 0 : clientOptions.environment) && typeof clientOptions.environment === "string") { + this.environment = clientOptions.environment; + } + this.generateContentConfig = { + temperature: 1, + topP: 0.95, + topK: 40, + maxOutputTokens: 8192, + // systemInstruction: this.userProvidedInstructions + // ? { parts: [{ text: this.userProvidedInstructions }] } + // : { parts: [{ text: buildGoogleCUASystemPrompt() }] }, + tools: [ + { + computerUse: { + environment: this.environment + } + } + ] + }; + this.clientOptions = { + apiKey: this.apiKey + }; + } + setViewport(width, height) { + this.currentViewport = { width, height }; + } + setCurrentUrl(url) { + this.currentUrl = url; + } + setScreenshotProvider(provider) { + this.screenshotProvider = provider; + } + setActionHandler(handler) { + this.actionHandler = handler; + } + /** + * Execute a task with the Google CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions) { + return __async(this, null, function* () { + const { options, logger } = executionOptions; + const { instruction } = options; + const maxSteps = options.maxSteps || 10; + let currentStep = 0; + let completed = false; + const actions = []; + const messageList = []; + let finalMessage = ""; + this.history = []; + yield this.initializeHistory(instruction); + let totalInputTokens = 0; + let totalOutputTokens = 0; + let totalInferenceTime = 0; + try { + while (!completed && currentStep < maxSteps) { + logger({ + category: "agent", + message: `Executing step ${currentStep + 1}/${maxSteps}`, + level: 2 + }); + const result = yield this.executeStep(logger); + totalInputTokens += result.usage.input_tokens; + totalOutputTokens += result.usage.output_tokens; + totalInferenceTime += result.usage.inference_time_ms; + actions.push(...result.actions); + completed = result.completed; + if (result.message) { + messageList.push(result.message); + finalMessage = result.message; + } + currentStep++; + } + return { + success: completed, + actions, + message: finalMessage, + completed, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing agent task: ${errorMessage}`, + level: 0 + }); + return { + success: false, + actions, + message: `Failed to execute task: ${errorMessage}`, + completed: false, + usage: { + input_tokens: totalInputTokens, + output_tokens: totalOutputTokens, + inference_time_ms: totalInferenceTime + } + }; + } + }); + } + /** + * Initialize conversation history with the initial instruction + */ + initializeHistory(instruction) { + return __async(this, null, function* () { + const parts = [{ text: instruction }]; + this.history = [ + { + role: "user", + parts: [ + { + text: "System prompt: " + buildGoogleCUASystemPrompt().content + } + ] + }, + { + role: "user", + parts + } + ]; + }); + } + /** + * Execute a single step of the agent + */ + executeStep(logger) { + return __async(this, null, function* () { + var _a15, _b; + try { + const startTime = Date.now(); + const compressedResult = compressGoogleConversationImages( + this.history, + 2 + ); + const compressedHistory = compressedResult.items; + const maxRetries = 5; + const baseDelayS = 1; + let lastError = null; + let response = null; + for (let attempt = 0; attempt < maxRetries; attempt++) { + try { + if (attempt > 0) { + const delay = baseDelayS * Math.pow(2, attempt) * 1e3; + logger({ + category: "agent", + message: `Generating content failed on attempt ${attempt + 1}. Retrying in ${delay / 1e3} seconds...`, + level: 2 + }); + yield new Promise((resolve2) => setTimeout(resolve2, delay)); + } + response = yield this.client.models.generateContent({ + model: this.modelName, + contents: compressedHistory, + config: this.generateContentConfig + }); + if (!response.candidates || response.candidates.length === 0) { + throw new Error("Response has no candidates!"); + } + break; + } catch (error) { + lastError = error instanceof Error ? error : new Error(String(error)); + logger({ + category: "agent", + message: `API call error: ${lastError.message}`, + level: 2 + }); + if (attempt === maxRetries - 1) { + logger({ + category: "agent", + message: `Generating content failed after ${maxRetries} attempts.`, + level: 0 + }); + throw lastError; + } + } + } + if (!response) { + throw lastError || new Error("Failed to get response after all retries"); + } + const endTime = Date.now(); + const elapsedMs = endTime - startTime; + const { usageMetadata } = response; + const result = yield this.processResponse(response, logger); + if (response.candidates && response.candidates[0]) { + const sanitizedContent = JSON.parse( + JSON.stringify(response.candidates[0].content) + ); + if (sanitizedContent.parts) { + for (const part of sanitizedContent.parts) { + if ((_a15 = part.functionCall) == null ? void 0 : _a15.args) { + if (typeof part.functionCall.args.x === "number" && part.functionCall.args.x > 999) { + part.functionCall.args.x = 999; + } + if (typeof part.functionCall.args.y === "number" && part.functionCall.args.y > 999) { + part.functionCall.args.y = 999; + } + } + } + } + this.history.push(sanitizedContent); + } + const functionResponses = []; + if (result.actions.length > 0) { + let hasError = false; + for (let i = 0; i < result.actions.length; i++) { + const action = result.actions[i]; + logger({ + category: "agent", + message: `Executing action ${i + 1}/${result.actions.length}: ${action.type}`, + level: 2 + }); + if (action.type === "function" && action.name === "open_web_browser") { + logger({ + category: "agent", + message: "Skipping open_web_browser action", + level: 2 + }); + } else if (this.actionHandler) { + try { + yield this.actionHandler(action); + if (i < result.actions.length - 1) { + const nextAction = result.actions[i + 1]; + const isTypingAction = action.type === "type" || nextAction.type === "type"; + const delay = isTypingAction ? 500 : 200; + yield new Promise((resolve2) => setTimeout(resolve2, delay)); + } + } catch (actionError) { + logger({ + category: "agent", + message: `Error executing action ${action.type}: ${actionError}`, + level: 0 + }); + hasError = true; + } + } + } + if (result.functionCalls.length > 0 || hasError) { + try { + logger({ + category: "agent", + message: `Taking screenshot after executing ${result.actions.length} actions${hasError ? " (with errors)" : ""}`, + level: 2 + }); + const screenshot = yield this.captureScreenshot(); + const base64Data = screenshot.replace( + /^data:image\/png;base64,/, + "" + ); + for (const functionCall of result.functionCalls) { + const functionResponsePart = { + functionResponse: { + name: functionCall.name, + response: __spreadValues({ + url: this.currentUrl || "" + }, ((_b = functionCall.args) == null ? void 0 : _b.safety_decision) ? { + safety_acknowledgement: "true" + } : {}), + parts: [ + { + inlineData: { + mimeType: "image/png", + data: base64Data + } + } + ] + } + }; + functionResponses.push(functionResponsePart); + } + } catch (error) { + logger({ + category: "agent", + message: `Error capturing screenshot: ${error}`, + level: 0 + }); + } + } + if (functionResponses.length > 0) { + logger({ + category: "agent", + message: `Adding ${functionResponses.length} function responses to history`, + level: 2 + }); + this.history.push({ + role: "user", + parts: functionResponses + }); + } + } + return { + actions: result.actions, + message: result.message, + completed: result.completed, + usage: { + input_tokens: (usageMetadata == null ? void 0 : usageMetadata.promptTokenCount) || 0, + output_tokens: (usageMetadata == null ? void 0 : usageMetadata.candidatesTokenCount) || 0, + inference_time_ms: elapsedMs + } + }; + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + logger({ + category: "agent", + message: `Error executing step: ${errorMessage}`, + level: 0 + }); + throw error; + } + }); + } + /** + * Process the response from Google's API + */ + processResponse(response, logger) { + return __async(this, null, function* () { + const actions = []; + let message = ""; + const functionCalls = []; + if (!response.candidates || response.candidates.length === 0) { + return { + actions: [], + message: "No candidates in response", + completed: true, + functionCalls: [] + }; + } + const candidate = response.candidates[0]; + logger({ + category: "agent", + message: `Raw response from Google: ${JSON.stringify(candidate.content, null, 2)}`, + level: 2 + }); + for (const part of candidate.content.parts) { + if (part.text) { + message += part.text + "\n"; + logger({ + category: "agent", + message: `Reasoning: ${part.text}`, + level: 1 + }); + } + if (part.functionCall) { + functionCalls.push(part.functionCall); + logger({ + category: "agent", + message: `Found function call: ${part.functionCall.name} with args: ${JSON.stringify(part.functionCall.args)}`, + level: 2 + }); + const action = this.convertFunctionCallToAction(part.functionCall); + if (action) { + if (part.functionCall.name === "type_text_at" && action.type === "type") { + logger({ + category: "agent", + message: `Adding action: ${JSON.stringify(action)}`, + level: 2 + }); + actions.push({ + type: "click", + x: action.x, + y: action.y, + button: "left" + }); + if (action.clearBeforeTyping) { + actions.push({ + type: "keypress", + keys: ["ControlOrMeta+A"] + }); + actions.push({ + type: "keypress", + keys: ["Backspace"] + }); + } + actions.push(action); + if (action.pressEnter) { + actions.push({ + type: "keypress", + keys: ["Enter"] + }); + } + } else { + actions.push(action); + } + } else { + logger({ + category: "agent", + message: `Warning: Could not convert function call ${part.functionCall.name} to action`, + level: 1 + }); + } + } + } + logger({ + category: "agent", + message: `Found ${functionCalls.length} function calls, converted to ${actions.length} actions`, + level: 2 + }); + const completed = functionCalls.length === 0 || candidate.finishReason && candidate.finishReason !== "STOP"; + return { + actions, + message: message.trim(), + completed, + functionCalls + }; + }); + } + /** + * Convert Google function call to Stagehand action + */ + convertFunctionCallToAction(functionCall) { + var _a15, _b; + const { name: name14, args } = functionCall; + if (!name14 || !args) { + return null; + } + switch (name14) { + case "open_web_browser": + return { + type: "function", + name: "open_web_browser", + arguments: null + }; + case "click_at": { + const { x, y } = this.normalizeCoordinates( + args.x, + args.y + ); + return { + type: "click", + x, + y, + button: args.button || "left" + }; + } + case "type_text_at": { + const { x, y } = this.normalizeCoordinates( + args.x, + args.y + ); + const pressEnter = (_a15 = args.press_enter) != null ? _a15 : false; + const clearBeforeTyping = (_b = args.clear_before_typing) != null ? _b : true; + return { + type: "type", + text: args.text, + x, + y, + pressEnter, + clearBeforeTyping + }; + } + case "key_combination": { + const keys = args.keys.split("+").map((key) => key.trim()).map((key) => mapKeyToPlaywright(key)); + return { + type: "keypress", + keys + }; + } + case "scroll_document": { + const direction = args.direction.toLowerCase(); + return { + type: "keypress", + keys: [direction === "up" ? "PageUp" : "PageDown"] + }; + } + case "scroll_at": { + const { x, y } = this.normalizeCoordinates( + args.x, + args.y + ); + const direction = (args.direction || "down").toLowerCase(); + const magnitude = typeof args.magnitude === "number" ? args.magnitude : 800; + let scroll_x = 0; + let scroll_y = 0; + if (direction === "up") { + scroll_y = -magnitude; + } else if (direction === "down") { + scroll_y = magnitude; + } else if (direction === "left") { + scroll_x = -magnitude; + } else if (direction === "right") { + scroll_x = magnitude; + } else { + scroll_y = magnitude; + } + return { + type: "scroll", + x, + y, + scroll_x, + scroll_y + }; + } + case "navigate": + return { + type: "function", + name: "goto", + arguments: { url: args.url } + }; + case "go_back": + return { + type: "function", + name: "back", + arguments: null + }; + case "go_forward": + return { + type: "function", + name: "forward", + arguments: null + }; + case "wait_5_seconds": + return { + type: "wait", + milliseconds: 5e3 + // Google CUA waits for 5 seconds + }; + case "hover_at": { + const { x, y } = this.normalizeCoordinates( + args.x, + args.y + ); + return { + type: "move", + x, + y + }; + } + case "search": + return { + type: "function", + name: "goto", + arguments: { url: "https://www.google.com" } + }; + case "drag_and_drop": { + const startPoint = this.normalizeCoordinates( + args.x, + args.y + ); + const endPoint = this.normalizeCoordinates( + args.destination_x, + args.destination_y + ); + return { + type: "drag", + path: [ + { x: startPoint.x, y: startPoint.y }, + { x: endPoint.x, y: endPoint.y } + ] + }; + } + default: + console.warn(`Unsupported Google CUA function: ${name14}`); + return null; + } + } + /** + * Normalize coordinates from Google's 0-1000 range to actual viewport dimensions + */ + normalizeCoordinates(x, y) { + x = Math.min(999, Math.max(0, x)); + y = Math.min(999, Math.max(0, y)); + return { + x: Math.floor(x / 1e3 * this.currentViewport.width), + y: Math.floor(y / 1e3 * this.currentViewport.height) + }; + } + captureScreenshot(options) { + return __async(this, null, function* () { + if (options == null ? void 0 : options.base64Image) { + return `data:image/png;base64,${options.base64Image}`; + } + if (this.screenshotProvider) { + try { + const base64Image = yield this.screenshotProvider(); + return `data:image/png;base64,${base64Image}`; + } catch (error) { + console.error("Error capturing screenshot:", error); + throw error; + } + } + throw new AgentScreenshotProviderError( + "`screenshotProvider` has not been set. Please call `setScreenshotProvider()` with a valid function that returns a base64-encoded image" + ); + }); + } +}; + +// lib/agent/AgentProvider.ts +var modelToAgentProviderMap = { + "computer-use-preview": "openai", + "computer-use-preview-2025-03-11": "openai", + "claude-3-7-sonnet-latest": "anthropic", + "claude-sonnet-4-20250514": "anthropic", + "claude-opus-4-1-20250805": "anthropic", + "claude-sonnet-4-5-20250929": "anthropic", + "computer-use-exp-07-16": "google", + "computer-use-preview-10-2025": "google" +}; +var AgentProvider = class _AgentProvider { + /** + * Create a new agent provider + */ + constructor(logger) { + this.logger = logger; + } + getClient(modelName, clientOptions, userProvidedInstructions, experimental) { + const type = _AgentProvider.getAgentProvider(modelName); + this.logger({ + category: "agent", + message: `Getting agent client for type: ${type}, model: ${modelName}`, + level: 2 + }); + try { + switch (type) { + case "openai": + return new OpenAICUAClient( + type, + modelName, + userProvidedInstructions, + clientOptions + ); + case "anthropic": + return new AnthropicCUAClient( + type, + modelName, + userProvidedInstructions, + clientOptions, + experimental + ); + case "google": + return new GoogleCUAClient( + type, + modelName, + userProvidedInstructions, + clientOptions + ); + default: + throw new UnsupportedModelProviderError( + ["openai", "anthropic", "google"], + "Computer Use Agent" + ); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Error creating agent client: ${errorMessage}`, + level: 0 + }); + throw error; + } + } + static getAgentProvider(modelName) { + if (modelName in modelToAgentProviderMap) { + return modelToAgentProviderMap[modelName]; + } + throw new UnsupportedModelError( + Object.keys(modelToAgentProviderMap), + "Computer Use Agent" + ); + } +}; + +// lib/agent/StagehandAgent.ts +var StagehandAgent = class { + constructor(client, logger) { + this.client = client; + this.logger = logger; + } + execute(optionsOrInstruction) { + return __async(this, null, function* () { + const options = typeof optionsOrInstruction === "string" ? { instruction: optionsOrInstruction } : optionsOrInstruction; + this.logger({ + category: "agent", + message: `Executing agent task: ${options.instruction}`, + level: 1 + }); + const executionOptions = { + options, + logger: this.logger, + retries: 3 + }; + return yield this.client.execute(executionOptions); + }); + } + getModelName() { + return this.client.modelName; + } + getAgentType() { + return this.client.type; + } +}; + +// lib/handlers/agentHandler.ts +var StagehandAgentHandler = class { + constructor(stagehand, stagehandPage, logger, options) { + this.stagehand = stagehand; + this.stagehandPage = stagehandPage; + this.logger = logger; + this.options = options; + this.provider = new AgentProvider(logger); + const client = this.provider.getClient( + options.modelName, + options.clientOptions || {}, + options.userProvidedInstructions, + options.experimental + ); + this.agentClient = client; + this.setupAgentClient(); + this.agent = new StagehandAgent(client, logger); + } + setupAgentClient() { + this.agentClient.setScreenshotProvider(() => __async(this, null, function* () { + const screenshot = yield this.page.screenshot({ + fullPage: false + }); + return screenshot.toString("base64"); + })); + this.agentClient.setActionHandler((action) => __async(this, null, function* () { + var _a15; + const defaultDelay = 1e3; + const waitBetweenActions = ((_a15 = this.options.clientOptions) == null ? void 0 : _a15.waitBetweenActions) || defaultDelay; + try { + try { + yield this.injectCursor(); + } catch (e) { + } + yield new Promise((resolve2) => setTimeout(resolve2, 500)); + yield this.executeAction(action); + yield new Promise((resolve2) => setTimeout(resolve2, waitBetweenActions)); + try { + yield this.captureAndSendScreenshot(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Warning: Failed to take screenshot after action: ${errorMessage}. Continuing execution.`, + level: 1 + }); + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Error executing action ${action.type}: ${errorMessage}`, + level: 0 + }); + throw error; + } + })); + this.updateClientViewport(); + this.updateClientUrl(); + } + /** + * Execute a task with the agent + */ + execute(optionsOrInstruction) { + return __async(this, null, function* () { + const options = typeof optionsOrInstruction === "string" ? { instruction: optionsOrInstruction } : optionsOrInstruction; + const currentUrl = this.page.url(); + if (!currentUrl || currentUrl === "about:blank") { + this.logger({ + category: "agent", + message: `Page URL is empty or about:blank. Redirecting to www.google.com...`, + level: 0 + }); + yield this.page.goto("https://www.google.com"); + } + this.logger({ + category: "agent", + message: `Executing agent task: ${options.instruction}`, + level: 1 + }); + try { + yield this.injectCursor(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Warning: Failed to inject cursor: ${errorMessage}. Continuing with execution.`, + level: 1 + }); + } + if (options.autoScreenshot !== false) { + try { + yield this.captureAndSendScreenshot(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Warning: Failed to take initial screenshot: ${errorMessage}. Continuing with execution.`, + level: 1 + }); + } + } + const result = yield this.agent.execute(optionsOrInstruction); + if (result.usage) { + this.stagehand.updateMetrics( + "AGENT" /* AGENT */, + result.usage.input_tokens, + result.usage.output_tokens, + result.usage.inference_time_ms + ); + } + return result; + }); + } + /** + * Execute a single action on the page + */ + executeAction(action) { + return __async(this, null, function* () { + try { + switch (action.type) { + case "click": { + const { x, y, button = "left" } = action; + yield new Promise((resolve2) => setTimeout(resolve2, 200)); + yield this.page.mouse.click(x, y, { + button + }); + return { success: true }; + } + // Handle the case for "doubleClick" as well for backward compatibility + case "doubleClick": { + const { x, y } = action; + yield this.updateCursorPosition(x, y); + yield this.animateClick(x, y); + yield new Promise((resolve2) => setTimeout(resolve2, 200)); + yield this.animateClick(x, y); + yield new Promise((resolve2) => setTimeout(resolve2, 200)); + yield this.page.mouse.dblclick(x, y); + return { success: true }; + } + case "tripleClick": { + const { x, y } = action; + yield this.updateCursorPosition(x, y); + yield this.animateClick(x, y); + yield new Promise((resolve2) => setTimeout(resolve2, 200)); + yield this.page.mouse.click(x, y, { + clickCount: 3 + }); + return { success: true }; + } + case "type": { + const { text } = action; + yield this.page.keyboard.type(text); + return { success: true }; + } + case "keypress": { + const { keys } = action; + if (Array.isArray(keys)) { + yield this.page.keyboard.press(keys.join("+")); + } + return { success: true }; + } + case "scroll": { + const { x, y, scroll_x = 0, scroll_y = 0 } = action; + yield this.page.mouse.move(x, y); + yield this.page.mouse.wheel(scroll_x, scroll_y); + return { success: true }; + } + case "drag": { + const { path: path4 } = action; + if (Array.isArray(path4) && path4.length >= 2) { + const start = path4[0]; + yield this.updateCursorPosition(start.x, start.y); + yield this.page.mouse.move(start.x, start.y); + yield this.page.mouse.down(); + for (let i = 1; i < path4.length; i++) { + yield this.updateCursorPosition(path4[i].x, path4[i].y); + yield this.page.mouse.move(path4[i].x, path4[i].y); + } + yield this.page.mouse.up(); + } + return { success: true }; + } + case "move": { + const { x, y } = action; + yield this.updateCursorPosition(x, y); + yield this.page.mouse.move(x, y); + return { success: true }; + } + case "wait": { + yield new Promise((resolve2) => setTimeout(resolve2, 1e3)); + return { success: true }; + } + case "screenshot": { + return { success: true }; + } + case "function": { + const { name: name14, arguments: args = {} } = action; + if (name14 === "goto" && typeof args === "object" && args !== null && "url" in args) { + yield this.page.goto(args.url); + this.updateClientUrl(); + return { success: true }; + } else if (name14 === "back") { + yield this.page.goBack(); + this.updateClientUrl(); + return { success: true }; + } else if (name14 === "forward") { + yield this.page.goForward(); + this.updateClientUrl(); + return { success: true }; + } else if (name14 === "reload") { + yield this.page.reload(); + this.updateClientUrl(); + return { success: true }; + } + return { + success: false, + error: `Unsupported function: ${name14}` + }; + } + case "key": { + const { text } = action; + const playwrightKey = mapKeyToPlaywright(text); + yield this.page.keyboard.press(playwrightKey); + return { success: true }; + } + default: + return { + success: false, + error: `Unsupported action type: ${action.type}` + }; + } + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Error executing action ${action.type}: ${errorMessage}`, + level: 0 + }); + return { + success: false, + error: errorMessage + }; + } + }); + } + updateClientViewport() { + } + updateClientUrl() { + const url = this.page.url(); + this.agentClient.setCurrentUrl(url); + } + getAgent() { + return this.agent; + } + getClient() { + return this.agentClient; + } + captureAndSendScreenshot() { + return __async(this, null, function* () { + this.logger({ + category: "agent", + message: "Taking screenshot and sending to agent", + level: 1 + }); + try { + const screenshot = yield this.page.screenshot({ + type: "png", + fullPage: false + }); + if (this.screenshotCollector) { + yield this.screenshotCollector.addScreenshot(screenshot); + } + const base64Image = screenshot.toString("base64"); + return yield this.agentClient.captureScreenshot({ + base64Image, + currentUrl: this.page.url() + }); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : String(error); + this.logger({ + category: "agent", + message: `Error capturing screenshot: ${errorMessage}`, + level: 0 + }); + return null; + } + }); + } + /** + * Inject a cursor element into the page for visual feedback + */ + injectCursor() { + return __async(this, null, function* () { + try { + this.logger({ + category: "agent", + message: "Cursor injected for visual feedback", + level: 1 + }); + } catch (error) { + this.logger({ + category: "agent", + message: `Failed to inject cursor: ${error}`, + level: 0 + }); + } + }); + } + /** + * Update the cursor position on the page + */ + updateCursorPosition(x, y) { + return __async(this, null, function* () { + try { + this.logger({ + category: "agent", + message: `Updating cursor position to ${x}, ${y}`, + level: 2 + }); + } catch (e) { + } + }); + } + /** + * Animate a click at the given position + */ + animateClick(_x, _y) { + return __async(this, null, function* () { + try { + this.logger({ + category: "agent", + message: `Animating click at ${_x}, ${_y}`, + level: 2 + }); + } catch (e) { + } + }); + } + get page() { + return this.stagehand.page; + } + /** + * Set the screenshot collector for this agent handler + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + setScreenshotCollector(collector) { + this.screenshotCollector = collector; + } + /** + * Get the screenshot collector + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getScreenshotCollector() { + return this.screenshotCollector; + } +}; + +// types/operator.ts +var import_v35 = require("zod/v3"); +var operatorResponseSchema = import_v35.z.object({ + reasoning: import_v35.z.string().describe( + "The reasoning for the step taken. If this step's method is `close`, the goal was to extract data, and the task was successful, state the data that was extracted." + ), + method: import_v35.z.enum([ + "act", + "extract", + "goto", + "close", + "wait", + "navback", + "refresh" + ]).describe(`The action to perform on the page based off of the goal and the current state of the page. + goto: Navigate to a specific URL. + act: Perform an action on the page. + extract: Extract data from the page. + close: The task is complete, close the browser. + wait: Wait for a period of time. + navback: Navigate back to the previous page. Do not navigate back if you are already on the first page. + refresh: Refresh the page.`), + parameters: import_v35.z.string().describe( + `The parameter for the action. Only pass in a parameter for the following methods: + - act: The action to perform. e.g. "click on the submit button" or "type [email] into the email input field and press enter" + - extract: The data to extract. e.g. "the title of the article". If you want to extract all of the text on the page, leave this undefined. + - wait: The amount of time to wait in milliseconds. + - goto: The URL to navigate to. e.g. "https://www.google.com" + The other methods do not require a parameter.` + ).nullable(), + taskComplete: import_v35.z.boolean().describe( + "Whether the task is complete. If true, the task is complete and no more steps are needed. If you chose to close the task because the goal is not achievable, set this to false." + ) +}); +var operatorSummarySchema = import_v35.z.object({ + answer: import_v35.z.string().describe("The final answer to the original instruction.") +}); + +// lib/handlers/operatorHandler.ts +var StagehandOperatorHandler = class { + constructor(stagehandPage, logger, llmClient) { + this.stagehandPage = stagehandPage; + this.logger = logger; + this.llmClient = llmClient; + } + execute(instructionOrOptions) { + return __async(this, null, function* () { + const options = typeof instructionOrOptions === "string" ? { instruction: instructionOrOptions } : instructionOrOptions; + this.messages = [buildOperatorSystemPrompt(options.instruction)]; + let completed = false; + let currentStep = 0; + const maxSteps = options.maxSteps || 10; + const actions = []; + while (!completed && currentStep < maxSteps) { + const url = this.stagehandPage.page.url(); + if (!url || url === "about:blank") { + this.messages.push({ + role: "user", + content: [ + { + type: "text", + text: "No page is currently loaded. The first step should be a 'goto' action to navigate to a URL." + } + ] + }); + } else { + const screenshot = yield this.stagehandPage.page.screenshot({ + type: "png", + fullPage: false + }); + const base64Image = screenshot.toString("base64"); + let messageText = `Here is a screenshot of the current page (URL: ${url}):`; + messageText = `Previous actions were: ${actions.map((action) => { + let result2 = ""; + if (action.type === "act") { + const args = action.playwrightArguments; + result2 = `Performed a "${args.method}" action ${args.arguments.length > 0 ? `with arguments: ${args.arguments.map((arg) => `"${arg}"`).join(", ")}` : ""} on "${args.description}"`; + } else if (action.type === "extract") { + result2 = `Extracted data: ${action.extractionResult}`; + } + return `[${action.type}] ${action.reasoning}. Result: ${result2}`; + }).join("\n")} + +${messageText}`; + this.messages.push({ + role: "user", + content: [ + { + type: "text", + text: messageText + }, + this.llmClient.type === "anthropic" ? { + type: "image", + source: { + type: "base64", + media_type: "image/png", + data: base64Image + }, + text: "the screenshot of the current page" + } : { + type: "image_url", + image_url: { url: `data:image/png;base64,${base64Image}` } + } + ] + }); + } + const result = yield this.getNextStep(currentStep); + if (result.method === "close") { + completed = true; + } + let playwrightArguments; + if (result.method === "act") { + [playwrightArguments] = yield this.stagehandPage.page.observe( + result.parameters + ); + } + let extractionResult; + if (result.method === "extract") { + if (result.parameters === null || result.parameters === void 0) { + const extractionResultObj = yield this.stagehandPage.page.extract(); + extractionResult = extractionResultObj.page_text; + } else { + extractionResult = yield this.stagehandPage.page.extract( + result.parameters + ); + } + } + yield this.executeAction(result, playwrightArguments, extractionResult); + actions.push({ + type: result.method, + reasoning: result.reasoning, + taskCompleted: result.taskComplete, + parameters: result.parameters, + playwrightArguments, + extractionResult + }); + currentStep++; + } + return { + success: true, + message: yield this.getSummary(options.instruction), + actions, + completed: actions[actions.length - 1].taskCompleted + }; + }); + } + getNextStep(currentStep) { + return __async(this, null, function* () { + const { data: response } = yield this.llmClient.createChatCompletion({ + options: { + messages: this.messages, + response_model: { + name: "operatorResponseSchema", + schema: operatorResponseSchema + }, + requestId: `operator-step-${currentStep}` + }, + logger: this.logger + }); + return response; + }); + } + getSummary(goal) { + return __async(this, null, function* () { + const { data: response } = yield this.llmClient.createChatCompletion({ + options: { + messages: [ + ...this.messages, + { + role: "user", + content: [ + { + type: "text", + text: `Now use the steps taken to answer the original instruction of ${goal}.` + } + ] + } + ], + response_model: { + name: "operatorSummarySchema", + schema: operatorSummarySchema + }, + requestId: "operator-summary" + }, + logger: this.logger + }); + return response.answer; + }); + } + executeAction(action, playwrightArguments, extractionResult) { + return __async(this, null, function* () { + const { method, parameters } = action; + const page = this.stagehandPage.page; + if (method === "close") { + return; + } + switch (method) { + case "act": + if (!playwrightArguments) { + throw new StagehandMissingArgumentError( + "No arguments provided to `act()`. Please ensure that all required arguments are passed in." + ); + } + yield page.act(playwrightArguments); + break; + case "extract": + if (!extractionResult) { + throw new StagehandError( + "Error in OperatorHandler: Cannot complete extraction. No extractionResult provided." + ); + } + return extractionResult; + case "goto": + yield page.goto(parameters, { waitUntil: "load" }); + break; + case "wait": + yield page.waitForTimeout(parseInt(parameters)); + break; + case "navback": + yield page.goBack(); + break; + case "refresh": + yield page.reload(); + break; + default: + throw new StagehandError( + `Error in OperatorHandler: Cannot execute unknown action: ${method}` + ); + } + }); + } +}; + +// lib/logger.ts +var import_pino = __toESM(require("pino")); +var levelMapping = { + 0: "error", + // Critical/important messages + 1: "info", + // Standard information + 2: "debug" + // Detailed debugging information +}; +function createLogger(options = {}) { + const loggerConfig = { + level: options.level || "info", + base: void 0, + // Don't include pid and hostname + browser: { + asObject: true + }, + // Disable worker threads to avoid issues in tests + transport: void 0 + }; + if (options.pretty && !isTestEnvironment()) { + try { + const transport = { + transport: { + target: "pino-pretty", + options: { + colorize: true, + translateTime: "SYS:standard", + ignore: "pid,hostname" + } + } + }; + Object.assign(loggerConfig, transport); + } catch (e) { + console.warn( + "pino-pretty not available, falling back to standard logging" + ); + } + } + return (0, import_pino.default)(loggerConfig, options.destination); +} +function isTestEnvironment() { + return process.env.NODE_ENV === "test" || process.env.JEST_WORKER_ID !== void 0 || process.env.PLAYWRIGHT_TEST_BASE_DIR !== void 0 || // Check if we're in a CI environment + process.env.CI === "true"; +} +var _StagehandLogger = class _StagehandLogger { + constructor(options = {}, externalLogger) { + this.isTest = isTestEnvironment(); + this.usePino = this.isTest ? false : options.usePino !== false; + if (this.usePino) { + if (!_StagehandLogger.sharedPinoLogger) { + _StagehandLogger.sharedPinoLogger = createLogger(options); + } + this.logger = _StagehandLogger.sharedPinoLogger; + } + this.verbose = 1; + this.externalLogger = externalLogger; + } + /** + * Set the verbosity level + */ + setVerbosity(level) { + this.verbose = level; + if (this.usePino && this.logger) { + switch (level) { + case 0: + this.logger.level = "error"; + break; + case 1: + this.logger.level = "info"; + break; + case 2: + this.logger.level = "debug"; + break; + } + } + } + /** + * Log a message using our LogLine format + */ + log(logLine) { + var _a15, _b, _c; + if (((_a15 = logLine.level) != null ? _a15 : 1) > this.verbose) { + return; + } + const shouldFallbackToConsole = !this.usePino && !this.externalLogger || this.isTest && !this.externalLogger; + if (shouldFallbackToConsole) { + const level = (_b = logLine.level) != null ? _b : 1; + const prefix = `[${logLine.category || "log"}] `; + switch (level) { + case 0: + console.error(prefix + logLine.message); + break; + case 1: + console.log(prefix + logLine.message); + break; + case 2: + console.debug(prefix + logLine.message); + break; + } + return; + } + if (this.usePino && this.logger) { + const pinoLevel = levelMapping[(_c = logLine.level) != null ? _c : 1] || "info"; + const logData = __spreadValues({ + category: logLine.category, + timestamp: logLine.timestamp || (/* @__PURE__ */ new Date()).toISOString() + }, this.formatAuxiliaryData(logLine.auxiliary)); + if (pinoLevel === "error") { + this.logger.error(logData, logLine.message); + } else if (pinoLevel === "info") { + this.logger.info(logData, logLine.message); + } else if (pinoLevel === "debug") { + this.logger.debug(logData, logLine.message); + } else if (pinoLevel === "warn") { + this.logger.warn(logData, logLine.message); + } else if (pinoLevel === "trace") { + this.logger.trace(logData, logLine.message); + } else { + this.logger.info(logData, logLine.message); + } + } + if (this.externalLogger && (!this.usePino || this.isTest)) { + this.externalLogger(logLine); + } + } + /** + * Helper to format auxiliary data for structured logging + */ + formatAuxiliaryData(auxiliary) { + if (!auxiliary) return {}; + const formattedData = {}; + for (const [key, { value, type }] of Object.entries(auxiliary)) { + switch (type) { + case "integer": + formattedData[key] = parseInt(value, 10); + break; + case "float": + formattedData[key] = parseFloat(value); + break; + case "boolean": + formattedData[key] = value === "true"; + break; + case "object": + try { + formattedData[key] = JSON.parse(value); + } catch (e) { + formattedData[key] = value; + } + break; + default: + formattedData[key] = value; + } + } + return formattedData; + } + /** + * Convenience methods for different log levels + */ + error(message, data) { + this.log({ + message, + level: 0, + auxiliary: this.convertToAuxiliary(data) + }); + } + warn(message, data) { + this.log({ + message, + level: 1, + category: "warning", + auxiliary: this.convertToAuxiliary(data) + }); + } + info(message, data) { + this.log({ + message, + level: 1, + auxiliary: this.convertToAuxiliary(data) + }); + } + debug(message, data) { + this.log({ + message, + level: 2, + auxiliary: this.convertToAuxiliary(data) + }); + } + /** + * Convert a plain object to our auxiliary format + */ + convertToAuxiliary(data) { + if (!data) return void 0; + const auxiliary = {}; + for (const [key, value] of Object.entries(data)) { + if (value === void 0) continue; + const type = typeof value; + auxiliary[key] = { + value: type === "object" ? JSON.stringify(value) : String(value), + type: type === "number" ? Number.isInteger(value) ? "integer" : "float" : type === "boolean" ? "boolean" : type === "object" ? "object" : "string" + }; + } + return auxiliary; + } +}; +/** + * We maintain a single shared Pino instance when `usePino` is enabled. + * This prevents spawning a new worker thread for every Stagehand instance + * (which happens when `pino-pretty` transport is used), eliminating the + * memory/RSS growth observed when many Stagehand objects are created and + * disposed within the same process (e.g. a request-per-instance API). + */ +_StagehandLogger.sharedPinoLogger = null; +var StagehandLogger = _StagehandLogger; + +// types/log.ts +var LOG_LEVEL_NAMES = { + 0: "error", + 1: "info", + 2: "debug" +}; + +// types/model.ts +var import_v36 = require("zod/v3"); +var AvailableModelSchema = import_v36.z.enum([ + "gpt-4.1", + "gpt-4.1-mini", + "gpt-4.1-nano", + "o4-mini", + "o3", + "o3-mini", + "o1", + "o1-mini", + "gpt-4o", + "gpt-4o-mini", + "gpt-4o-2024-08-06", + "gpt-4.5-preview", + "o1-preview", + "claude-3-5-sonnet-latest", + "claude-3-5-sonnet-20241022", + "claude-3-5-sonnet-20240620", + "claude-3-7-sonnet-latest", + "claude-3-7-sonnet-20250219", + "cerebras-llama-3.3-70b", + "cerebras-llama-3.1-8b", + "groq-llama-3.3-70b-versatile", + "groq-llama-3.3-70b-specdec", + "gemini-1.5-flash", + "gemini-1.5-pro", + "gemini-1.5-flash-8b", + "gemini-2.0-flash-lite", + "gemini-2.0-flash", + "gemini-2.5-flash-preview-04-17", + "gemini-2.5-pro-preview-03-25" +]); + +// lib/index.ts +import_dotenv.default.config({ path: ".env" }); +var DEFAULT_MODEL_NAME = "openai/gpt-4.1-mini"; +var globalLogger; +var defaultLogger = (logLine, disablePino) => __async(null, null, function* () { + if (!globalLogger) { + globalLogger = new StagehandLogger( + { + pretty: true, + usePino: !disablePino + }, + void 0 + ); + } + globalLogger.log(logLine); +}); +function getBrowser(apiKey, projectId, env = "LOCAL", headless = false, logger, browserbaseSessionCreateParams, browserbaseSessionID, localBrowserLaunchOptions) { + return __async(this, null, function* () { + var _a15, _b, _c, _d, _e, _f, _g, _h, _i, _j, _k, _l, _m, _n, _o, _p, _q, _r; + if (env === "BROWSERBASE") { + if (!apiKey) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_API_KEY", + "Browserbase" + ); + } + if (!projectId) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_PROJECT_ID", + "Browserbase" + ); + } + let debugUrl = void 0; + let sessionUrl = void 0; + let sessionId; + let connectUrl; + const browserbase = new import_sdk3.Browserbase({ + apiKey + }); + if (browserbaseSessionID) { + try { + const session = yield browserbase.sessions.retrieve(browserbaseSessionID); + if (session.status !== "RUNNING") { + throw new StagehandError( + `Session ${browserbaseSessionID} is not running (status: ${session.status})` + ); + } + sessionId = browserbaseSessionID; + connectUrl = session.connectUrl; + logger({ + category: "init", + message: "resuming existing browserbase session...", + level: 1, + auxiliary: { + sessionId: { + value: sessionId, + type: "string" + } + } + }); + } catch (error) { + logger({ + category: "init", + message: "failed to resume session", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string" + }, + trace: { + value: error.stack, + type: "string" + } + } + }); + throw error; + } + } else { + logger({ + category: "init", + message: "creating new browserbase session...", + level: 1 + }); + if (!projectId) { + throw new StagehandError( + "BROWSERBASE_PROJECT_ID is required for new Browserbase sessions." + ); + } + const session = yield browserbase.sessions.create(__spreadProps(__spreadValues({ + projectId + }, browserbaseSessionCreateParams), { + userMetadata: __spreadProps(__spreadValues({}, (browserbaseSessionCreateParams == null ? void 0 : browserbaseSessionCreateParams.userMetadata) || {}), { + stagehand: "true" + }) + })); + sessionId = session.id; + connectUrl = session.connectUrl; + logger({ + category: "init", + message: "created new browserbase session", + level: 1, + auxiliary: { + sessionId: { + value: sessionId, + type: "string" + } + } + }); + } + if (!connectUrl.includes("connect.connect")) { + logger({ + category: "init", + message: "connecting to browserbase session", + level: 1, + auxiliary: { + connectUrl: { + value: connectUrl, + type: "string" + } + } + }); + } + const browser = yield import_playwright3.chromium.connectOverCDP(connectUrl); + const { debuggerUrl } = yield browserbase.sessions.debug(sessionId); + debugUrl = debuggerUrl; + sessionUrl = `https://www.browserbase.com/sessions/${sessionId}`; + logger({ + category: "init", + message: browserbaseSessionID ? "browserbase session resumed" : "browserbase session started", + auxiliary: { + sessionUrl: { + value: sessionUrl, + type: "string" + }, + debugUrl: { + value: debugUrl, + type: "string" + }, + sessionId: { + value: sessionId, + type: "string" + } + } + }); + const context = browser.contexts()[0]; + return { browser, context, debugUrl, sessionUrl, sessionId, env }; + } else { + if (localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.cdpUrl) { + if (!localBrowserLaunchOptions.cdpUrl.includes("connect.connect")) { + logger({ + category: "init", + message: "connecting to local browser via CDP URL", + level: 1, + auxiliary: { + cdpUrl: { + value: localBrowserLaunchOptions.cdpUrl, + type: "string" + } + } + }); + } + const browser2 = yield import_playwright3.chromium.connectOverCDP( + localBrowserLaunchOptions.cdpUrl + ); + const context2 = browser2.contexts()[0]; + return { browser: browser2, context: context2, env: "LOCAL" }; + } + let userDataDir = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.userDataDir; + if (!userDataDir) { + const tmpDirPath = import_path2.default.join(import_os.default.tmpdir(), "stagehand"); + if (!import_fs2.default.existsSync(tmpDirPath)) { + import_fs2.default.mkdirSync(tmpDirPath, { recursive: true }); + } + const tmpDir = import_fs2.default.mkdtempSync(import_path2.default.join(tmpDirPath, "ctx_")); + import_fs2.default.mkdirSync(import_path2.default.join(tmpDir, "userdir/Default"), { recursive: true }); + const defaultPreferences = { + plugins: { + always_open_pdf_externally: true + } + }; + import_fs2.default.writeFileSync( + import_path2.default.join(tmpDir, "userdir/Default/Preferences"), + JSON.stringify(defaultPreferences) + ); + userDataDir = import_path2.default.join(tmpDir, "userdir"); + } + let downloadsPath = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.downloadsPath; + if (!downloadsPath) { + downloadsPath = import_path2.default.join(process.cwd(), "downloads"); + import_fs2.default.mkdirSync(downloadsPath, { recursive: true }); + } + const context = yield import_playwright3.chromium.launchPersistentContext(userDataDir, { + acceptDownloads: (_a15 = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.acceptDownloads) != null ? _a15 : true, + headless: (_b = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.headless) != null ? _b : headless, + viewport: { + width: (_d = (_c = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.viewport) == null ? void 0 : _c.width) != null ? _d : 1288, + height: (_f = (_e = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.viewport) == null ? void 0 : _e.height) != null ? _f : 711 + }, + locale: (_g = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.locale) != null ? _g : "en-US", + timezoneId: (_h = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.timezoneId) != null ? _h : "America/New_York", + deviceScaleFactor: (_i = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.deviceScaleFactor) != null ? _i : 1, + args: (_j = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.args) != null ? _j : [ + "--disable-blink-features=AutomationControlled" + ], + bypassCSP: (_k = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.bypassCSP) != null ? _k : true, + proxy: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.proxy, + geolocation: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.geolocation, + hasTouch: (_l = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.hasTouch) != null ? _l : true, + ignoreHTTPSErrors: (_m = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.ignoreHTTPSErrors) != null ? _m : true, + permissions: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.permissions, + recordHar: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.recordHar, + recordVideo: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.recordVideo, + tracesDir: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.tracesDir, + extraHTTPHeaders: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.extraHTTPHeaders, + chromiumSandbox: (_n = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.chromiumSandbox) != null ? _n : false, + devtools: (_o = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.devtools) != null ? _o : false, + env: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.env, + executablePath: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.executablePath, + handleSIGHUP: (_p = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.handleSIGHUP) != null ? _p : true, + handleSIGINT: (_q = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.handleSIGINT) != null ? _q : true, + handleSIGTERM: (_r = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.handleSIGTERM) != null ? _r : true, + ignoreDefaultArgs: localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.ignoreDefaultArgs + }); + if (localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.cookies) { + context.addCookies(localBrowserLaunchOptions.cookies); + } + const browser = context.browser(); + logger({ + category: "init", + message: "local browser started successfully." + }); + yield applyStealthScripts(context); + return { browser, context, contextPath: userDataDir, env: "LOCAL" }; + } + }); +} +function applyStealthScripts(context) { + return __async(this, null, function* () { + yield context.addInitScript(() => { + Object.defineProperty(navigator, "webdriver", { + get: () => void 0 + }); + Object.defineProperty(navigator, "languages", { + get: () => ["en-US", "en"] + }); + Object.defineProperty(navigator, "plugins", { + get: () => [1, 2, 3, 4, 5] + }); + delete window.__playwright; + delete window.__pw_manual; + delete window.__PW_inspect; + Object.defineProperty(navigator, "headless", { + get: () => false + }); + const originalQuery = window.navigator.permissions.query; + window.navigator.permissions.query = (parameters) => parameters.name === "notifications" ? Promise.resolve({ + state: Notification.permission + }) : originalQuery(parameters); + }); + }); +} +var Stagehand3 = class { + constructor({ + env, + apiKey, + projectId, + verbose, + llmProvider, + llmClient, + logger, + browserbaseSessionCreateParams, + domSettleTimeoutMs, + enableCaching, + browserbaseSessionID, + modelName, + modelClientOptions, + systemPrompt, + useAPI = true, + localBrowserLaunchOptions, + waitForCaptchaSolves = false, + logInferenceToFile = false, + selfHeal = false, + disablePino, + experimental = false + } = { + env: "BROWSERBASE" + }) { + this.cleanupCalled = false; + this._isClosed = false; + this._history = []; + this.stagehandMetrics = { + actPromptTokens: 0, + actCompletionTokens: 0, + actInferenceTimeMs: 0, + extractPromptTokens: 0, + extractCompletionTokens: 0, + extractInferenceTimeMs: 0, + observePromptTokens: 0, + observeCompletionTokens: 0, + observeInferenceTimeMs: 0, + agentPromptTokens: 0, + agentCompletionTokens: 0, + agentInferenceTimeMs: 0, + totalPromptTokens: 0, + totalCompletionTokens: 0, + totalInferenceTimeMs: 0 + }; + var _a15, _b, _c, _d, _e, _f, _g; + this.externalLogger = logger || ((logLine) => defaultLogger(logLine, disablePino)); + this.stagehandLogger = new StagehandLogger( + { + pretty: true, + // use pino if pino is enabled, and there is no custom logger + usePino: !logger && !disablePino + }, + this.externalLogger + ); + this.enableCaching = enableCaching != null ? enableCaching : process.env.ENABLE_CACHING && process.env.ENABLE_CACHING === "true"; + this.llmProvider = llmProvider || new LLMProvider(this.logger, this.enableCaching); + this.apiKey = apiKey != null ? apiKey : process.env.BROWSERBASE_API_KEY; + this.projectId = projectId != null ? projectId : process.env.BROWSERBASE_PROJECT_ID; + this._env = env != null ? env : "BROWSERBASE"; + if (this._env === "BROWSERBASE") { + if (!this.apiKey) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_API_KEY", + "Browserbase" + ); + } else if (!this.projectId) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_PROJECT_ID", + "Browserbase" + ); + } + } + this.verbose = verbose != null ? verbose : 0; + this.stagehandLogger.setVerbosity(this.verbose); + this.modelName = modelName != null ? modelName : DEFAULT_MODEL_NAME; + let modelApiKey; + if (!(modelClientOptions == null ? void 0 : modelClientOptions.apiKey)) { + if (LLMProvider.getModelProvider(this.modelName) === "aisdk") { + modelApiKey = loadApiKeyFromEnv( + this.modelName.split("/")[0], + this.logger + ); + } else { + modelApiKey = LLMProvider.getModelProvider(this.modelName) === "openai" ? process.env.OPENAI_API_KEY || ((_b = (_a15 = this.llmClient) == null ? void 0 : _a15.clientOptions) == null ? void 0 : _b.apiKey) : LLMProvider.getModelProvider(this.modelName) === "anthropic" ? process.env.ANTHROPIC_API_KEY || ((_d = (_c = this.llmClient) == null ? void 0 : _c.clientOptions) == null ? void 0 : _d.apiKey) : LLMProvider.getModelProvider(this.modelName) === "google" ? process.env.GOOGLE_API_KEY || ((_f = (_e = this.llmClient) == null ? void 0 : _e.clientOptions) == null ? void 0 : _f.apiKey) : void 0; + } + this.modelClientOptions = __spreadProps(__spreadValues({}, modelClientOptions), { + apiKey: modelApiKey + }); + } else { + this.modelClientOptions = modelClientOptions; + } + if (llmClient) { + this.llmClient = llmClient; + this.logger({ + category: "init", + message: "Custom LLM clients are currently not supported in API mode", + level: 1 + }); + this.usingAPI = false; + } else { + try { + this.llmClient = this.llmProvider.getClient( + this.modelName, + this.modelClientOptions + ); + } catch (error) { + if (error instanceof UnsupportedAISDKModelProviderError || error instanceof InvalidAISDKModelFormatError) { + throw error; + } + this.llmClient = void 0; + } + } + this.domSettleTimeoutMs = domSettleTimeoutMs != null ? domSettleTimeoutMs : 3e4; + this.headless = (_g = localBrowserLaunchOptions == null ? void 0 : localBrowserLaunchOptions.headless) != null ? _g : false; + this.browserbaseSessionCreateParams = browserbaseSessionCreateParams; + this.browserbaseSessionID = browserbaseSessionID; + this.userProvidedInstructions = systemPrompt; + this.usingAPI = useAPI; + if (this.usingAPI && env === "LOCAL") { + this.usingAPI = false; + } else if (this.usingAPI && this.llmClient && !["openai", "anthropic", "google", "aisdk"].includes(this.llmClient.type)) { + throw new UnsupportedModelError( + ["openai", "anthropic", "google", "aisdk"], + "API mode" + ); + } + this.waitForCaptchaSolves = waitForCaptchaSolves; + this.localBrowserLaunchOptions = localBrowserLaunchOptions; + if (this.usingAPI) { + this.registerSignalHandlers(); + } + this.logInferenceToFile = logInferenceToFile; + this.selfHeal = selfHeal; + this.disablePino = disablePino; + this.experimental = experimental; + if (this.experimental) { + this.stagehandLogger.warn( + "Experimental mode is enabled. This is a beta feature and may break at any time. Enabling experimental mode will disable the API" + ); + this.usingAPI = false; + } + } + createLivePageProxy() { + const proto = Object.getPrototypeOf(this.stagehandPage.page); + const target = Object.create(proto); + const handler = { + get: (_t, prop, receiver) => { + const real = this.stagehandPage.page; + const value = Reflect.get(real, prop, receiver); + return typeof value === "function" ? value.bind(real) : value; + }, + set: (_t, prop, value) => { + const real = this.stagehandPage.page; + Reflect.set(real, prop, value); + return true; + }, + has: (_t, prop) => prop in this.stagehandPage.page, + getPrototypeOf: () => proto + }; + return new Proxy(target, handler); + } + get history() { + return Object.freeze([...this._history]); + } + setActivePage(page) { + this.stagehandPage = page; + } + get page() { + if (!this.stagehandContext) { + throw new StagehandNotInitializedError("page"); + } + if (!this._livePageProxy) { + this._livePageProxy = this.createLivePageProxy(); + } + return this._livePageProxy; + } + get metrics() { + return this.stagehandMetrics; + } + get isClosed() { + return this._isClosed; + } + updateMetrics(functionName, promptTokens, completionTokens, inferenceTimeMs) { + switch (functionName) { + case "ACT" /* ACT */: + this.stagehandMetrics.actPromptTokens += promptTokens; + this.stagehandMetrics.actCompletionTokens += completionTokens; + this.stagehandMetrics.actInferenceTimeMs += inferenceTimeMs; + break; + case "EXTRACT" /* EXTRACT */: + this.stagehandMetrics.extractPromptTokens += promptTokens; + this.stagehandMetrics.extractCompletionTokens += completionTokens; + this.stagehandMetrics.extractInferenceTimeMs += inferenceTimeMs; + break; + case "OBSERVE" /* OBSERVE */: + this.stagehandMetrics.observePromptTokens += promptTokens; + this.stagehandMetrics.observeCompletionTokens += completionTokens; + this.stagehandMetrics.observeInferenceTimeMs += inferenceTimeMs; + break; + case "AGENT" /* AGENT */: + this.stagehandMetrics.agentPromptTokens += promptTokens; + this.stagehandMetrics.agentCompletionTokens += completionTokens; + this.stagehandMetrics.agentInferenceTimeMs += inferenceTimeMs; + break; + } + this.updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs); + } + updateTotalMetrics(promptTokens, completionTokens, inferenceTimeMs) { + this.stagehandMetrics.totalPromptTokens += promptTokens; + this.stagehandMetrics.totalCompletionTokens += completionTokens; + this.stagehandMetrics.totalInferenceTimeMs += inferenceTimeMs; + } + registerSignalHandlers() { + const cleanup = (signal) => __async(this, null, function* () { + if (this.cleanupCalled) return; + this.cleanupCalled = true; + this.stagehandLogger.info( + `[${signal}] received. Ending Browserbase session...` + ); + try { + yield this.close(); + } catch (err) { + this.stagehandLogger.error("Error ending Browserbase session:", { + error: String(err) + }); + } finally { + process.exit(0); + } + }); + process.once("SIGINT", () => void cleanup("SIGINT")); + process.once("SIGTERM", () => void cleanup("SIGTERM")); + } + get logger() { + return (logLine) => { + this.log(logLine); + }; + } + get env() { + if (this._env === "BROWSERBASE") { + if (!this.apiKey) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_API_KEY", + "Browserbase" + ); + } else if (!this.projectId) { + throw new MissingEnvironmentVariableError( + "BROWSERBASE_PROJECT_ID", + "Browserbase" + ); + } + return "BROWSERBASE"; + } else { + return "LOCAL"; + } + } + get downloadsPath() { + var _a15, _b; + return this.env === "BROWSERBASE" ? "downloads" : (_b = (_a15 = this.localBrowserLaunchOptions) == null ? void 0 : _a15.downloadsPath) != null ? _b : import_path2.default.resolve(process.cwd(), "downloads"); + } + get context() { + if (!this.stagehandContext) { + throw new StagehandNotInitializedError("context"); + } + return this.stagehandContext.context; + } + init() { + return __async(this, null, function* () { + var _a15; + if (isRunningInBun()) { + throw new StagehandError( + "Playwright does not currently support the Bun runtime environment. Please use Node.js instead. For more information, see: https://github.com/microsoft/playwright/issues/27139" + ); + } + if (this.usingAPI) { + this.apiClient = new StagehandAPI({ + apiKey: this.apiKey, + projectId: this.projectId, + logger: this.logger + }); + const modelApiKey = (_a15 = this.modelClientOptions) == null ? void 0 : _a15.apiKey; + const { sessionId: sessionId2, available } = yield this.apiClient.init({ + modelName: this.modelName, + modelApiKey, + domSettleTimeoutMs: this.domSettleTimeoutMs, + verbose: this.verbose, + debugDom: this.debugDom, + systemPrompt: this.userProvidedInstructions, + selfHeal: this.selfHeal, + waitForCaptchaSolves: this.waitForCaptchaSolves, + actionTimeoutMs: this.actTimeoutMs, + browserbaseSessionCreateParams: this.browserbaseSessionCreateParams, + browserbaseSessionID: this.browserbaseSessionID + }); + if (!available) { + this.apiClient = null; + } + this.browserbaseSessionID = sessionId2; + } + const { browser, context, debugUrl, sessionUrl, contextPath, sessionId } = yield getBrowser( + this.apiKey, + this.projectId, + this.env, + this.headless, + this.logger, + this.browserbaseSessionCreateParams, + this.browserbaseSessionID, + this.localBrowserLaunchOptions + ).catch((e) => { + this.stagehandLogger.error("Error in init:", { error: String(e) }); + const br = { + context: void 0, + debugUrl: void 0, + sessionUrl: void 0, + sessionId: void 0, + env: this.env + }; + return br; + }); + this.contextPath = contextPath; + this._browser = browser; + if (!context) { + const errorMessage = "The browser context is undefined. This means the CDP connection to the browser failed"; + this.stagehandLogger.error( + this.env === "LOCAL" ? `${errorMessage}. If running locally, please check if the browser is running and the port is open.` : errorMessage + ); + throw new StagehandInitError(errorMessage); + } + this.stagehandContext = yield StagehandContext.init(context, this); + const defaultPage = (yield this.stagehandContext.getStagehandPages())[0]; + this.stagehandPage = defaultPage; + if (this.headless) { + yield this.page.setViewportSize({ width: 2560, height: 1440 }); + } + const guardedScript = ` + if (!window.__stagehandInjected) { + window.__stagehandInjected = true; + ${scriptContent} + } +`; + yield this.context.addInitScript({ + content: guardedScript + }); + try { + const session = yield this.context.newCDPSession(this.page); + yield session.send("Browser.setDownloadBehavior", { + behavior: "allow", + downloadPath: this.downloadsPath, + eventsEnabled: true + }); + } catch (error) { + this.stagehandLogger.error("Error setting download behavior:", { + error: String(error) + }); + } + this.browserbaseSessionID = sessionId; + return { debugUrl, sessionUrl, sessionId }; + }); + } + log(logObj) { + var _a15; + logObj.level = (_a15 = logObj.level) != null ? _a15 : 1; + this.stagehandLogger.log(logObj); + } + close() { + return __async(this, null, function* () { + var _a15; + this._isClosed = true; + if (this.apiClient) { + const response = yield this.apiClient.end(); + const body = yield response.json(); + if (!body.success) { + if (response.status == 409) { + this.log({ + category: "close", + message: "Warning: attempted to end a session that is not currently active", + level: 0 + }); + } else { + throw new StagehandError(body.message); + } + } + this.apiClient = null; + return; + } else { + yield this.context.close(); + if (this._browser) { + yield this._browser.close(); + } + } + if (this.contextPath && !((_a15 = this.localBrowserLaunchOptions) == null ? void 0 : _a15.preserveUserDataDir)) { + try { + import_fs2.default.rmSync(this.contextPath, { recursive: true, force: true }); + } catch (e) { + console.error("Error deleting context directory:", e); + } + } + }); + } + addToHistory(method, parameters, result) { + this._history.push({ + method, + parameters, + result: result != null ? result : null, + timestamp: (/* @__PURE__ */ new Date()).toISOString() + }); + } + /** + * Create an agent instance that can be executed with different instructions + * @returns An agent instance with execute() and setViewport() methods + */ + agent(options) { + var _a15; + if (!options || !options.provider) { + return { + execute: (instructionOrOptions) => __async(this, null, function* () { + return new StagehandOperatorHandler( + this.stagehandPage, + this.logger, + this.llmClient + ).execute(instructionOrOptions); + }) + }; + } + const agentHandler = new StagehandAgentHandler( + this, + this.stagehandPage, + this.logger, + { + modelName: options.model, + clientOptions: options.options, + userProvidedInstructions: (_a15 = options.instructions) != null ? _a15 : `You are a helpful assistant that can use a web browser. + You are currently on the following page: ${this.stagehandPage.page.url()}. + Do not ask follow up questions, the user will trust your judgement.`, + agentType: options.provider, + experimental: this.experimental + } + ); + this.log({ + category: "agent", + message: "Creating agent instance", + level: 1 + }); + return { + execute: (instructionOrOptions) => __async(this, null, function* () { + const executeOptions = typeof instructionOrOptions === "string" ? { instruction: instructionOrOptions } : instructionOrOptions; + if (!executeOptions.instruction) { + throw new StagehandError( + "Instruction is required for agent execution" + ); + } + if (this.usingAPI) { + if (!this.apiClient) { + throw new StagehandNotInitializedError("API client"); + } + if (!options.options) { + options.options = {}; + } + if (options.provider === "anthropic") { + options.options.apiKey = process.env.ANTHROPIC_API_KEY; + } else if (options.provider === "openai") { + options.options.apiKey = process.env.OPENAI_API_KEY; + } else if (options.provider === "google") { + options.options.apiKey = process.env.GOOGLE_API_KEY; + } + if (!options.options.apiKey) { + throw new StagehandError( + `API key not found for \`${options.provider}\` provider. Please set the ${options.provider === "anthropic" ? "ANTHROPIC_API_KEY" : "OPENAI_API_KEY"} environment variable or pass an apiKey in the options object.` + ); + } + return yield this.apiClient.agentExecute(options, executeOptions); + } + return yield agentHandler.execute(executeOptions); + }), + setScreenshotCollector: (collector) => { + agentHandler.setScreenshotCollector(collector); + } + }; + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (module.exports = { + AgentScreenshotProviderError, + AnnotatedScreenshotText, + AvailableModelSchema, + BrowserbaseSessionNotFoundError, + CaptchaTimeoutError, + ContentFrameNotFoundError, + CreateChatCompletionResponseError, + ExperimentalApiConflictError, + ExperimentalNotConfiguredError, + HandlerNotInitializedError, + InvalidAISDKModelFormatError, + LLMClient, + LLMResponseError, + LOG_LEVEL_NAMES, + MissingEnvironmentVariableError, + MissingLLMConfigurationError, + PlaywrightCommandException, + PlaywrightCommandMethodNotSupportedException, + Stagehand, + StagehandAPIError, + StagehandAPIUnauthorizedError, + StagehandClickError, + StagehandDefaultError, + StagehandDomProcessError, + StagehandElementNotFoundError, + StagehandEnvironmentError, + StagehandError, + StagehandEvalError, + StagehandFunctionName, + StagehandHttpError, + StagehandIframeError, + StagehandInitError, + StagehandInvalidArgumentError, + StagehandMissingArgumentError, + StagehandNotInitializedError, + StagehandResponseBodyError, + StagehandResponseParseError, + StagehandServerError, + StagehandShadowRootMissingError, + StagehandShadowSegmentEmptyError, + StagehandShadowSegmentNotFoundError, + UnsupportedAISDKModelProviderError, + UnsupportedModelError, + UnsupportedModelProviderError, + XPathResolutionError, + ZodSchemaValidationError, + defaultExtractSchema, + operatorResponseSchema, + operatorSummarySchema, + pageTextSchema +}); diff --git a/sdk/stagehand-ts/dist/lib/StagehandContext.d.ts b/sdk/stagehand-ts/dist/lib/StagehandContext.d.ts new file mode 100644 index 0000000..7fc90bb --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/StagehandContext.d.ts @@ -0,0 +1,25 @@ +import type { BrowserContext as PlaywrightContext, Page as PlaywrightPage } from "playwright"; +import { Stagehand } from "./index"; +import { StagehandPage } from "./StagehandPage"; +import { EnhancedContext } from "../types/context"; +export declare class StagehandContext { + private readonly stagehand; + private readonly intContext; + private pageMap; + private activeStagehandPage; + private readonly frameIdMap; + private constructor(); + private createStagehandPage; + static init(context: PlaywrightContext, stagehand: Stagehand): Promise; + get frameIdLookup(): ReadonlyMap; + registerFrameId(frameId: string, page: StagehandPage): void; + unregisterFrameId(frameId: string): void; + getStagehandPageByFrameId(frameId: string): StagehandPage | undefined; + get context(): EnhancedContext; + getStagehandPage(page: PlaywrightPage): Promise; + getStagehandPages(): Promise; + setActivePage(page: StagehandPage): void; + getActivePage(): StagehandPage | null; + private handleNewPlaywrightPage; + private attachFrameNavigatedListener; +} diff --git a/sdk/stagehand-ts/dist/lib/StagehandPage.d.ts b/sdk/stagehand-ts/dist/lib/StagehandPage.d.ts new file mode 100644 index 0000000..2fe874b --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/StagehandPage.d.ts @@ -0,0 +1,104 @@ +import type { CDPSession, Page as PlaywrightPage, Frame } from "playwright"; +import { z } from "zod/v3"; +import { Page, defaultExtractSchema } from "../types/page"; +import { ExtractOptions, ExtractResult, ObserveOptions, ObserveResult } from "../types/stagehand"; +import { StagehandAPI } from "./api"; +import { ActOptions, ActResult, Stagehand } from "./index"; +import { LLMClient } from "./llm/LLMClient"; +import { StagehandContext } from "./StagehandContext"; +import { EncodedId, EnhancedContext } from "../types/context"; +/** ensure we register the custom selector only once per process */ +export declare class StagehandPage { + stagehand: Stagehand; + private rawPage; + private intPage; + private intContext; + private actHandler; + private extractHandler; + private observeHandler; + private llmClient; + private cdpClient; + private api; + private userProvidedInstructions?; + private waitForCaptchaSolves; + private initialized; + private isClosed; + private readonly cdpClients; + private fidOrdinals; + private rootFrameId; + get frameId(): string; + updateRootFrameId(newId: string): void; + constructor(page: PlaywrightPage, stagehand: Stagehand, context: StagehandContext, llmClient: LLMClient, userProvidedInstructions?: string, api?: StagehandAPI, waitForCaptchaSolves?: boolean); + ordinalForFrameId(fid: string | undefined): number; + encodeWithFrameId(fid: string | undefined, backendId: number): EncodedId; + resetFrameOrdinals(): void; + private ensureStagehandScript; + /** Register the custom selector engine that pierces open/closed shadow roots. */ + /** + * Waits for a captcha to be solved when using Browserbase environment. + * + * @param timeoutMs - Optional timeout in milliseconds. If provided, the promise will reject if the captcha solving hasn't started within the given time. + * @throws StagehandEnvironmentError if called in a LOCAL environment + * @throws CaptchaTimeoutError if the timeout is reached before captcha solving starts + * @returns Promise that resolves when the captcha is solved + */ + waitForCaptchaSolve(timeoutMs?: number): Promise; + init(): Promise; + get page(): Page; + get context(): EnhancedContext; + /** + * `_waitForSettledDom` waits until the DOM is settled, and therefore is + * ready for actions to be taken. + * + * **Definition of "settled"** + * • No in-flight network requests (except WebSocket / Server-Sent-Events). + * • That idle state lasts for at least **500 ms** (the "quiet-window"). + * + * **How it works** + * 1. Subscribes to CDP Network and Page events for the main target and all + * out-of-process iframes (via `Target.setAutoAttach { flatten:true }`). + * 2. Every time `Network.requestWillBeSent` fires, the request ID is added + * to an **`inflight`** `Set`. + * 3. When the request finishes—`loadingFinished`, `loadingFailed`, + * `requestServedFromCache`, or a *data:* response—the request ID is + * removed. + * 4. *Document* requests are also mapped **frameId → requestId**; when + * `Page.frameStoppedLoading` fires the corresponding Document request is + * removed immediately (covers iframes whose network events never close). + * 5. A **stalled-request sweep timer** runs every 500 ms. If a *Document* + * request has been open for ≥ 2 s it is forcibly removed; this prevents + * ad/analytics iframes from blocking the wait forever. + * 6. When `inflight` becomes empty the helper starts a 500 ms timer. + * If no new request appears before the timer fires, the promise + * resolves → **DOM is considered settled**. + * 7. A global guard (`timeoutMs` or `stagehand.domSettleTimeoutMs`, + * default ≈ 30 s) ensures we always resolve; if it fires we log how many + * requests were still outstanding. + * + * @param timeoutMs – Optional hard cap (ms). Defaults to + * `this.stagehand.domSettleTimeoutMs`. + */ + _waitForSettledDom(timeoutMs?: number): Promise; + act(actionOrOptions: string | ActOptions | ObserveResult): Promise; + extract(instructionOrOptions?: string | ExtractOptions): Promise>; + observe(instructionOrOptions?: string | ObserveOptions): Promise; + /** + * Get or create a CDP session for the given target. + * @param target The Page or (OOPIF) Frame you want to talk to. + */ + getCDPClient(target?: PlaywrightPage | Frame): Promise; + /** + * Send a CDP command to the chosen DevTools target. + * + * @param method Any valid CDP method, e.g. `"DOM.getDocument"`. + * @param params Command parameters (optional). + * @param target A `Page` or OOPIF `Frame`. Defaults to the main page. + * + * @typeParam T Expected result shape (defaults to `unknown`). + */ + sendCDP(method: string, params?: Record, target?: PlaywrightPage | Frame): Promise; + /** Enable a CDP domain (e.g. `"Network"` or `"DOM"`) on the chosen target. */ + enableCDP(domain: string, target?: PlaywrightPage | Frame): Promise; + /** Disable a CDP domain on the chosen target. */ + disableCDP(domain: string, target?: PlaywrightPage | Frame): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/a11y/utils.d.ts b/sdk/stagehand-ts/dist/lib/a11y/utils.d.ts new file mode 100644 index 0000000..7ce5d96 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/a11y/utils.d.ts @@ -0,0 +1,144 @@ +import { AccessibilityNode, TreeResult, BackendIdMaps, CombinedA11yResult, EncodedId } from "../../types/context"; +import { StagehandPage } from "../StagehandPage"; +import { LogLine } from "../../types/log"; +import { Frame } from "playwright"; +/** + * Clean a string by removing private-use unicode characters, normalizing whitespace, + * and trimming the result. + * + * @param input - The text to clean, potentially containing PUA and NBSP characters. + * @returns A cleaned string with PUA characters removed, NBSP variants collapsed, + * consecutive spaces merged, and leading/trailing whitespace trimmed. + */ +export declare function cleanText(input: string): string; +/** + * Generate a human-readable, indented outline of an accessibility node tree. + * + * @param node - The accessibility node to format, optionally with an encodedId. + * @param level - The current depth level for indentation (used internally). + * @returns A string representation of the node and its descendants, with one node per line. + */ +export declare function formatSimplifiedTree(node: AccessibilityNode & { + encodedId?: EncodedId; +}, level?: number): string; +/** + * Build mappings from CDP backendNodeIds to HTML tag names and relative XPaths. + * + * @param experimental - Whether to use experimental behaviour. + * @param sp - The StagehandPage wrapper for Playwright and CDP calls. + * @param targetFrame - Optional Playwright.Frame whose DOM subtree to map; defaults to main frame. + * @returns A Promise resolving to BackendIdMaps containing tagNameMap and xpathMap. + */ +export declare function buildBackendIdMaps(experimental: boolean, sp: StagehandPage, targetFrame?: Frame): Promise; +/** + * Convert a flat array of AccessibilityNodes into a cleaned, hierarchical tree. + * Nodes are pruned, structural wrappers removed, and each kept node is stamped + * with its EncodedId for later lookup or subtree injection. + * + * @param nodes - Raw flat list of AX nodes retrieved via CDP. + * @param tagNameMap - Mapping of EncodedId to HTML tag names for structural decisions. + * @param logger - Optional function for logging diagnostic messages. + * @param xpathMap - Optional mapping of EncodedId to relative XPath for element lookup. + * @returns A Promise resolving to a TreeResult with cleaned tree, simplified text outline, + * iframe list, URL map, and inherited xpathMap. + */ +export declare function buildHierarchicalTree(nodes: AccessibilityNode[], tagNameMap: Record, logger?: (l: LogLine) => void, xpathMap?: Record): Promise; +/** + * Resolve the CDP frame identifier for a Playwright Frame, handling same-process and OOPIF. + * + * @param sp - The StagehandPage instance for issuing CDP commands. + * @param frame - The target Playwright.Frame; undefined or main frame yields undefined. + * @returns A Promise resolving to the CDP frameId string, or undefined for main document. + */ +export declare function getCDPFrameId(sp: StagehandPage, frame?: Frame): Promise; +/** + * Retrieve and build a cleaned accessibility tree for a document or specific iframe. + * Prunes, formats, and optionally filters by XPath, including scrollable role decoration. + * + * @param stagehandPage - The StagehandPage instance for Playwright and CDP interaction. + * @param logger - Logging function for diagnostics and performance metrics. + * @param selector - Optional XPath to filter the AX tree to a specific subtree. + * @param targetFrame - Optional Playwright.Frame to scope the AX tree retrieval. + * @returns A Promise resolving to a TreeResult with the hierarchical AX tree and related metadata. + */ +export declare function getAccessibilityTree(experimental: boolean, stagehandPage: StagehandPage, logger: (log: LogLine) => void, selector?: string, targetFrame?: Frame): Promise; +/** + * Get the backendNodeId of the iframe element that contains a given Playwright.Frame. + * + * @param sp - The StagehandPage instance for issuing CDP commands. + * @param frame - The Playwright.Frame whose host iframe element to locate. + * @returns A Promise resolving to the backendNodeId of the iframe element, or null if not applicable. + */ +export declare function getFrameRootBackendNodeId(sp: StagehandPage, frame: Frame | undefined): Promise; +/** + * Compute the absolute XPath for the iframe element hosting a given Playwright.Frame. + * + * @param frame - The Playwright.Frame whose iframe element to locate. + * @returns A Promise resolving to the XPath of the iframe element, or "/" if no frame provided. + */ +export declare function getFrameRootXpathWithShadow(frame: Frame | undefined): Promise; +export declare function getFrameRootXpath(frame: Frame | undefined): Promise; +/** + * Inject simplified subtree outlines into the main frame outline for nested iframes. + * Walks the main tree text, looks for EncodedId labels, and inserts matching subtrees. + * + * @param tree - The indented AX outline of the main frame. + * @param idToTree - Map of EncodedId to subtree outlines for nested frames. + * @returns A single combined text outline with iframe subtrees injected. + */ +export declare function injectSubtrees(tree: string, idToTree: Map): string; +/** + * Retrieve and merge accessibility trees for the main document and nested iframes. + * Walks through frame chains if a root XPath is provided, then stitches subtree outlines. + * + * @param stagehandPage - The StagehandPage instance for Playwright and CDP interaction. + * @param logger - Logging function for diagnostics and performance. + * @param rootXPath - Optional absolute XPath to focus the crawl on a subtree across frames. + * @returns A Promise resolving to CombinedA11yResult with combined tree text, xpath map, and URL map. + */ +export declare function getAccessibilityTreeWithFrames(experimental: boolean, stagehandPage: StagehandPage, logger: (l: LogLine) => void, rootXPath?: string): Promise; +/** + * `findScrollableElementIds` is a function that identifies elements in + * the browser that are deemed "scrollable". At a high level, it does the + * following: + * - Calls the browser-side `window.getScrollableElementXpaths()` function, + * which returns a list of XPaths for scrollable containers. + * - Iterates over the returned list of XPaths, locating each element in the DOM + * using `stagehandPage.sendCDP(...)` + * - During each iteration, we call `Runtime.evaluate` to run `document.evaluate(...)` + * with each XPath, obtaining a `RemoteObject` reference if it exists. + * - Then, for each valid object reference, we call `DOM.describeNode` to retrieve + * the element’s `backendNodeId`. + * - Collects all resulting `backendNodeId`s in a Set and returns them. + * + * @param stagehandPage - A StagehandPage instance with built-in CDP helpers. + * @returns A Promise that resolves to a Set of unique `backendNodeId`s corresponding + * to scrollable elements in the DOM. + */ +export declare function findScrollableElementIds(stagehandPage: StagehandPage, targetFrame?: Frame): Promise>; +/** + * Resolve an XPath to a Chrome-DevTools-Protocol (CDP) remote-object ID. + * + * @param page A StagehandPage (or Playwright.Page with .sendCDP) + * @param xpath An absolute or relative XPath + * @returns The remote objectId for the matched node, or null + */ +export declare function resolveObjectIdForXPath(page: StagehandPage, xpath: string, targetFrame?: Frame): Promise; +/** + * Resolve a chain of iframe frames from an absolute XPath, returning the frame sequence and inner XPath. + * + * This helper walks an XPath expression containing iframe steps (e.g., '/html/body/iframe[2]/...'), + * descending into each matching iframe element to build a frame chain, and returns the leftover + * XPath segment to evaluate within the context of the last iframe. + * + * @param sp - The StagehandPage instance for evaluating XPath and locating frames. + * @param absPath - An absolute XPath expression starting with '/', potentially including iframe steps. + * @returns An object containing: + * frames: Array of Frame objects representing each iframe in the chain. + * rest: The remaining XPath string to evaluate inside the final iframe. + * @throws Error if an iframe cannot be found or the final XPath cannot be resolved. + */ +export declare function resolveFrameChain(sp: StagehandPage, absPath: string): Promise<{ + frames: Frame[]; + rest: string; +}>; diff --git a/sdk/stagehand-ts/dist/lib/agent/AgentClient.d.ts b/sdk/stagehand-ts/dist/lib/agent/AgentClient.d.ts new file mode 100644 index 0000000..af9a115 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/AgentClient.d.ts @@ -0,0 +1,18 @@ +import { AgentAction, AgentResult, AgentType, AgentExecutionOptions } from "@/types/agent"; +/** + * Abstract base class for agent clients + * This provides a common interface for all agent implementations + */ +export declare abstract class AgentClient { + type: AgentType; + modelName: string; + clientOptions: Record; + userProvidedInstructions?: string; + constructor(type: AgentType, modelName: string, userProvidedInstructions?: string); + abstract execute(options: AgentExecutionOptions): Promise; + abstract captureScreenshot(options?: Record): Promise; + abstract setViewport(width: number, height: number, deviceScaleFactor?: number): void; + abstract setCurrentUrl(url: string): void; + abstract setScreenshotProvider(provider: () => Promise): void; + abstract setActionHandler(handler: (action: AgentAction) => Promise): void; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/AgentProvider.d.ts b/sdk/stagehand-ts/dist/lib/agent/AgentProvider.d.ts new file mode 100644 index 0000000..cff6304 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/AgentProvider.d.ts @@ -0,0 +1,18 @@ +import { LogLine } from "@/types/log"; +import { AgentClient } from "./AgentClient"; +import { AgentType } from "@/types/agent"; +export declare const modelToAgentProviderMap: Record; +/** + * Provider for agent clients + * This class is responsible for creating the appropriate agent client + * based on the provider type + */ +export declare class AgentProvider { + private logger; + /** + * Create a new agent provider + */ + constructor(logger: (message: LogLine) => void); + getClient(modelName: string, clientOptions?: Record, userProvidedInstructions?: string, experimental?: boolean): AgentClient; + static getAgentProvider(modelName: string): AgentType; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/AnthropicCUAClient.d.ts b/sdk/stagehand-ts/dist/lib/agent/AnthropicCUAClient.d.ts new file mode 100644 index 0000000..2698ff2 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/AnthropicCUAClient.d.ts @@ -0,0 +1,54 @@ +import { LogLine } from "@/types/log"; +import { AgentAction, AgentResult, AgentType, AgentExecutionOptions, ToolUseItem, AnthropicMessage, AnthropicContentBlock, AnthropicToolResult } from "@/types/agent"; +import { AgentClient } from "./AgentClient"; +export type ResponseInputItem = AnthropicMessage | AnthropicToolResult; +/** + * Client for Anthropic's Computer Use API + * This implementation uses the official Anthropic Messages API for Computer Use + */ +export declare class AnthropicCUAClient extends AgentClient { + private apiKey; + private baseURL?; + private client; + lastMessageId?: string; + private currentViewport; + private currentUrl?; + private screenshotProvider?; + private actionHandler?; + private thinkingBudget; + private experimental; + constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: Record, experimental?: boolean); + setViewport(width: number, height: number): void; + setCurrentUrl(url: string): void; + setScreenshotProvider(provider: () => Promise): void; + setActionHandler(handler: (action: AgentAction) => Promise): void; + /** + * Execute a task with the Anthropic CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions: AgentExecutionOptions): Promise; + executeStep(inputItems: ResponseInputItem[], logger: (message: LogLine) => void): Promise<{ + actions: AgentAction[]; + message: string; + completed: boolean; + nextInputItems: ResponseInputItem[]; + usage: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; + }>; + private createInitialInputItems; + getAction(inputItems: ResponseInputItem[]): Promise<{ + content: AnthropicContentBlock[]; + id: string; + usage: Record; + }>; + takeAction(toolUseItems: ToolUseItem[], logger: (message: LogLine) => void): Promise; + private convertToolUseToAction; + captureScreenshot(options?: { + base64Image?: string; + currentUrl?: string; + }): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/GoogleCUAClient.d.ts b/sdk/stagehand-ts/dist/lib/agent/GoogleCUAClient.d.ts new file mode 100644 index 0000000..aeba46c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/GoogleCUAClient.d.ts @@ -0,0 +1,62 @@ +import { LogLine } from "../../types/log"; +import { AgentAction, AgentResult, AgentType, AgentExecutionOptions } from "@/types/agent"; +import { AgentClient } from "./AgentClient"; +/** + * Client for Google's Computer Use Assistant API + * This implementation uses the Google Generative AI SDK for Computer Use + */ +export declare class GoogleCUAClient extends AgentClient { + private apiKey; + private client; + private currentViewport; + private currentUrl?; + private screenshotProvider?; + private actionHandler?; + private history; + private environment; + private generateContentConfig; + constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: Record); + setViewport(width: number, height: number): void; + setCurrentUrl(url: string): void; + setScreenshotProvider(provider: () => Promise): void; + setActionHandler(handler: (action: AgentAction) => Promise): void; + /** + * Execute a task with the Google CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions: AgentExecutionOptions): Promise; + /** + * Initialize conversation history with the initial instruction + */ + private initializeHistory; + /** + * Execute a single step of the agent + */ + executeStep(logger: (message: LogLine) => void): Promise<{ + actions: AgentAction[]; + message: string; + completed: boolean; + usage: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; + }>; + /** + * Process the response from Google's API + */ + private processResponse; + /** + * Convert Google function call to Stagehand action + */ + private convertFunctionCallToAction; + /** + * Normalize coordinates from Google's 0-1000 range to actual viewport dimensions + */ + private normalizeCoordinates; + captureScreenshot(options?: { + base64Image?: string; + currentUrl?: string; + }): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/OpenAICUAClient.d.ts b/sdk/stagehand-ts/dist/lib/agent/OpenAICUAClient.d.ts new file mode 100644 index 0000000..7e3853f --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/OpenAICUAClient.d.ts @@ -0,0 +1,62 @@ +import { LogLine } from "../../types/log"; +import { AgentAction, AgentResult, AgentType, AgentExecutionOptions, ResponseInputItem, ResponseItem } from "@/types/agent"; +import { AgentClient } from "./AgentClient"; +/** + * Client for OpenAI's Computer Use Assistant API + * This implementation uses the official OpenAI Responses API for Computer Use + */ +export declare class OpenAICUAClient extends AgentClient { + private apiKey; + private organization?; + private baseURL; + private client; + lastResponseId?: string; + private currentViewport; + private currentUrl?; + private screenshotProvider?; + private actionHandler?; + private reasoningItems; + private environment; + constructor(type: AgentType, modelName: string, userProvidedInstructions?: string, clientOptions?: Record); + setViewport(width: number, height: number): void; + setCurrentUrl(url: string): void; + setScreenshotProvider(provider: () => Promise): void; + setActionHandler(handler: (action: AgentAction) => Promise): void; + /** + * Execute a task with the OpenAI CUA + * This is the main entry point for the agent + * @implements AgentClient.execute + */ + execute(executionOptions: AgentExecutionOptions): Promise; + /** + * Execute a single step of the agent + * This coordinates the flow: Request → Get Action → Execute Action + */ + executeStep(inputItems: ResponseInputItem[], previousResponseId: string | undefined, logger: (message: LogLine) => void): Promise<{ + actions: AgentAction[]; + message: string; + completed: boolean; + nextInputItems: ResponseInputItem[]; + responseId: string; + usage: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; + }>; + private isComputerCallItem; + private isFunctionCallItem; + private createInitialInputItems; + getAction(inputItems: ResponseInputItem[], previousResponseId?: string): Promise<{ + output: ResponseItem[]; + responseId: string; + usage: Record; + }>; + takeAction(output: ResponseItem[], logger: (message: LogLine) => void): Promise; + private convertComputerCallToAction; + private convertFunctionCallToAction; + captureScreenshot(options?: { + base64Image?: string; + currentUrl?: string; + }): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/StagehandAgent.d.ts b/sdk/stagehand-ts/dist/lib/agent/StagehandAgent.d.ts new file mode 100644 index 0000000..c6a2c3b --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/StagehandAgent.d.ts @@ -0,0 +1,15 @@ +import { LogLine } from "@/types/log"; +import { AgentExecuteOptions, AgentResult } from "@/types/agent"; +import { AgentClient } from "./AgentClient"; +/** + * Main interface for agent operations in Stagehand + * This class provides methods for executing tasks with an agent + */ +export declare class StagehandAgent { + private client; + private logger; + constructor(client: AgentClient, logger: (message: LogLine) => void); + execute(optionsOrInstruction: AgentExecuteOptions | string): Promise; + getModelName(): string; + getAgentType(): string; +} diff --git a/sdk/stagehand-ts/dist/lib/agent/utils/cuaKeyMapping.d.ts b/sdk/stagehand-ts/dist/lib/agent/utils/cuaKeyMapping.d.ts new file mode 100644 index 0000000..9a6cdf6 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/utils/cuaKeyMapping.d.ts @@ -0,0 +1,10 @@ +/** + * Universal key mapping utility for converting various key representations + * to Playwright-compatible key names. Used by all CUA clients and handlers. + */ +/** + * Maps a key name from various formats to Playwright-compatible format + * @param key The key name in any supported format + * @returns The Playwright-compatible key name + */ +export declare function mapKeyToPlaywright(key: string): string; diff --git a/sdk/stagehand-ts/dist/lib/agent/utils/imageCompression.d.ts b/sdk/stagehand-ts/dist/lib/agent/utils/imageCompression.d.ts new file mode 100644 index 0000000..af611cc --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/agent/utils/imageCompression.d.ts @@ -0,0 +1,52 @@ +import { AnthropicMessage, AnthropicToolResult, ResponseInputItem as OpenAIResponseInputItem } from "@/types/agent"; +import type { Content as GoogleContent } from "@google/genai"; +export type AnthropicResponseInputItem = AnthropicMessage | AnthropicToolResult; +export type SupportedInputItem = AnthropicResponseInputItem | OpenAIResponseInputItem | GoogleContent; +/** + * Finds all items in the conversation history that contain images (Anthropic format) + * @param items - Array of conversation items to check + * @returns Array of indices where images were found + */ +export declare function findAnthropicItemsWithImages(items: AnthropicResponseInputItem[]): number[]; +/** + * Finds all items in the conversation history that contain images (OpenAI format) + * @param items - Array of conversation items to check + * @returns Array of indices where images were found + */ +export declare function findOpenAIItemsWithImages(items: OpenAIResponseInputItem[]): number[]; +/** + * Finds all items in the conversation history that contain images (Google format) + * @param items - Array of conversation items to check + * @returns Array of indices where images were found + */ +export declare function findGoogleItemsWithImages(items: GoogleContent[]): number[]; +/** + * Compresses Anthropic conversation history by removing images from older items + * while keeping the most recent images intact + * @param items - Array of conversation items to process + * @param keepMostRecentCount - Number of most recent image-containing items to preserve (default: 2) + * @returns Object with processed items + */ +export declare function compressAnthropicConversationImages(items: AnthropicResponseInputItem[], keepMostRecentCount?: number): { + items: AnthropicResponseInputItem[]; +}; +/** + * Compresses OpenAI conversation history by removing images from older items + * while keeping the most recent images intact + * @param items - Array of conversation items to process + * @param keepMostRecentCount - Number of most recent image-containing items to preserve (default: 2) + * @returns Object with processed items + */ +export declare function compressOpenAIConversationImages(items: OpenAIResponseInputItem[], keepMostRecentCount?: number): { + items: OpenAIResponseInputItem[]; +}; +/** + * Compresses Google conversation history by removing images from older items + * while keeping the most recent images intact + * @param items - Array of conversation items to process + * @param keepMostRecentCount - Number of most recent image-containing items to preserve (default: 2) + * @returns Object with processed items + */ +export declare function compressGoogleConversationImages(items: GoogleContent[], keepMostRecentCount?: number): { + items: GoogleContent[]; +}; diff --git a/sdk/stagehand-ts/dist/lib/api.d.ts b/sdk/stagehand-ts/dist/lib/api.d.ts new file mode 100644 index 0000000..6e017c7 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/api.d.ts @@ -0,0 +1,23 @@ +import { z } from "zod/v3"; +import { StagehandAPIConstructorParams, StartSessionParams, StartSessionResult } from "../types/api"; +import { GotoOptions } from "../types/playwright"; +import { ActOptions, ActResult, AgentConfig, ExtractOptions, ExtractResult, ObserveOptions, ObserveResult } from "../types/stagehand"; +import { AgentExecuteOptions, AgentResult } from "."; +export declare class StagehandAPI { + private apiKey; + private projectId; + private sessionId?; + private modelApiKey; + private logger; + private fetchWithCookies; + constructor({ apiKey, projectId, logger }: StagehandAPIConstructorParams); + init({ modelName, modelApiKey, domSettleTimeoutMs, verbose, debugDom, systemPrompt, selfHeal, waitForCaptchaSolves, actionTimeoutMs, browserbaseSessionCreateParams, browserbaseSessionID, }: StartSessionParams): Promise; + act(options: ActOptions | ObserveResult): Promise; + extract(options: ExtractOptions): Promise>; + observe(options?: ObserveOptions): Promise; + goto(url: string, options?: GotoOptions): Promise; + agentExecute(agentConfig: AgentConfig, executeOptions: AgentExecuteOptions): Promise; + end(): Promise; + private execute; + private request; +} diff --git a/sdk/stagehand-ts/dist/lib/cache.d.ts b/sdk/stagehand-ts/dist/lib/cache.d.ts new file mode 100644 index 0000000..9499d3c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/cache.d.ts @@ -0,0 +1,29 @@ +/** + * A file system cache to skip inference when repeating steps + * It also acts as the source of truth for identifying previously seen actions and observations + */ +declare class Cache { + disabled: boolean; + constructor({ disabled }?: { + disabled?: boolean; + }); + readObservations(): any; + readActions(): any; + writeObservations({ key, value, }: { + key: string; + value: { + id: string; + result: string; + }; + }): void; + writeActions({ key, value, }: { + key: string; + value: { + id: string; + result: string; + }; + }): void; + evictCache(): void; + private initCache; +} +export default Cache; diff --git a/sdk/stagehand-ts/dist/lib/cache/ActionCache.d.ts b/sdk/stagehand-ts/dist/lib/cache/ActionCache.d.ts new file mode 100644 index 0000000..d60d901 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/cache/ActionCache.d.ts @@ -0,0 +1,62 @@ +import { LogLine } from "../../types/log"; +import { BaseCache, CacheEntry } from "./BaseCache"; +export interface PlaywrightCommand { + method: string; + args: string[]; +} +export interface ActionEntry extends CacheEntry { + data: { + playwrightCommand: PlaywrightCommand; + componentString: string; + xpaths: string[]; + newStepString: string; + completed: boolean; + previousSelectors: string[]; + action: string; + }; +} +/** + * ActionCache handles logging and retrieving actions along with their Playwright commands. + */ +export declare class ActionCache extends BaseCache { + constructor(logger: (message: LogLine) => void, cacheDir?: string, cacheFile?: string); + addActionStep({ url, action, previousSelectors, playwrightCommand, componentString, xpaths, newStepString, completed, requestId, }: { + url: string; + action: string; + previousSelectors: string[]; + playwrightCommand: PlaywrightCommand; + componentString: string; + requestId: string; + xpaths: string[]; + newStepString: string; + completed: boolean; + }): Promise; + /** + * Retrieves all actions for a specific trajectory. + * @param trajectoryId - Unique identifier for the trajectory. + * @param requestId - The identifier for the current request. + * @returns An array of TrajectoryEntry objects or null if not found. + */ + getActionStep({ url, action, previousSelectors, requestId, }: { + url: string; + action: string; + previousSelectors: string[]; + requestId: string; + }): Promise; + removeActionStep(cacheHashObj: { + url: string; + action: string; + previousSelectors: string[]; + requestId: string; + }): Promise; + /** + * Clears all actions for a specific trajectory. + * @param trajectoryId - Unique identifier for the trajectory. + * @param requestId - The identifier for the current request. + */ + clearAction(requestId: string): Promise; + /** + * Resets the entire action cache. + */ + resetCache(): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/cache/BaseCache.d.ts b/sdk/stagehand-ts/dist/lib/cache/BaseCache.d.ts new file mode 100644 index 0000000..240e60d --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/cache/BaseCache.d.ts @@ -0,0 +1,66 @@ +import { LogLine } from "../../types/log"; +export interface CacheEntry { + timestamp: number; + data: unknown; + requestId: string; +} +export interface CacheStore { + [key: string]: CacheEntry; +} +export declare class BaseCache { + private readonly CACHE_MAX_AGE_MS; + private readonly CLEANUP_PROBABILITY; + protected cacheDir: string; + protected cacheFile: string; + protected lockFile: string; + protected logger: (message: LogLine) => void; + private readonly LOCK_TIMEOUT_MS; + protected lockAcquired: boolean; + protected lockAcquireFailures: number; + protected requestIdToUsedHashes: { + [key: string]: string[]; + }; + constructor(logger: (message: LogLine) => void, cacheDir?: string, cacheFile?: string); + private setupProcessHandlers; + protected ensureCacheDirectory(): void; + protected createHash(data: unknown): string; + protected sleep(ms: number): Promise; + acquireLock(): Promise; + releaseLock(): void; + /** + * Cleans up stale cache entries that exceed the maximum age. + */ + cleanupStaleEntries(): Promise; + protected readCache(): CacheStore; + protected writeCache(cache: CacheStore): void; + /** + * Retrieves data from the cache based on the provided options. + * @param hashObj - The options used to generate the cache key. + * @param requestId - The identifier for the current request. + * @returns The cached data if available, otherwise null. + */ + get(hashObj: Record | string, requestId: string): Promise; + /** + * Stores data in the cache based on the provided options and requestId. + * @param hashObj - The options used to generate the cache key. + * @param data - The data to be cached. + * @param requestId - The identifier for the cache entry. + */ + set(hashObj: Record, data: T["data"], requestId: string): Promise; + delete(hashObj: Record): Promise; + /** + * Tracks the usage of a hash with a specific requestId. + * @param requestId - The identifier for the current request. + * @param hash - The cache key hash. + */ + protected trackRequestIdUsage(requestId: string, hash: string): void; + /** + * Deletes all cache entries associated with a specific requestId. + * @param requestId - The identifier for the request whose cache entries should be deleted. + */ + deleteCacheForRequestId(requestId: string): Promise; + /** + * Resets the entire cache by clearing the cache file. + */ + resetCache(): void; +} diff --git a/sdk/stagehand-ts/dist/lib/cache/LLMCache.d.ts b/sdk/stagehand-ts/dist/lib/cache/LLMCache.d.ts new file mode 100644 index 0000000..533fb94 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/cache/LLMCache.d.ts @@ -0,0 +1,22 @@ +import { BaseCache, CacheEntry } from "./BaseCache"; +export declare class LLMCache extends BaseCache { + constructor(logger: (message: { + category?: string; + message: string; + level?: number; + }) => void, cacheDir?: string, cacheFile?: string); + /** + * Overrides the get method to track used hashes by requestId. + * @param options - The options used to generate the cache key. + * @param requestId - The identifier for the current request. + * @returns The cached data if available, otherwise null. + */ + get(options: Record, requestId: string): Promise; + /** + * Overrides the set method to include cache cleanup logic. + * @param options - The options used to generate the cache key. + * @param data - The data to be cached. + * @param requestId - The identifier for the current request. + */ + set(options: Record, data: unknown, requestId: string): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/dom/build/scriptContent.d.ts b/sdk/stagehand-ts/dist/lib/dom/build/scriptContent.d.ts new file mode 100644 index 0000000..47d446c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/build/scriptContent.d.ts @@ -0,0 +1 @@ +export declare const scriptContent = "(() => {\n // lib/dom/elementCheckUtils.ts\n function isElementNode(node) {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n function isTextNode(node) {\n return node.nodeType === Node.TEXT_NODE && Boolean(node.textContent?.trim());\n }\n\n // lib/dom/xpathUtils.ts\n function getParentElement(node) {\n return isElementNode(node) ? node.parentElement : node.parentNode;\n }\n function getCombinations(attributes, size) {\n const results = [];\n function helper(start, combo) {\n if (combo.length === size) {\n results.push([...combo]);\n return;\n }\n for (let i = start; i < attributes.length; i++) {\n combo.push(attributes[i]);\n helper(i + 1, combo);\n combo.pop();\n }\n }\n helper(0, []);\n return results;\n }\n function isXPathFirstResultElement(xpath, target) {\n try {\n const result = document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n return result.snapshotItem(0) === target;\n } catch (error) {\n console.warn(`Invalid XPath expression: ${xpath}`, error);\n return false;\n }\n }\n function escapeXPathString(value) {\n if (value.includes(\"'\")) {\n if (value.includes('\"')) {\n return \"concat(\" + value.split(/('+)/).map((part) => {\n if (part === \"'\") {\n return `\"'\"`;\n } else if (part.startsWith(\"'\") && part.endsWith(\"'\")) {\n return `\"${part}\"`;\n } else {\n return `'${part}'`;\n }\n }).join(\",\") + \")\";\n } else {\n return `\"${value}\"`;\n }\n } else {\n return `'${value}'`;\n }\n }\n async function generateXPathsForElement(element) {\n if (!element) return [];\n const [complexXPath, standardXPath, idBasedXPath] = await Promise.all([\n generateComplexXPath(element),\n generateStandardXPath(element),\n generatedIdBasedXPath(element)\n ]);\n return [standardXPath, ...idBasedXPath ? [idBasedXPath] : [], complexXPath];\n }\n async function generateComplexXPath(element) {\n const parts = [];\n let currentElement = element;\n while (currentElement && (isTextNode(currentElement) || isElementNode(currentElement))) {\n if (isElementNode(currentElement)) {\n const el = currentElement;\n let selector = el.tagName.toLowerCase();\n const attributePriority = [\n \"data-qa\",\n \"data-component\",\n \"data-role\",\n \"role\",\n \"aria-role\",\n \"type\",\n \"name\",\n \"aria-label\",\n \"placeholder\",\n \"title\",\n \"alt\"\n ];\n const attributes = attributePriority.map((attr) => {\n let value = el.getAttribute(attr);\n if (attr === \"href-full\" && value) {\n value = el.getAttribute(\"href\");\n }\n return value ? { attr: attr === \"href-full\" ? \"href\" : attr, value } : null;\n }).filter((attr) => attr !== null);\n let uniqueSelector = \"\";\n for (let i = 1; i <= attributes.length; i++) {\n const combinations = getCombinations(attributes, i);\n for (const combo of combinations) {\n const conditions = combo.map((a) => `@${a.attr}=${escapeXPathString(a.value)}`).join(\" and \");\n const xpath2 = `//${selector}[${conditions}]`;\n if (isXPathFirstResultElement(xpath2, el)) {\n uniqueSelector = xpath2;\n break;\n }\n }\n if (uniqueSelector) break;\n }\n if (uniqueSelector) {\n parts.unshift(uniqueSelector.replace(\"//\", \"\"));\n break;\n } else {\n const parent = getParentElement(el);\n if (parent) {\n const siblings = Array.from(parent.children).filter(\n (sibling) => sibling.tagName === el.tagName\n );\n const index = siblings.indexOf(el) + 1;\n selector += siblings.length > 1 ? `[${index}]` : \"\";\n }\n parts.unshift(selector);\n }\n }\n currentElement = getParentElement(currentElement);\n }\n const xpath = \"//\" + parts.join(\"/\");\n return xpath;\n }\n async function generateStandardXPath(element) {\n const parts = [];\n while (element && (isTextNode(element) || isElementNode(element))) {\n let index = 0;\n let hasSameTypeSiblings = false;\n const siblings = element.parentElement ? Array.from(element.parentElement.childNodes) : [];\n for (let i = 0; i < siblings.length; i++) {\n const sibling = siblings[i];\n if (sibling.nodeType === element.nodeType && sibling.nodeName === element.nodeName) {\n index = index + 1;\n hasSameTypeSiblings = true;\n if (sibling.isSameNode(element)) {\n break;\n }\n }\n }\n if (element.nodeName !== \"#text\") {\n const tagName = element.nodeName.toLowerCase();\n const pathIndex = hasSameTypeSiblings ? `[${index}]` : \"\";\n parts.unshift(`${tagName}${pathIndex}`);\n }\n element = element.parentElement;\n }\n return parts.length ? `/${parts.join(\"/\")}` : \"\";\n }\n async function generatedIdBasedXPath(element) {\n if (isElementNode(element) && element.id) {\n return `//*[@id='${element.id}']`;\n }\n return null;\n }\n\n // types/stagehandErrors.ts\n var StagehandError = class extends Error {\n constructor(message) {\n super(message);\n this.name = this.constructor.name;\n }\n };\n var StagehandDomProcessError = class extends StagehandError {\n constructor(message) {\n super(`Error Processing Dom: ${message}`);\n }\n };\n\n // lib/dom/utils.ts\n function canElementScroll(elem) {\n if (typeof elem.scrollTo !== \"function\") {\n console.warn(\"canElementScroll: .scrollTo is not a function.\");\n return false;\n }\n try {\n const originalTop = elem.scrollTop;\n elem.scrollTo({\n top: originalTop + 100,\n left: 0,\n behavior: \"instant\"\n });\n if (elem.scrollTop === originalTop) {\n throw new StagehandDomProcessError(\"scrollTop did not change\");\n }\n elem.scrollTo({\n top: originalTop,\n left: 0,\n behavior: \"instant\"\n });\n return true;\n } catch (error) {\n console.warn(\"canElementScroll error:\", error.message || error);\n return false;\n }\n }\n function getNodeFromXpath(xpath) {\n return document.evaluate(\n xpath,\n document.documentElement,\n null,\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null\n ).singleNodeValue;\n }\n function waitForElementScrollEnd(element, idleMs = 100) {\n return new Promise((resolve) => {\n let scrollEndTimer;\n const handleScroll = () => {\n clearTimeout(scrollEndTimer);\n scrollEndTimer = window.setTimeout(() => {\n element.removeEventListener(\"scroll\", handleScroll);\n resolve();\n }, idleMs);\n };\n element.addEventListener(\"scroll\", handleScroll, { passive: true });\n handleScroll();\n });\n }\n\n // lib/dom/process.ts\n function getScrollableElements(topN) {\n const docEl = document.documentElement;\n const scrollableElements = [docEl];\n const allElements = document.querySelectorAll(\"*\");\n for (const elem of allElements) {\n const style = window.getComputedStyle(elem);\n const overflowY = style.overflowY;\n const isPotentiallyScrollable = overflowY === \"auto\" || overflowY === \"scroll\" || overflowY === \"overlay\";\n if (isPotentiallyScrollable) {\n const candidateScrollDiff = elem.scrollHeight - elem.clientHeight;\n if (candidateScrollDiff > 0 && canElementScroll(elem)) {\n scrollableElements.push(elem);\n }\n }\n }\n scrollableElements.sort((a, b) => b.scrollHeight - a.scrollHeight);\n if (topN !== void 0) {\n return scrollableElements.slice(0, topN);\n }\n return scrollableElements;\n }\n async function getScrollableElementXpaths(topN) {\n const scrollableElems = getScrollableElements(topN);\n const xpaths = [];\n for (const elem of scrollableElems) {\n const allXPaths = await generateXPathsForElement(elem);\n const firstXPath = allXPaths?.[0] || \"\";\n xpaths.push(firstXPath);\n }\n return xpaths;\n }\n (() => {\n const closedRoots = /* @__PURE__ */ new WeakMap();\n const nativeAttachShadow = Element.prototype.attachShadow;\n Element.prototype.attachShadow = function(init) {\n const root = nativeAttachShadow.call(this, init);\n if (init.mode === \"closed\") closedRoots.set(this, root);\n return root;\n };\n const backdoor = {\n getClosedRoot: (host) => closedRoots.get(host),\n queryClosed: (host, selector) => {\n const root = closedRoots.get(host);\n return root ? Array.from(root.querySelectorAll(selector)) : [];\n },\n xpathClosed: (host, xp) => {\n const root = closedRoots.get(host);\n if (!root) return [];\n const it = document.evaluate(\n xp,\n root,\n null,\n XPathResult.ORDERED_NODE_SNAPSHOT_TYPE,\n null\n );\n const out = [];\n for (let i = 0; i < it.snapshotLength; ++i) {\n const n = it.snapshotItem(i);\n if (n) out.push(n);\n }\n return out;\n }\n };\n if (!(\"__stagehand__\" in window)) {\n Object.defineProperty(window, \"__stagehand__\", {\n value: backdoor,\n enumerable: false,\n writable: false,\n configurable: false\n });\n }\n })();\n window.getScrollableElementXpaths = getScrollableElementXpaths;\n window.getNodeFromXpath = getNodeFromXpath;\n window.waitForElementScrollEnd = waitForElementScrollEnd;\n})();\n"; diff --git a/sdk/stagehand-ts/dist/lib/dom/elementCheckUtils.d.ts b/sdk/stagehand-ts/dist/lib/dom/elementCheckUtils.d.ts new file mode 100644 index 0000000..6a69f67 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/elementCheckUtils.d.ts @@ -0,0 +1,2 @@ +export declare function isElementNode(node: Node): node is Element; +export declare function isTextNode(node: Node): node is Text; diff --git a/sdk/stagehand-ts/dist/lib/dom/genDomScripts.d.ts b/sdk/stagehand-ts/dist/lib/dom/genDomScripts.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/genDomScripts.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/lib/dom/index.d.ts b/sdk/stagehand-ts/dist/lib/dom/index.d.ts new file mode 100644 index 0000000..96b5321 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/index.d.ts @@ -0,0 +1,2 @@ +export * from "./process"; +export * from "./utils"; diff --git a/sdk/stagehand-ts/dist/lib/dom/process.d.ts b/sdk/stagehand-ts/dist/lib/dom/process.d.ts new file mode 100644 index 0000000..bb3ca92 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/process.d.ts @@ -0,0 +1,17 @@ +/** + * Finds and returns a list of scrollable elements on the page, + * ordered from the element with the largest scrollHeight to the smallest. + * + * @param topN Optional maximum number of scrollable elements to return. + * If not provided, all found scrollable elements are returned. + * @returns An array of HTMLElements sorted by descending scrollHeight. + */ +export declare function getScrollableElements(topN?: number): HTMLElement[]; +/** + * Calls getScrollableElements, then for each element calls generateXPaths, + * and returns the first XPath for each. + * + * @param topN (optional) integer limit on how many scrollable elements to process + * @returns string[] list of XPaths (1 for each scrollable element) + */ +export declare function getScrollableElementXpaths(topN?: number): Promise; diff --git a/sdk/stagehand-ts/dist/lib/dom/utils.d.ts b/sdk/stagehand-ts/dist/lib/dom/utils.d.ts new file mode 100644 index 0000000..edcf12f --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/utils.d.ts @@ -0,0 +1,7 @@ +/** + * Tests if the element actually responds to .scrollTo(...) + * and that scrollTop changes as expected. + */ +export declare function canElementScroll(elem: HTMLElement): boolean; +export declare function getNodeFromXpath(xpath: string): Node; +export declare function waitForElementScrollEnd(element: HTMLElement, idleMs?: number): Promise; diff --git a/sdk/stagehand-ts/dist/lib/dom/xpathUtils.d.ts b/sdk/stagehand-ts/dist/lib/dom/xpathUtils.d.ts new file mode 100644 index 0000000..e898c1f --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/dom/xpathUtils.d.ts @@ -0,0 +1,14 @@ +/** + * Escapes a string for use in an XPath expression. + * Handles special characters, including single and double quotes. + * @param value - The string to escape. + * @returns The escaped string safe for XPath. + */ +export declare function escapeXPathString(value: string): string; +/** + * Generates both a complicated XPath and a standard XPath for a given DOM element. + * @param element - The target DOM element. + * @param documentOverride - Optional document override. + * @returns An object containing both XPaths. + */ +export declare function generateXPathsForElement(element: ChildNode): Promise; diff --git a/sdk/stagehand-ts/dist/lib/handlers/actHandler.d.ts b/sdk/stagehand-ts/dist/lib/handlers/actHandler.d.ts new file mode 100644 index 0000000..a9c189b --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/actHandler.d.ts @@ -0,0 +1,33 @@ +import { LogLine } from "../../types/log"; +import { LLMClient } from "../llm/LLMClient"; +import { StagehandPage } from "../StagehandPage"; +import { ActResult, ObserveResult, ActOptions } from "@/types/stagehand"; +import { StagehandObserveHandler } from "@/lib/handlers/observeHandler"; +/** + * NOTE: Vision support has been removed from this version of Stagehand. + * If useVision or verifierUseVision is set to true, a warning is logged and + * the flow continues as if vision = false. + */ +export declare class StagehandActHandler { + private readonly stagehandPage; + private readonly logger; + private readonly selfHeal; + private readonly experimental; + constructor({ logger, stagehandPage, selfHeal, experimental, }: { + logger: (logLine: LogLine) => void; + stagehandPage: StagehandPage; + selfHeal: boolean; + experimental: boolean; + }); + /** + * Perform an immediate Playwright action based on an ObserveResult object + * that was returned from `page.observe(...)`. + */ + actFromObserveResult(observe: ObserveResult, domSettleTimeoutMs?: number): Promise; + /** + * Perform an act based on an instruction. + * This method will observe the page and then perform the act on the first element returned. + */ + observeAct(actionOrOptions: ActOptions, observeHandler: StagehandObserveHandler, llmClient: LLMClient, requestId: string): Promise; + private _performPlaywrightMethod; +} diff --git a/sdk/stagehand-ts/dist/lib/handlers/agentHandler.d.ts b/sdk/stagehand-ts/dist/lib/handlers/agentHandler.d.ts new file mode 100644 index 0000000..4d8c891 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/agentHandler.d.ts @@ -0,0 +1,52 @@ +import { StagehandPage } from "../StagehandPage"; +import { StagehandAgent } from "../agent/StagehandAgent"; +import { AgentClient } from "../agent/AgentClient"; +import { LogLine } from "../../types/log"; +import { AgentExecuteOptions, AgentResult, AgentHandlerOptions } from "@/types/agent"; +import { Stagehand } from "../index"; +export declare class StagehandAgentHandler { + private stagehand; + private stagehandPage; + private agent; + private provider; + private logger; + private agentClient; + private options; + private screenshotCollector?; + constructor(stagehand: Stagehand, stagehandPage: StagehandPage, logger: (message: LogLine) => void, options: AgentHandlerOptions); + private setupAgentClient; + /** + * Execute a task with the agent + */ + execute(optionsOrInstruction: AgentExecuteOptions | string): Promise; + /** + * Execute a single action on the page + */ + private executeAction; + private updateClientViewport; + private updateClientUrl; + getAgent(): StagehandAgent; + getClient(): AgentClient; + captureAndSendScreenshot(): Promise; + /** + * Inject a cursor element into the page for visual feedback + */ + private injectCursor; + /** + * Update the cursor position on the page + */ + private updateCursorPosition; + /** + * Animate a click at the given position + */ + private animateClick; + private get page(); + /** + * Set the screenshot collector for this agent handler + */ + setScreenshotCollector(collector: any): void; + /** + * Get the screenshot collector + */ + getScreenshotCollector(): any; +} diff --git a/sdk/stagehand-ts/dist/lib/handlers/extractHandler.d.ts b/sdk/stagehand-ts/dist/lib/handlers/extractHandler.d.ts new file mode 100644 index 0000000..97606a7 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/extractHandler.d.ts @@ -0,0 +1,54 @@ +import { z } from "zod/v3"; +import { ZodPathSegments } from "../../types/stagehand"; +import { LLMClient } from "../llm/LLMClient"; +import { StagehandPage } from "../StagehandPage"; +import { Stagehand } from "../index"; +export declare class StagehandExtractHandler { + private readonly stagehand; + private readonly stagehandPage; + private readonly logger; + private readonly userProvidedInstructions?; + private readonly experimental; + constructor({ stagehand, logger, stagehandPage, userProvidedInstructions, experimental, }: { + stagehand: Stagehand; + logger: (message: { + category?: string; + message: string; + level?: number; + auxiliary?: { + [key: string]: { + value: string; + type: string; + }; + }; + }) => void; + stagehandPage: StagehandPage; + userProvidedInstructions?: string; + experimental: boolean; + }); + extract({ instruction, schema, content, llmClient, requestId, domSettleTimeoutMs, useTextExtract, selector, iframes, }?: { + instruction?: string; + schema?: T; + content?: z.infer; + chunksSeen?: Array; + llmClient?: LLMClient; + requestId?: string; + domSettleTimeoutMs?: number; + useTextExtract?: boolean; + selector?: string; + iframes?: boolean; + }): Promise>; + private extractPageText; + private domExtract; +} +/** + * Scans the provided Zod schema for any `z.string().url()` fields and + * replaces them with `z.number()`. + * + * @param schema - The Zod object schema to transform. + * @returns A tuple containing: + * 1. The transformed schema (or the original schema if no changes were needed). + * 2. An array of {@link ZodPathSegments} objects representing all the replaced URL fields, + * with each path segment showing where in the schema the replacement occurred. + */ +export declare function transformUrlStringsToNumericIds>(schema: T): [T, ZodPathSegments[]]; diff --git a/sdk/stagehand-ts/dist/lib/handlers/handlerUtils/actHandlerUtils.d.ts b/sdk/stagehand-ts/dist/lib/handlers/handlerUtils/actHandlerUtils.d.ts new file mode 100644 index 0000000..c100ca4 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/handlerUtils/actHandlerUtils.d.ts @@ -0,0 +1,21 @@ +import { Page, Locator, FrameLocator } from "playwright"; +import { MethodHandlerContext } from "@/types/act"; +export declare function deepLocatorWithShadow(root: Page | FrameLocator, xpath: string): Promise; +export declare function deepLocator(root: Page | FrameLocator, xpath: string): Locator; +/** + * A mapping of playwright methods that may be chosen by the LLM to their + * implementation. + */ +export declare const methodHandlerMap: Record Promise>; +export declare function scrollToNextChunk(ctx: MethodHandlerContext): Promise; +export declare function scrollToPreviousChunk(ctx: MethodHandlerContext): Promise; +export declare function scrollElementIntoView(ctx: MethodHandlerContext): Promise; +export declare function scrollElementToPercentage(ctx: MethodHandlerContext): Promise; +export declare function fillOrType(ctx: MethodHandlerContext): Promise; +export declare function pressKey(ctx: MethodHandlerContext): Promise; +export declare function selectOption(ctx: MethodHandlerContext): Promise; +export declare function clickElement(ctx: MethodHandlerContext): Promise; +/** + * Fallback method: if method is not in our map but *is* a valid Playwright locator method. + */ +export declare function fallbackLocatorMethod(ctx: MethodHandlerContext): Promise; diff --git a/sdk/stagehand-ts/dist/lib/handlers/observeHandler.d.ts b/sdk/stagehand-ts/dist/lib/handlers/observeHandler.d.ts new file mode 100644 index 0000000..0479a6b --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/observeHandler.d.ts @@ -0,0 +1,40 @@ +import { LogLine } from "../../types/log"; +import { Stagehand } from "../index"; +import { LLMClient } from "../llm/LLMClient"; +import { StagehandPage } from "../StagehandPage"; +export declare class StagehandObserveHandler { + private readonly stagehand; + private readonly logger; + private readonly stagehandPage; + private readonly experimental; + private readonly userProvidedInstructions?; + constructor({ stagehand, logger, stagehandPage, userProvidedInstructions, experimental, }: { + stagehand: Stagehand; + logger: (logLine: LogLine) => void; + stagehandPage: StagehandPage; + userProvidedInstructions?: string; + experimental: boolean; + }); + observe({ instruction, llmClient, requestId, returnAction, onlyVisible, drawOverlay, fromAct, iframes, }: { + instruction: string; + llmClient: LLMClient; + requestId: string; + domSettleTimeoutMs?: number; + returnAction?: boolean; + /** + * @deprecated The `onlyVisible` parameter has no effect in this version of Stagehand and will be removed in later versions. + */ + onlyVisible?: boolean; + drawOverlay?: boolean; + fromAct?: boolean; + iframes?: boolean; + }): Promise<({ + selector: string; + description: string; + } | { + selector: string; + method: string; + arguments: string[]; + description: string; + })[]>; +} diff --git a/sdk/stagehand-ts/dist/lib/handlers/operatorHandler.d.ts b/sdk/stagehand-ts/dist/lib/handlers/operatorHandler.d.ts new file mode 100644 index 0000000..ca26752 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/handlers/operatorHandler.d.ts @@ -0,0 +1,15 @@ +import { AgentExecuteOptions, AgentResult } from "@/types/agent"; +import { LogLine } from "@/types/log"; +import { LLMClient } from "../llm/LLMClient"; +import { StagehandPage } from "../StagehandPage"; +export declare class StagehandOperatorHandler { + private stagehandPage; + private logger; + private llmClient; + private messages; + constructor(stagehandPage: StagehandPage, logger: (message: LogLine) => void, llmClient: LLMClient); + execute(instructionOrOptions: string | AgentExecuteOptions): Promise; + private getNextStep; + private getSummary; + private executeAction; +} diff --git a/sdk/stagehand-ts/dist/lib/index.d.ts b/sdk/stagehand-ts/dist/lib/index.d.ts new file mode 100644 index 0000000..686da45 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/index.d.ts @@ -0,0 +1,91 @@ +import { EnhancedContext } from "../types/context"; +import { LogLine } from "../types/log"; +import { Page } from "../types/page"; +import { ConstructorParams, InitResult, AgentConfig, StagehandMetrics, StagehandFunctionName, HistoryEntry, ActOptions, ExtractOptions, ObserveOptions } from "../types/stagehand"; +import { StagehandPage } from "./StagehandPage"; +import { StagehandAPI } from "./api"; +import { LLMClient } from "./llm/LLMClient"; +import { LLMProvider } from "./llm/LLMProvider"; +import { AgentExecuteOptions, AgentResult } from "../types/agent"; +import { z } from "zod/v3"; +import { GotoOptions } from "@/types/playwright"; +export declare class Stagehand { + private stagehandPage; + private stagehandContext; + browserbaseSessionID?: string; + readonly domSettleTimeoutMs: number; + readonly debugDom: boolean; + readonly headless: boolean; + verbose: 0 | 1 | 2; + llmProvider: LLMProvider; + enableCaching: boolean; + protected apiKey: string | undefined; + private projectId; + private externalLogger?; + private browserbaseSessionCreateParams?; + variables: { + [key: string]: unknown; + }; + private contextPath?; + llmClient: LLMClient; + readonly userProvidedInstructions?: string; + private usingAPI; + private modelName; + apiClient: StagehandAPI | undefined; + readonly waitForCaptchaSolves: boolean; + private localBrowserLaunchOptions?; + readonly selfHeal: boolean; + private cleanupCalled; + readonly actTimeoutMs: number; + readonly logInferenceToFile?: boolean; + private stagehandLogger; + private disablePino; + private modelClientOptions; + private _env; + private _browser; + private _isClosed; + private _history; + readonly experimental: boolean; + private _livePageProxy?; + private createLivePageProxy; + get history(): ReadonlyArray; + protected setActivePage(page: StagehandPage): void; + get page(): Page; + stagehandMetrics: StagehandMetrics; + get metrics(): StagehandMetrics; + get isClosed(): boolean; + updateMetrics(functionName: StagehandFunctionName, promptTokens: number, completionTokens: number, inferenceTimeMs: number): void; + private updateTotalMetrics; + constructor({ env, apiKey, projectId, verbose, llmProvider, llmClient, logger, browserbaseSessionCreateParams, domSettleTimeoutMs, enableCaching, browserbaseSessionID, modelName, modelClientOptions, systemPrompt, useAPI, localBrowserLaunchOptions, waitForCaptchaSolves, logInferenceToFile, selfHeal, disablePino, experimental, }?: ConstructorParams); + private registerSignalHandlers; + get logger(): (logLine: LogLine) => void; + get env(): "LOCAL" | "BROWSERBASE"; + get downloadsPath(): string; + get context(): EnhancedContext; + init(): Promise; + log(logObj: LogLine): void; + close(): Promise; + addToHistory(method: HistoryEntry["method"], parameters: ActOptions | ExtractOptions | ObserveOptions | { + url: string; + options: GotoOptions; + } | string, result?: unknown): void; + /** + * Create an agent instance that can be executed with different instructions + * @returns An agent instance with execute() and setViewport() methods + */ + agent(options?: AgentConfig): { + execute: (instructionOrOptions: string | AgentExecuteOptions) => Promise; + setScreenshotCollector?: (collector: unknown) => void; + }; +} +export * from "../types/browser"; +export * from "../types/log"; +export * from "../types/model"; +export * from "../types/page"; +export * from "../types/playwright"; +export * from "../types/stagehand"; +export * from "../types/operator"; +export * from "../types/agent"; +export * from "./llm/LLMClient"; +export * from "../types/stagehandErrors"; +export * from "../types/stagehandApiErrors"; diff --git a/sdk/stagehand-ts/dist/lib/inference.d.ts b/sdk/stagehand-ts/dist/lib/inference.d.ts new file mode 100644 index 0000000..ed2f41f --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/inference.d.ts @@ -0,0 +1,61 @@ +import { z } from "zod/v3"; +import { LogLine } from "../types/log"; +import { LLMClient } from "./llm/LLMClient"; +/** Simple usage shape if your LLM returns usage tokens. */ +interface LLMUsage { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; +} +/** + * For calls that use a schema: the LLMClient may return { data: T; usage?: LLMUsage } + */ +export interface LLMParsedResponse { + data: T; + usage?: LLMUsage; +} +export declare function extract({ instruction, domElements, schema, llmClient, chunksSeen, chunksTotal, requestId, logger, userProvidedInstructions, logInferenceToFile, }: { + instruction: string; + domElements: string; + schema: z.ZodObject; + llmClient: LLMClient; + chunksSeen: number; + chunksTotal: number; + requestId: string; + userProvidedInstructions?: string; + logger: (message: LogLine) => void; + logInferenceToFile?: boolean; +}): Promise<{ + metadata: { + completed: boolean; + progress: string; + }; + prompt_tokens: number; + completion_tokens: number; + inference_time_ms: number; +}>; +export declare function observe({ instruction, domElements, llmClient, requestId, userProvidedInstructions, logger, returnAction, logInferenceToFile, fromAct, }: { + instruction: string; + domElements: string; + llmClient: LLMClient; + requestId: string; + userProvidedInstructions?: string; + logger: (message: LogLine) => void; + returnAction?: boolean; + logInferenceToFile?: boolean; + fromAct?: boolean; +}): Promise<{ + elements: ({ + elementId: string; + description: string; + } | { + method: string; + arguments: string[]; + elementId: string; + description: string; + })[]; + prompt_tokens: number; + completion_tokens: number; + inference_time_ms: number; +}>; +export {}; diff --git a/sdk/stagehand-ts/dist/lib/inferenceLogUtils.d.ts b/sdk/stagehand-ts/dist/lib/inferenceLogUtils.d.ts new file mode 100644 index 0000000..7a2fb10 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/inferenceLogUtils.d.ts @@ -0,0 +1,12 @@ +/** + * Appends a new entry to the act_summary.json file, then writes the file back out. + */ +export declare function appendSummary(inferenceType: string, entry: T): void; +/** + * Writes `data` as JSON into a file in `directory`, using a prefix plus timestamp. + * Returns both the file name and the timestamp used, so you can log them. + */ +export declare function writeTimestampedTxtFile(directory: string, prefix: string, data: unknown): { + fileName: string; + timestamp: string; +}; diff --git a/sdk/stagehand-ts/dist/lib/llm/AnthropicClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/AnthropicClient.d.ts new file mode 100644 index 0000000..519c339 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/AnthropicClient.d.ts @@ -0,0 +1,21 @@ +import { ClientOptions } from "@anthropic-ai/sdk"; +import { LogLine } from "../../types/log"; +import { AvailableModel } from "../../types/model"; +import { LLMCache } from "../cache/LLMCache"; +import { CreateChatCompletionOptions, LLMClient, LLMResponse } from "./LLMClient"; +export declare class AnthropicClient extends LLMClient { + type: "anthropic"; + private client; + private cache; + private enableCaching; + clientOptions: ClientOptions; + constructor({ enableCaching, cache, modelName, clientOptions, userProvidedInstructions, }: { + logger: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + modelName: AvailableModel; + clientOptions?: ClientOptions; + userProvidedInstructions?: string; + }); + createChatCompletion({ options, retries, logger, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/CerebrasClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/CerebrasClient.d.ts new file mode 100644 index 0000000..58803d0 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/CerebrasClient.d.ts @@ -0,0 +1,22 @@ +import type { ClientOptions } from "openai"; +import { LogLine } from "../../types/log"; +import { AvailableModel } from "../../types/model"; +import { LLMCache } from "../cache/LLMCache"; +import { CreateChatCompletionOptions, LLMClient, LLMResponse } from "./LLMClient"; +export declare class CerebrasClient extends LLMClient { + type: "cerebras"; + private client; + private cache; + private enableCaching; + clientOptions: ClientOptions; + hasVision: boolean; + constructor({ enableCaching, cache, modelName, clientOptions, userProvidedInstructions, }: { + logger: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + modelName: AvailableModel; + clientOptions?: ClientOptions; + userProvidedInstructions?: string; + }); + createChatCompletion({ options, retries, logger, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/GoogleClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/GoogleClient.d.ts new file mode 100644 index 0000000..b4a4b3c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/GoogleClient.d.ts @@ -0,0 +1,24 @@ +import { LogLine } from "../../types/log"; +import { AvailableModel, ClientOptions } from "../../types/model"; +import { LLMCache } from "../cache/LLMCache"; +import { CreateChatCompletionOptions, LLMClient, LLMResponse } from "./LLMClient"; +export declare class GoogleClient extends LLMClient { + type: "google"; + private client; + private cache; + private enableCaching; + clientOptions: ClientOptions; + hasVision: boolean; + private logger; + constructor({ logger, // Added logger based on other clients + enableCaching, cache, modelName, clientOptions, }: { + logger: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + modelName: AvailableModel; + clientOptions?: ClientOptions; + }); + private formatMessages; + private formatTools; + createChatCompletion({ options, logger, retries, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/GroqClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/GroqClient.d.ts new file mode 100644 index 0000000..b02885e --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/GroqClient.d.ts @@ -0,0 +1,22 @@ +import type { ClientOptions } from "openai"; +import { LogLine } from "../../types/log"; +import { AvailableModel } from "../../types/model"; +import { LLMCache } from "../cache/LLMCache"; +import { CreateChatCompletionOptions, LLMClient, LLMResponse } from "./LLMClient"; +export declare class GroqClient extends LLMClient { + type: "groq"; + private client; + private cache; + private enableCaching; + clientOptions: ClientOptions; + hasVision: boolean; + constructor({ enableCaching, cache, modelName, clientOptions, userProvidedInstructions, }: { + logger: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + modelName: AvailableModel; + clientOptions?: ClientOptions; + userProvidedInstructions?: string; + }); + createChatCompletion({ options, retries, logger, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/LLMClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/LLMClient.d.ts new file mode 100644 index 0000000..d5e2ace --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/LLMClient.d.ts @@ -0,0 +1,98 @@ +import { ZodType } from "zod/v3"; +import { LLMTool } from "../../types/llm"; +import { LogLine } from "../../types/log"; +import { AvailableModel, ClientOptions } from "../../types/model"; +import { generateObject, generateText, streamText, streamObject, experimental_generateImage, embed, embedMany, experimental_transcribe, experimental_generateSpeech } from "ai"; +export interface ChatMessage { + role: "system" | "user" | "assistant"; + content: ChatMessageContent; +} +export type ChatMessageContent = string | (ChatMessageImageContent | ChatMessageTextContent)[]; +export interface ChatMessageImageContent { + type: string; + image_url?: { + url: string; + }; + text?: string; + source?: { + type: string; + media_type: string; + data: string; + }; +} +export interface ChatMessageTextContent { + type: string; + text: string; +} +export declare const AnnotatedScreenshotText = "This is a screenshot of the current page state with the elements annotated on it. Each element id is annotated with a number to the top left of it. Duplicate annotations at the same location are under each other vertically."; +export interface ChatCompletionOptions { + messages: ChatMessage[]; + temperature?: number; + top_p?: number; + frequency_penalty?: number; + presence_penalty?: number; + image?: { + buffer: Buffer; + description?: string; + }; + response_model?: { + name: string; + schema: ZodType; + }; + tools?: LLMTool[]; + tool_choice?: "auto" | "none" | "required"; + maxTokens?: number; + requestId?: string; +} +export type LLMResponse = { + id: string; + object: string; + created: number; + model: string; + choices: { + index: number; + message: { + role: string; + content: string | null; + tool_calls: { + id: string; + type: string; + function: { + name: string; + arguments: string; + }; + }[]; + }; + finish_reason: string; + }[]; + usage: { + prompt_tokens: number; + completion_tokens: number; + total_tokens: number; + }; +}; +export interface CreateChatCompletionOptions { + options: ChatCompletionOptions; + logger: (message: LogLine) => void; + retries?: number; +} +export declare abstract class LLMClient { + type: "openai" | "anthropic" | "cerebras" | "groq" | (string & {}); + modelName: AvailableModel | (string & {}); + hasVision: boolean; + clientOptions: ClientOptions; + userProvidedInstructions?: string; + constructor(modelName: AvailableModel, userProvidedInstructions?: string); + abstract createChatCompletion(options: CreateChatCompletionOptions): Promise; + generateObject: typeof generateObject; + generateText: typeof generateText; + streamText: typeof streamText; + streamObject: typeof streamObject; + generateImage: typeof experimental_generateImage; + embed: typeof embed; + embedMany: typeof embedMany; + transcribe: typeof experimental_transcribe; + generateSpeech: typeof experimental_generateSpeech; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/LLMProvider.d.ts b/sdk/stagehand-ts/dist/lib/llm/LLMProvider.d.ts new file mode 100644 index 0000000..093531a --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/LLMProvider.d.ts @@ -0,0 +1,13 @@ +import { LogLine } from "../../types/log"; +import { AvailableModel, ClientOptions, ModelProvider } from "../../types/model"; +import { LLMClient } from "./LLMClient"; +export declare function getAISDKLanguageModel(subProvider: string, subModelName: string, apiKey?: string): import("ai/dist").LanguageModelV1; +export declare class LLMProvider { + private logger; + private enableCaching; + private cache; + constructor(logger: (message: LogLine) => void, enableCaching: boolean); + cleanRequestCache(requestId: string): void; + getClient(modelName: AvailableModel, clientOptions?: ClientOptions): LLMClient; + static getModelProvider(modelName: AvailableModel): ModelProvider; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/OpenAIClient.d.ts b/sdk/stagehand-ts/dist/lib/llm/OpenAIClient.d.ts new file mode 100644 index 0000000..4f2cc32 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/OpenAIClient.d.ts @@ -0,0 +1,20 @@ +import { ClientOptions } from "openai"; +import { LogLine } from "../../types/log"; +import { AvailableModel } from "../../types/model"; +import { LLMCache } from "../cache/LLMCache"; +import { CreateChatCompletionOptions, LLMClient, LLMResponse } from "./LLMClient"; +export declare class OpenAIClient extends LLMClient { + type: "openai"; + private client; + private cache; + private enableCaching; + clientOptions: ClientOptions; + constructor({ enableCaching, cache, modelName, clientOptions, }: { + logger: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + modelName: AvailableModel; + clientOptions?: ClientOptions; + }); + createChatCompletion({ options: optionsInitial, logger, retries, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/llm/aisdk.d.ts b/sdk/stagehand-ts/dist/lib/llm/aisdk.d.ts new file mode 100644 index 0000000..9863bc7 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/llm/aisdk.d.ts @@ -0,0 +1,19 @@ +import { LanguageModel } from "ai"; +import { CreateChatCompletionOptions, LLMClient } from "./LLMClient"; +import { LogLine } from "../../types/log"; +import { ChatCompletion } from "openai/resources"; +import { LLMCache } from "../cache/LLMCache"; +export declare class AISdkClient extends LLMClient { + type: "aisdk"; + private model; + private logger?; + private cache; + private enableCaching; + constructor({ model, logger, enableCaching, cache, }: { + model: LanguageModel; + logger?: (message: LogLine) => void; + enableCaching?: boolean; + cache?: LLMCache; + }); + createChatCompletion({ options, }: CreateChatCompletionOptions): Promise; +} diff --git a/sdk/stagehand-ts/dist/lib/logger.d.ts b/sdk/stagehand-ts/dist/lib/logger.d.ts new file mode 100644 index 0000000..3e0219a --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/logger.d.ts @@ -0,0 +1,54 @@ +import pino from "pino"; +import { LogLine } from "../types/log"; +export interface LoggerOptions { + pretty?: boolean; + level?: pino.Level; + destination?: pino.DestinationStream; + usePino?: boolean; +} +/** + * Creates a configured Pino logger instance + */ +export declare function createLogger(options?: LoggerOptions): import("pino/pino").Logger; +/** + * StagehandLogger class that wraps Pino for our specific needs + */ +export declare class StagehandLogger { + /** + * We maintain a single shared Pino instance when `usePino` is enabled. + * This prevents spawning a new worker thread for every Stagehand instance + * (which happens when `pino-pretty` transport is used), eliminating the + * memory/RSS growth observed when many Stagehand objects are created and + * disposed within the same process (e.g. a request-per-instance API). + */ + private static sharedPinoLogger; + private logger?; + private verbose; + private externalLogger?; + private usePino; + private isTest; + constructor(options?: LoggerOptions, externalLogger?: (logLine: LogLine) => void); + /** + * Set the verbosity level + */ + setVerbosity(level: 0 | 1 | 2): void; + /** + * Log a message using our LogLine format + */ + log(logLine: LogLine): void; + /** + * Helper to format auxiliary data for structured logging + */ + private formatAuxiliaryData; + /** + * Convenience methods for different log levels + */ + error(message: string, data?: Record): void; + warn(message: string, data?: Record): void; + info(message: string, data?: Record): void; + debug(message: string, data?: Record): void; + /** + * Convert a plain object to our auxiliary format + */ + private convertToAuxiliary; +} diff --git a/sdk/stagehand-ts/dist/lib/prompt.d.ts b/sdk/stagehand-ts/dist/lib/prompt.d.ts new file mode 100644 index 0000000..ee8614c --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/prompt.d.ts @@ -0,0 +1,14 @@ +import { ChatMessage } from "./llm/LLMClient"; +export declare function buildUserInstructionsString(userProvidedInstructions?: string): string; +export declare function buildExtractSystemPrompt(isUsingPrintExtractedDataTool?: boolean, userProvidedInstructions?: string): ChatMessage; +export declare function buildExtractUserPrompt(instruction: string, domElements: string, isUsingPrintExtractedDataTool?: boolean): ChatMessage; +export declare function buildMetadataSystemPrompt(): ChatMessage; +export declare function buildMetadataPrompt(instruction: string, extractionResponse: object, chunksSeen: number, chunksTotal: number): ChatMessage; +export declare function buildObserveSystemPrompt(userProvidedInstructions?: string): ChatMessage; +export declare function buildObserveUserMessage(instruction: string, domElements: string): ChatMessage; +/** + * Builds the instruction for the observeAct method to find the most relevant element for an action + */ +export declare function buildActObservePrompt(action: string, supportedActions: string[], variables?: Record): string; +export declare function buildOperatorSystemPrompt(goal: string): ChatMessage; +export declare function buildGoogleCUASystemPrompt(): ChatMessage; diff --git a/sdk/stagehand-ts/dist/lib/utils.d.ts b/sdk/stagehand-ts/dist/lib/utils.d.ts new file mode 100644 index 0000000..90502c4 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/utils.d.ts @@ -0,0 +1,49 @@ +import { z } from "zod/v3"; +import { ObserveResult, Page } from "."; +import { LogLine } from "../types/log"; +import { ZodPathSegments } from "../types/stagehand"; +import { Schema } from "@google/genai"; +import { ModelProvider } from "../types/model"; +export declare function validateZodSchema(schema: z.ZodTypeAny, data: unknown): boolean; +export declare function drawObserveOverlay(page: Page, results: ObserveResult[]): Promise; +export declare function clearOverlays(page: Page): Promise; +/** + * Detects if the code is running in the Bun runtime environment. + * @returns {boolean} True if running in Bun, false otherwise. + */ +export declare function isRunningInBun(): boolean; +export declare function toGeminiSchema(zodSchema: z.ZodTypeAny): Schema; +export declare function getZodType(schema: z.ZodTypeAny): string; +/** + * Recursively traverses a given Zod schema, scanning for any fields of type `z.string().url()`. + * For each such field, it replaces the `z.string().url()` with `z.number()`. + * + * This function is used internally by higher-level utilities (e.g., transforming entire object schemas) + * and handles nested objects, arrays, unions, intersections, optionals. + * + * @param schema - The Zod schema to transform. + * @param currentPath - An array of string/number keys representing the current schema path (used internally for recursion). + * @returns A two-element tuple: + * 1. The updated Zod schema, with any `.url()` fields replaced by `z.number()`. + * 2. An array of {@link ZodPathSegments} objects representing each replaced field, including the path segments. + */ +export declare function transformSchema(schema: z.ZodTypeAny, currentPath: Array): [z.ZodTypeAny, ZodPathSegments[]]; +/** + * Once we get the final extracted object that has numeric IDs in place of URLs, + * use `injectUrls` to walk the object and replace numeric IDs + * with the real URL strings from idToUrlMapping. The `path` may include `*` + * for array indices (indicating "all items in the array"). + */ +export declare function injectUrls(obj: unknown, path: Array, idToUrlMapping: Record): void; +/** + * Mapping from LLM provider names to their corresponding environment variable names for API keys. + */ +export declare const providerEnvVarMap: Partial>; +/** + * Loads an API key for a provider, checking environment variables. + * @param provider The name of the provider (e.g., 'openai', 'anthropic') + * @param logger Optional logger for info/error messages + * @returns The API key if found, undefined otherwise + */ +export declare function loadApiKeyFromEnv(provider: string | undefined, logger: (logLine: LogLine) => void): string | undefined; +export declare function trimTrailingTextNode(path: string | undefined): string | undefined; diff --git a/sdk/stagehand-ts/dist/lib/version.d.ts b/sdk/stagehand-ts/dist/lib/version.d.ts new file mode 100644 index 0000000..857f102 --- /dev/null +++ b/sdk/stagehand-ts/dist/lib/version.d.ts @@ -0,0 +1,5 @@ +/** + * AUTO-GENERATED — DO NOT EDIT BY HAND + * Run `pnpm run gen-version` to refresh. + */ +export declare const STAGEHAND_VERSION: "2.4.2"; diff --git a/sdk/stagehand-ts/dist/scripts/gen-version.d.ts b/sdk/stagehand-ts/dist/scripts/gen-version.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/scripts/gen-version.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/scripts/run-evals.d.ts b/sdk/stagehand-ts/dist/scripts/run-evals.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/sdk/stagehand-ts/dist/scripts/run-evals.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/sdk/stagehand-ts/dist/stagehand.config.d.ts b/sdk/stagehand-ts/dist/stagehand.config.d.ts new file mode 100644 index 0000000..6532a28 --- /dev/null +++ b/sdk/stagehand-ts/dist/stagehand.config.d.ts @@ -0,0 +1,3 @@ +import type { ConstructorParams } from "@/dist"; +declare const StagehandConfig: ConstructorParams; +export default StagehandConfig; diff --git a/sdk/stagehand-ts/dist/types/act.d.ts b/sdk/stagehand-ts/dist/types/act.d.ts new file mode 100644 index 0000000..b89c81d --- /dev/null +++ b/sdk/stagehand-ts/dist/types/act.d.ts @@ -0,0 +1,50 @@ +import { LLMClient } from "../lib/llm/LLMClient"; +import { Locator } from "playwright"; +import { Logger } from "@/types/log"; +import { StagehandPage } from "@/lib/StagehandPage"; +export interface ActCommandParams { + action: string; + steps?: string; + domElements: string; + llmClient: LLMClient; + retries?: number; + logger: (message: { + category?: string; + message: string; + }) => void; + requestId: string; + variables?: Record; + userProvidedInstructions?: string; +} +export interface ActCommandResult { + method: string; + element: number; + args: unknown[]; + completed: boolean; + step: string; + why?: string; +} +export declare enum SupportedPlaywrightAction { + CLICK = "click", + FILL = "fill", + TYPE = "type", + PRESS = "press", + SCROLL = "scrollTo", + NEXT_CHUNK = "nextChunk", + PREV_CHUNK = "prevChunk", + SELECT_OPTION_FROM_DROPDOWN = "selectOptionFromDropdown" +} +/** + * A context object to hold all parameters that might be needed by + * any of the methods in the `methodHandlerMap` + */ +export interface MethodHandlerContext { + method: string; + locator: Locator; + xpath: string; + args: unknown[]; + logger: Logger; + stagehandPage: StagehandPage; + initialUrl: string; + domSettleTimeoutMs?: number; +} diff --git a/sdk/stagehand-ts/dist/types/agent.d.ts b/sdk/stagehand-ts/dist/types/agent.d.ts new file mode 100644 index 0000000..2c35845 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/agent.d.ts @@ -0,0 +1,125 @@ +import { LogLine } from "./log"; +export interface AgentAction { + type: string; + [key: string]: unknown; +} +export interface AgentResult { + success: boolean; + message: string; + actions: AgentAction[]; + completed: boolean; + metadata?: Record; + usage?: { + input_tokens: number; + output_tokens: number; + inference_time_ms: number; + }; +} +export interface AgentOptions { + maxSteps?: number; + autoScreenshot?: boolean; + waitBetweenActions?: number; + context?: string; +} +export interface AgentExecuteOptions extends AgentOptions { + instruction: string; +} +export type AgentProviderType = "openai" | "anthropic" | "google"; +export interface AgentClientOptions { + apiKey: string; + organization?: string; + baseURL?: string; + defaultMaxSteps?: number; + [key: string]: unknown; +} +export type AgentType = "openai" | "anthropic" | "google"; +export interface AgentExecutionOptions { + options: AgentExecuteOptions; + logger: (message: LogLine) => void; + retries?: number; +} +export interface AgentHandlerOptions { + modelName: string; + clientOptions?: Record; + userProvidedInstructions?: string; + agentType: AgentType; + experimental?: boolean; +} +export interface ActionExecutionResult { + success: boolean; + error?: string; + data?: unknown; +} +export interface ToolUseItem extends ResponseItem { + type: "tool_use"; + id: string; + name: string; + input: Record; +} +export interface AnthropicMessage { + role: string; + content: string | Array; +} +export interface AnthropicContentBlock { + type: string; + [key: string]: unknown; +} +export interface AnthropicTextBlock extends AnthropicContentBlock { + type: "text"; + text: string; +} +export interface AnthropicToolResult { + type: "tool_result"; + tool_use_id: string; + content: string | Array; +} +export interface ResponseItem { + type: string; + id: string; + [key: string]: unknown; +} +export interface ComputerCallItem extends ResponseItem { + type: "computer_call"; + call_id: string; + action: { + type: string; + [key: string]: unknown; + }; + pending_safety_checks?: Array<{ + id: string; + code: string; + message: string; + }>; +} +export interface FunctionCallItem extends ResponseItem { + type: "function_call"; + call_id: string; + name: string; + arguments: string; +} +export type ResponseInputItem = { + role: string; + content: string; +} | { + type: "computer_call_output"; + call_id: string; + output: { + type: "input_image"; + image_url: string; + current_url?: string; + error?: string; + [key: string]: unknown; + } | string; + acknowledged_safety_checks?: Array<{ + id: string; + code: string; + message: string; + }>; +} | { + type: "function_call_output"; + call_id: string; + output: string; +}; +export interface AgentInstance { + execute: (instructionOrOptions: string | AgentExecuteOptions) => Promise; +} diff --git a/sdk/stagehand-ts/dist/types/api.d.ts b/sdk/stagehand-ts/dist/types/api.d.ts new file mode 100644 index 0000000..5f63441 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/api.d.ts @@ -0,0 +1,38 @@ +import Browserbase from "@browserbasehq/sdk"; +import { LogLine } from "./log"; +export interface StagehandAPIConstructorParams { + apiKey: string; + projectId: string; + logger: (message: LogLine) => void; +} +export interface ExecuteActionParams { + method: "act" | "extract" | "observe" | "navigate" | "end" | "agentExecute"; + args?: unknown; + params?: unknown; +} +export interface StartSessionParams { + modelName: string; + modelApiKey: string; + domSettleTimeoutMs: number; + verbose: number; + debugDom: boolean; + systemPrompt?: string; + browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams; + selfHeal?: boolean; + waitForCaptchaSolves?: boolean; + actionTimeoutMs?: number; + browserbaseSessionID?: string; +} +export interface StartSessionResult { + sessionId: string; + available?: boolean; +} +export interface SuccessResponse { + success: true; + data: T; +} +export interface ErrorResponse { + success: false; + message: string; +} +export type ApiResponse = SuccessResponse | ErrorResponse; diff --git a/sdk/stagehand-ts/dist/types/browser.d.ts b/sdk/stagehand-ts/dist/types/browser.d.ts new file mode 100644 index 0000000..52ce13b --- /dev/null +++ b/sdk/stagehand-ts/dist/types/browser.d.ts @@ -0,0 +1,10 @@ +import { Browser, BrowserContext } from "./page"; +export interface BrowserResult { + env: "LOCAL" | "BROWSERBASE"; + browser?: Browser; + context: BrowserContext; + debugUrl?: string; + sessionUrl?: string; + contextPath?: string; + sessionId?: string; +} diff --git a/sdk/stagehand-ts/dist/types/context.d.ts b/sdk/stagehand-ts/dist/types/context.d.ts new file mode 100644 index 0000000..6c6f022 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/context.d.ts @@ -0,0 +1,117 @@ +import type { BrowserContext as PlaywrightContext, Frame } from "playwright"; +import { Page } from "../types/page"; +export interface AXNode { + role?: { + value: string; + }; + name?: { + value: string; + }; + description?: { + value: string; + }; + value?: { + value: string; + }; + nodeId: string; + backendDOMNodeId?: number; + parentId?: string; + childIds?: string[]; + properties?: { + name: string; + value: { + type: string; + value?: string; + }; + }[]; +} +export type AccessibilityNode = { + role: string; + name?: string; + description?: string; + value?: string; + children?: AccessibilityNode[]; + childIds?: string[]; + parentId?: string; + nodeId?: string; + backendDOMNodeId?: number; + properties?: { + name: string; + value: { + type: string; + value?: string; + }; + }[]; +}; +export interface TreeResult { + tree: AccessibilityNode[]; + simplified: string; + iframes?: AccessibilityNode[]; + idToUrl: Record; + xpathMap: Record; +} +export type DOMNode = { + backendNodeId?: number; + nodeName?: string; + children?: DOMNode[]; + shadowRoots?: DOMNode[]; + contentDocument?: DOMNode; + nodeType: number; + frameId?: string; +}; +export type BackendIdMaps = { + tagNameMap: Record; + xpathMap: Record; + iframeXPath?: string; +}; +export interface EnhancedContext extends Omit { + newPage(): Promise; + pages(): Page[]; +} +export type FrameId = string; +export type LoaderId = string; +export interface CdpFrame { + id: FrameId; + parentId?: FrameId; + loaderId: LoaderId; + name?: string; + url: string; + urlFragment?: string; + domainAndRegistry?: string; + securityOrigin: string; + securityOriginDetails?: Record; + mimeType: string; + unreachableUrl?: string; + adFrameStatus?: string; + secureContextType?: string; + crossOriginIsolatedContextType?: string; + gatedAPIFeatures?: string[]; +} +export interface CdpFrameTree { + frame: CdpFrame; + childFrames?: CdpFrameTree[]; +} +export interface FrameOwnerResult { + backendNodeId?: number; +} +export interface CombinedA11yResult { + combinedTree: string; + combinedXpathMap: Record; + combinedUrlMap: Record; +} +export interface FrameSnapshot { + frame: Frame; + tree: string; + xpathMap: Record; + urlMap: Record; + frameXpath: string; + backendNodeId: number | null; + parentFrame?: Frame; + /** CDP frame identifier for this snapshot; used to generate stable EncodedIds. */ + frameId?: string; +} +export type EncodedId = `${number}-${number}`; +export interface RichNode extends AccessibilityNode { + encodedId?: EncodedId; +} +export declare const ID_PATTERN: RegExp; diff --git a/sdk/stagehand-ts/dist/types/evals.d.ts b/sdk/stagehand-ts/dist/types/evals.d.ts new file mode 100644 index 0000000..28a6a4f --- /dev/null +++ b/sdk/stagehand-ts/dist/types/evals.d.ts @@ -0,0 +1,95 @@ +import { z } from "zod/v3"; +import type { AvailableModel } from "../types/model"; +import type { LogLine } from "../types/log"; +import type { AgentInstance } from "../types/agent"; +import type { EvalCase } from "braintrust"; +import { Stagehand } from "@/dist"; +import { ConstructorParams } from "@/dist"; +import { EvalLogger } from "@/evals/logger"; +export type StagehandInitResult = { + stagehand: Stagehand; + logger: EvalLogger; + debugUrl: string; + sessionUrl: string; + stagehandConfig: ConstructorParams; + modelName: AvailableModel; + agent: AgentInstance; +}; +export declare enum ErrorType { + TIMEOUT = "timeout", + PROXY_ERROR = "proxy_error", + ANTIBOT = "antibot", + NETWORK = "network", + AGENT_FAILURE = "agent_failure", + EVALUATION_ERROR = "evaluation_error", + SETUP_ERROR = "setup_error", + PARSING_ERROR = "parsing_error", + UNKNOWN = "unknown" +} +export interface EvalOutput { + _success: boolean; + logs: LogLine[]; + debugUrl: string; + sessionUrl: string; + error?: unknown; + error_type?: ErrorType; + error_message?: string; + error_stack?: string; + execution_time?: number; + agent_steps?: number; + final_answer?: string; + reasoning?: string; + observations?: string | unknown; + [key: string]: unknown; +} +export type EvalFunction = (taskInput: StagehandInitResult & { + input: EvalInput; +}) => Promise; +export declare const EvalCategorySchema: z.ZodEnum<["observe", "act", "combination", "extract", "experimental", "targeted_extract", "regression", "regression_llm_providers", "llm_clients", "agent", "external_agent_benchmarks"]>; +export type EvalCategory = z.infer; +export interface EvalInput { + name: string; + modelName: AvailableModel; + params?: Record; +} +export interface TestcaseMetadata { + model: AvailableModel; + test: string; + category?: string; + dataset?: string; + dataset_id?: string; + dataset_level?: string | number; + dataset_category?: string; + [key: string]: unknown; +} +export interface Testcase extends EvalCase { + input: EvalInput; + name: string; + tags: string[]; + metadata: TestcaseMetadata; + expected: unknown; +} +export interface SummaryResult { + input: EvalInput; + output: { + _success: boolean; + }; + name: string; + score: number; +} +export interface EvalArgs { + input: TInput; + output: TOutput; + expected: TExpected; + metadata?: { + model: AvailableModel; + test: string; + }; +} +export interface EvalResult { + name: string; + score: number; +} +export type LogLineEval = LogLine & { + parsedAuxiliary?: string | object; +}; diff --git a/sdk/stagehand-ts/dist/types/evaluator.d.ts b/sdk/stagehand-ts/dist/types/evaluator.d.ts new file mode 100644 index 0000000..27669b8 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/evaluator.d.ts @@ -0,0 +1,40 @@ +export type EvaluateOptions = { + /** The question to ask about the task state */ + question: string; + /** The answer to the question */ + answer?: string; + /** Whether to take a screenshot of the task state, or array of screenshots to evaluate */ + screenshot?: boolean | Buffer[]; + /** Custom system prompt for the evaluator */ + systemPrompt?: string; + /** Delay in milliseconds before taking the screenshot @default 250 */ + screenshotDelayMs?: number; + /** The agent's reasoning/thought process for completing the task */ + agentReasoning?: string; +}; +export type BatchAskOptions = { + /** Array of questions with optional answers */ + questions: Array<{ + question: string; + answer?: string; + }>; + /** Whether to take a screenshot of the task state */ + screenshot?: boolean; + /** Custom system prompt for the evaluator */ + systemPrompt?: string; + /** Delay in milliseconds before taking the screenshot @default 1000 */ + screenshotDelayMs?: number; +}; +/** + * Result of an evaluation + */ +export interface EvaluationResult { + /** + * The evaluation result ('YES', 'NO', or 'INVALID' if parsing failed or value was unexpected) + */ + evaluation: "YES" | "NO" | "INVALID"; + /** + * The reasoning behind the evaluation + */ + reasoning: string; +} diff --git a/sdk/stagehand-ts/dist/types/llm.d.ts b/sdk/stagehand-ts/dist/types/llm.d.ts new file mode 100644 index 0000000..9ebb334 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/llm.d.ts @@ -0,0 +1,11 @@ +import { LanguageModel } from "ai"; +export interface LLMTool { + type: "function"; + name: string; + description: string; + parameters: Record; +} +export type AISDKProvider = (modelName: string) => LanguageModel; +export type AISDKCustomProvider = (options: { + apiKey: string; +}) => AISDKProvider; diff --git a/sdk/stagehand-ts/dist/types/log.d.ts b/sdk/stagehand-ts/dist/types/log.d.ts new file mode 100644 index 0000000..2d54035 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/log.d.ts @@ -0,0 +1,23 @@ +export type LogLevel = 0 | 1 | 2; +/** + * Mapping between numeric log levels and their names + * + * 0 - error/warn - Critical issues or important warnings + * 1 - info - Standard information messages + * 2 - debug - Detailed information for debugging + */ +export declare const LOG_LEVEL_NAMES: Record; +export type LogLine = { + id?: string; + category?: string; + message: string; + level?: LogLevel; + timestamp?: string; + auxiliary?: { + [key: string]: { + value: string; + type: "object" | "string" | "html" | "integer" | "float" | "boolean"; + }; + }; +}; +export type Logger = (logLine: LogLine) => void; diff --git a/sdk/stagehand-ts/dist/types/model.d.ts b/sdk/stagehand-ts/dist/types/model.d.ts new file mode 100644 index 0000000..4be6e8a --- /dev/null +++ b/sdk/stagehand-ts/dist/types/model.d.ts @@ -0,0 +1,17 @@ +import type { ClientOptions as AnthropicClientOptions } from "@anthropic-ai/sdk"; +import type { ClientOptions as OpenAIClientOptions } from "openai"; +import { z } from "zod/v3"; +export declare const AvailableModelSchema: z.ZodEnum<["gpt-4.1", "gpt-4.1-mini", "gpt-4.1-nano", "o4-mini", "o3", "o3-mini", "o1", "o1-mini", "gpt-4o", "gpt-4o-mini", "gpt-4o-2024-08-06", "gpt-4.5-preview", "o1-preview", "claude-3-5-sonnet-latest", "claude-3-5-sonnet-20241022", "claude-3-5-sonnet-20240620", "claude-3-7-sonnet-latest", "claude-3-7-sonnet-20250219", "cerebras-llama-3.3-70b", "cerebras-llama-3.1-8b", "groq-llama-3.3-70b-versatile", "groq-llama-3.3-70b-specdec", "gemini-1.5-flash", "gemini-1.5-pro", "gemini-1.5-flash-8b", "gemini-2.0-flash-lite", "gemini-2.0-flash", "gemini-2.5-flash-preview-04-17", "gemini-2.5-pro-preview-03-25"]>; +export type AvailableModel = z.infer | string; +export type ModelProvider = "openai" | "anthropic" | "cerebras" | "groq" | "google" | "aisdk"; +export type ClientOptions = OpenAIClientOptions | AnthropicClientOptions; +export interface AnthropicJsonSchemaObject { + definitions?: { + MySchema?: { + properties?: Record; + required?: string[]; + }; + }; + properties?: Record; + required?: string[]; +} diff --git a/sdk/stagehand-ts/dist/types/operator.d.ts b/sdk/stagehand-ts/dist/types/operator.d.ts new file mode 100644 index 0000000..b482aa2 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/operator.d.ts @@ -0,0 +1,26 @@ +import { z } from "zod/v3"; +export declare const operatorResponseSchema: z.ZodObject<{ + reasoning: z.ZodString; + method: z.ZodEnum<["act", "extract", "goto", "close", "wait", "navback", "refresh"]>; + parameters: z.ZodNullable; + taskComplete: z.ZodBoolean; +}, "strip", z.ZodTypeAny, { + reasoning?: string; + method?: "act" | "extract" | "close" | "goto" | "wait" | "navback" | "refresh"; + parameters?: string; + taskComplete?: boolean; +}, { + reasoning?: string; + method?: "act" | "extract" | "close" | "goto" | "wait" | "navback" | "refresh"; + parameters?: string; + taskComplete?: boolean; +}>; +export type OperatorResponse = z.infer; +export declare const operatorSummarySchema: z.ZodObject<{ + answer: z.ZodString; +}, "strip", z.ZodTypeAny, { + answer?: string; +}, { + answer?: string; +}>; +export type OperatorSummary = z.infer; diff --git a/sdk/stagehand-ts/dist/types/page.d.ts b/sdk/stagehand-ts/dist/types/page.d.ts new file mode 100644 index 0000000..2d21150 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/page.d.ts @@ -0,0 +1,33 @@ +import type { Browser as PlaywrightBrowser, BrowserContext as PlaywrightContext, Page as PlaywrightPage } from "playwright"; +import { z } from "zod/v3"; +import type { ActOptions, ActResult, ExtractOptions, ExtractResult, ObserveOptions, ObserveResult } from "./stagehand"; +export declare const defaultExtractSchema: z.ZodObject<{ + extraction: z.ZodString; +}, "strip", z.ZodTypeAny, { + extraction?: string; +}, { + extraction?: string; +}>; +export declare const pageTextSchema: z.ZodObject<{ + page_text: z.ZodString; +}, "strip", z.ZodTypeAny, { + page_text?: string; +}, { + page_text?: string; +}>; +export interface Page extends Omit { + act(action: string): Promise; + act(options: ActOptions): Promise; + act(observation: ObserveResult): Promise; + extract(instruction: string): Promise>; + extract(options: ExtractOptions): Promise>; + extract(): Promise>; + observe(): Promise; + observe(instruction: string): Promise; + observe(options?: ObserveOptions): Promise; + on: { + (event: "popup", listener: (page: Page) => unknown): Page; + } & PlaywrightPage["on"]; +} +export type BrowserContext = PlaywrightContext; +export type Browser = PlaywrightBrowser; diff --git a/sdk/stagehand-ts/dist/types/playwright.d.ts b/sdk/stagehand-ts/dist/types/playwright.d.ts new file mode 100644 index 0000000..a78d3b5 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/playwright.d.ts @@ -0,0 +1,12 @@ +export declare class PlaywrightCommandException extends Error { + constructor(message: string); +} +export declare class PlaywrightCommandMethodNotSupportedException extends Error { + constructor(message: string); +} +export interface GotoOptions { + timeout?: number; + waitUntil?: "load" | "domcontentloaded" | "networkidle" | "commit"; + referer?: string; + frameId?: string; +} diff --git a/sdk/stagehand-ts/dist/types/stagehand.d.ts b/sdk/stagehand-ts/dist/types/stagehand.d.ts new file mode 100644 index 0000000..aef7720 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/stagehand.d.ts @@ -0,0 +1,309 @@ +import Browserbase from "@browserbasehq/sdk"; +import { z } from "zod/v3"; +import { LLMProvider } from "../lib/llm/LLMProvider"; +import { LogLine } from "./log"; +import { AvailableModel, ClientOptions } from "./model"; +import { LLMClient } from "../lib/llm/LLMClient"; +import { Cookie } from "playwright"; +import { AgentProviderType } from "./agent"; +export interface ConstructorParams { + /** + * The environment to use for Stagehand + */ + env: "LOCAL" | "BROWSERBASE"; + /** + * Your Browserbase API key + */ + apiKey?: string; + /** + * Your Browserbase project ID + */ + projectId?: string; + /** + * The verbosity of the Stagehand logger + * 0 - No logs + * 1 - Only errors + * 2 - All logs + */ + verbose?: 0 | 1 | 2; + /** + * The LLM provider to use for Stagehand + * See + */ + llmProvider?: LLMProvider; + /** + * The logger to use for Stagehand + */ + logger?: (message: LogLine) => void | Promise; + /** + * The timeout to use for the DOM to settle + * @default 10000 + */ + domSettleTimeoutMs?: number; + /** + * The parameters to use for creating a Browserbase session + * See https://docs.browserbase.com/reference/api/create-a-session + */ + browserbaseSessionCreateParams?: Browserbase.Sessions.SessionCreateParams; + /** + * Enable caching of LLM responses + * @default true + */ + enableCaching?: boolean; + /** + * The ID of a Browserbase session to resume + */ + browserbaseSessionID?: string; + /** + * The model to use for Stagehand + */ + modelName?: AvailableModel; + /** + * The LLM client to use for Stagehand + */ + llmClient?: LLMClient; + /** + * The parameters to use for the LLM client + * Useful for parameterizing LLM API Keys + */ + modelClientOptions?: ClientOptions; + /** + * Customize the Stagehand system prompt + */ + systemPrompt?: string; + /** + * Offload Stagehand method calls to the Stagehand API. + * Must have a valid API key to use + */ + useAPI?: boolean; + /** + * Wait for captchas to be solved after navigation when using Browserbase environment. + * + * @default false + */ + waitForCaptchaSolves?: boolean; + /** + * The parameters to use for launching a local browser + */ + localBrowserLaunchOptions?: LocalBrowserLaunchOptions; + /** + * Log the inference to a file + */ + logInferenceToFile?: boolean; + selfHeal?: boolean; + /** + * Disable Pino (helpful for Next.js or test environments) + */ + disablePino?: boolean; + /** + * Experimental Flag: Enables the latest experimental features + */ + experimental?: boolean; +} +export interface InitResult { + debugUrl: string; + sessionUrl: string; + sessionId: string; +} +export interface ActOptions { + action: string; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + variables?: Record; + domSettleTimeoutMs?: number; + timeoutMs?: number; + iframes?: boolean; + frameId?: string; +} +export interface ActResult { + success: boolean; + message: string; + action: string; +} +export interface ExtractOptions { + instruction?: string; + schema?: T; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + domSettleTimeoutMs?: number; + /** + * @deprecated The `useTextExtract` parameter has no effect in this version of Stagehand and will be removed in later versions. + */ + useTextExtract?: boolean; + selector?: string; + iframes?: boolean; + frameId?: string; +} +export type ExtractResult = z.infer; +export interface ObserveOptions { + instruction?: string; + modelName?: AvailableModel; + modelClientOptions?: ClientOptions; + domSettleTimeoutMs?: number; + returnAction?: boolean; + /** + * @deprecated The `onlyVisible` parameter has no effect in this version of Stagehand and will be removed in later versions. + */ + onlyVisible?: boolean; + drawOverlay?: boolean; + iframes?: boolean; + frameId?: string; +} +export interface ObserveResult { + selector: string; + description: string; + backendNodeId?: number; + method?: string; + arguments?: string[]; +} +export interface LocalBrowserLaunchOptions { + args?: string[]; + chromiumSandbox?: boolean; + devtools?: boolean; + env?: Record; + executablePath?: string; + handleSIGHUP?: boolean; + handleSIGINT?: boolean; + handleSIGTERM?: boolean; + headless?: boolean; + ignoreDefaultArgs?: boolean | Array; + proxy?: { + server: string; + bypass?: string; + username?: string; + password?: string; + }; + tracesDir?: string; + userDataDir?: string; + preserveUserDataDir?: boolean; + acceptDownloads?: boolean; + downloadsPath?: string; + extraHTTPHeaders?: Record; + geolocation?: { + latitude: number; + longitude: number; + accuracy?: number; + }; + hasTouch?: boolean; + ignoreHTTPSErrors?: boolean; + locale?: string; + permissions?: Array; + recordHar?: { + omitContent?: boolean; + content?: "omit" | "embed" | "attach"; + path: string; + mode?: "full" | "minimal"; + urlFilter?: string | RegExp; + }; + recordVideo?: { + dir: string; + size?: { + width: number; + height: number; + }; + }; + viewport?: { + width: number; + height: number; + }; + deviceScaleFactor?: number; + timezoneId?: string; + bypassCSP?: boolean; + cookies?: Cookie[]; + cdpUrl?: string; +} +export interface StagehandMetrics { + actPromptTokens: number; + actCompletionTokens: number; + actInferenceTimeMs: number; + extractPromptTokens: number; + extractCompletionTokens: number; + extractInferenceTimeMs: number; + observePromptTokens: number; + observeCompletionTokens: number; + observeInferenceTimeMs: number; + agentPromptTokens: number; + agentCompletionTokens: number; + agentInferenceTimeMs: number; + totalPromptTokens: number; + totalCompletionTokens: number; + totalInferenceTimeMs: number; +} +/** + * Options for executing a task with an agent + */ +export interface AgentExecuteParams { + /** + * The instruction to execute with the agent + */ + instruction: string; + /** + * Maximum number of steps the agent can take to complete the task + * @default 10 + */ + maxSteps?: number; + /** + * Take a screenshot automatically before each agent step + * @default true + */ + autoScreenshot?: boolean; + /** + * Wait time in milliseconds between agent actions + * @default 0 + */ + waitBetweenActions?: number; + /** + * Additional context to provide to the agent + */ + context?: string; +} +/** + * Configuration for agent functionality + */ +export interface AgentConfig { + /** + * The provider to use for agent functionality + */ + provider?: AgentProviderType; + /** + * The model to use for agent functionality + */ + model?: string; + /** + * Custom instructions to provide to the agent + */ + instructions?: string; + /** + * Additional options to pass to the agent client + */ + options?: Record; +} +export declare enum StagehandFunctionName { + ACT = "ACT", + EXTRACT = "EXTRACT", + OBSERVE = "OBSERVE", + AGENT = "AGENT" +} +export interface HistoryEntry { + method: "act" | "extract" | "observe" | "navigate"; + parameters: unknown; + result: unknown; + timestamp: string; +} +/** + * Represents a path through a Zod schema from the root object down to a + * particular field. The `segments` array describes the chain of keys/indices. + * + * - **String** segments indicate object property names. + * - **Number** segments indicate array indices. + * + * For example, `["users", 0, "homepage"]` might describe reaching + * the `homepage` field in `schema.users[0].homepage`. + */ +export interface ZodPathSegments { + /** + * The ordered list of keys/indices leading from the schema root + * to the targeted field. + */ + segments: Array; +} diff --git a/sdk/stagehand-ts/dist/types/stagehandApiErrors.d.ts b/sdk/stagehand-ts/dist/types/stagehandApiErrors.d.ts new file mode 100644 index 0000000..bd4fc13 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/stagehandApiErrors.d.ts @@ -0,0 +1,18 @@ +export declare class StagehandAPIError extends Error { + constructor(message: string); +} +export declare class StagehandAPIUnauthorizedError extends StagehandAPIError { + constructor(message?: string); +} +export declare class StagehandHttpError extends StagehandAPIError { + constructor(message: string); +} +export declare class StagehandServerError extends StagehandAPIError { + constructor(message: string); +} +export declare class StagehandResponseBodyError extends StagehandAPIError { + constructor(); +} +export declare class StagehandResponseParseError extends StagehandAPIError { + constructor(message: string); +} diff --git a/sdk/stagehand-ts/dist/types/stagehandErrors.d.ts b/sdk/stagehand-ts/dist/types/stagehandErrors.d.ts new file mode 100644 index 0000000..f18de32 --- /dev/null +++ b/sdk/stagehand-ts/dist/types/stagehandErrors.d.ts @@ -0,0 +1,99 @@ +import { ZodError } from "zod/v3"; +export declare class StagehandError extends Error { + constructor(message: string); +} +export declare class StagehandDefaultError extends StagehandError { + constructor(error?: unknown); +} +export declare class StagehandEnvironmentError extends StagehandError { + constructor(currentEnvironment: string, requiredEnvironment: string, feature: string); +} +export declare class MissingEnvironmentVariableError extends StagehandError { + constructor(missingEnvironmentVariable: string, feature: string); +} +export declare class UnsupportedModelError extends StagehandError { + constructor(supportedModels: string[], feature?: string); +} +export declare class UnsupportedModelProviderError extends StagehandError { + constructor(supportedProviders: string[], feature?: string); +} +export declare class UnsupportedAISDKModelProviderError extends StagehandError { + constructor(provider: string, supportedProviders: string[]); +} +export declare class InvalidAISDKModelFormatError extends StagehandError { + constructor(modelName: string); +} +export declare class StagehandNotInitializedError extends StagehandError { + constructor(prop: string); +} +export declare class BrowserbaseSessionNotFoundError extends StagehandError { + constructor(); +} +export declare class CaptchaTimeoutError extends StagehandError { + constructor(); +} +export declare class MissingLLMConfigurationError extends StagehandError { + constructor(); +} +export declare class HandlerNotInitializedError extends StagehandError { + constructor(handlerType: string); +} +export declare class StagehandInvalidArgumentError extends StagehandError { + constructor(message: string); +} +export declare class StagehandElementNotFoundError extends StagehandError { + constructor(xpaths: string[]); +} +export declare class AgentScreenshotProviderError extends StagehandError { + constructor(message: string); +} +export declare class StagehandMissingArgumentError extends StagehandError { + constructor(message: string); +} +export declare class CreateChatCompletionResponseError extends StagehandError { + constructor(message: string); +} +export declare class StagehandEvalError extends StagehandError { + constructor(message: string); +} +export declare class StagehandDomProcessError extends StagehandError { + constructor(message: string); +} +export declare class StagehandClickError extends StagehandError { + constructor(message: string, selector: string); +} +export declare class LLMResponseError extends StagehandError { + constructor(primitive: string, message: string); +} +export declare class StagehandIframeError extends StagehandError { + constructor(frameUrl: string, message: string); +} +export declare class ContentFrameNotFoundError extends StagehandError { + constructor(selector: string); +} +export declare class XPathResolutionError extends StagehandError { + constructor(xpath: string); +} +export declare class ExperimentalApiConflictError extends StagehandError { + constructor(); +} +export declare class ExperimentalNotConfiguredError extends StagehandError { + constructor(featureName: string); +} +export declare class ZodSchemaValidationError extends Error { + readonly received: unknown; + readonly issues: ReturnType; + constructor(received: unknown, issues: ReturnType); +} +export declare class StagehandInitError extends StagehandError { + constructor(message: string); +} +export declare class StagehandShadowRootMissingError extends StagehandError { + constructor(detail?: string); +} +export declare class StagehandShadowSegmentEmptyError extends StagehandError { + constructor(); +} +export declare class StagehandShadowSegmentNotFoundError extends StagehandError { + constructor(segment: string, hint?: string); +} diff --git a/sdk/stagehand-ts/docs/.gitignore b/sdk/stagehand-ts/docs/.gitignore new file mode 100644 index 0000000..7dfb1d1 --- /dev/null +++ b/sdk/stagehand-ts/docs/.gitignore @@ -0,0 +1,3 @@ +node_modules +downloads +.DS_Store \ No newline at end of file diff --git a/sdk/stagehand-ts/docs/README.md b/sdk/stagehand-ts/docs/README.md new file mode 100644 index 0000000..d81eb1d --- /dev/null +++ b/sdk/stagehand-ts/docs/README.md @@ -0,0 +1,32 @@ +# Mintlify Starter Kit + +Click on `Use this template` to copy the Mintlify starter kit. The starter kit contains examples including + +- Guide pages +- Navigation +- Customizations +- API Reference pages +- Use of popular components + +### Development + +Install dependencies with pnpm + +``` +pnpm install +``` + +Run the following command at the root of your documentation (where mint.json is) + +``` +pnpm mintlify dev +``` + +### Publishing Changes + +Install our Github App to auto propagate changes from your repo to your deployment. Changes will be deployed to production automatically after pushing to the default branch. Find the link to install on your dashboard. + +#### Troubleshooting + +- Mintlify dev isn't running - Run `mintlify install` it'll re-install dependencies. +- Page loads as a 404 - Make sure you are running in a folder with `mint.json` diff --git a/sdk/stagehand-ts/docs/concepts/act.mdx b/sdk/stagehand-ts/docs/concepts/act.mdx new file mode 100644 index 0000000..306412b --- /dev/null +++ b/sdk/stagehand-ts/docs/concepts/act.mdx @@ -0,0 +1,118 @@ +--- +title: "Interact with a website" +description: "You can use Stagehand to intelligently interact with a website using AI" +icon: "arrow-pointer" +--- + +## Executing actions + +Stagehand has an `act()` function that can be used to execute actions on a page using natural language. Here's an example of Stagehand to find jobs on LinkedIn: + +![Take actions with Stagehand](/media/linkedin.gif) + +This workflow is as simple as the following lines of code: + + + ```typescript TypeScript const page = stagehand.page // Navigate to the URL + await page.goto("https://linkedin.com"); // Click on jobs menu selection await + page.act("click 'jobs'"); // Click on first posting await page.act("click the + first job posting"); ``` ```python Python page = stagehand.page # Navigate to + the URL await page.goto("https://linkedin.com") # Click on jobs menu selection + await page.act("click 'jobs'") # Click on first posting await page.act("click + the first job posting") ``` + + +The `page` object extends the Playwright page object, so you can use any of the [Playwright page methods](https://playwright.dev/docs/api/class-page) with it. + +## Get structured data from the page + +You can use `extract()` to get structured data from the page. +Here's an example of how to extract the job title from the job posting: + + +```typescript TypeScript +const { jobTitle } = await page.extract({ + instruction: "Extract the job title from the job posting", + schema: z.object({ + jobTitle: z.string(), + }), +}); +``` +```python Python +result = await page.extract("Extract the job title from the job posting") +``` + + + + Stagehand uses [Zod](https://zod.dev/) for TypeScript and + [Pydantic](https://docs.pydantic.dev/) for Python to help you define the + schema of the data to be extracted. + + +## Preview/Cache an action + +Sometimes you want to preview an action before it's executed. You can do this by calling `page.observe()` before `act()`. + + +```typescript TypeScript +const [action] = await page.observe("click 'jobs'"); + +console.log("Going to execute action:", action) +// You can add extra logic here to validate/cache the action + +await page.act(action) + +```` +```python Python +actions = await page.observe("click 'jobs'") +action = actions[0] + +print("Going to execute action:", action) +# You can add extra logic here to validate/cache the action + +await page.act(action) +```` + + + +`action` will be a JSON object that describes the action to be taken. + +```TypeScript +// action is a JSON-ified version of a Playwright action: +{ + description: "The jobs link", + method: "click", + selector: "/html/body/div[1]/div[1]/a", + arguments: [], +} +``` + +For more on caching, see the [caching docs](/examples/caching). + +## What actions can I take? + +Stagehand maps natural language to [Playwright](https://playwright.dev) actions. + +We generally support the following actions: + +| Action | Description | +| ---------------- | -------------------------------------------------------------- | +| `scrollIntoView` | Scrolls an element into the visible area of the browser window | +| `scrollTo` | Scrolls to a specific percentage of the page height | +| `fill` | Fills in form fields with specified text | +| `type` | Types text into input fields (alias for `fill`) | +| `press` | Simulates pressing keyboard keys | +| `click` | Clicks on elements matching the specified selector | +| `nextChunk` | Scrolls the height of the viewport by 100% | +| `prevChunk` | Scrolls the height of the viewport by -100% | + +Each of these actions can be triggered using natural language commands. For example: + + + ```typescript TypeScript await page.act("scroll to the bottom of the page") + await page.act("fill in the username field with 'john_doe'") await + page.act("scroll the modal to the next chunk") ``` ```python Python await + page.act("scroll to the bottom of the page") await page.act("fill in the + username field with 'john_doe'") await page.act("scroll the modal to the next + chunk") ``` + diff --git a/sdk/stagehand-ts/docs/concepts/agent.mdx b/sdk/stagehand-ts/docs/concepts/agent.mdx new file mode 100644 index 0000000..ff4ee45 --- /dev/null +++ b/sdk/stagehand-ts/docs/concepts/agent.mdx @@ -0,0 +1,236 @@ +--- +title: "Build a web browsing agent" +description: "Build an AI agent that can autonomously control a browser with Stagehand" +icon: "robot" +--- + +import { Excalidraw } from "/snippets/excalidraw.mdx"; + +Stagehand gives AI agents powerful tools to control a browser completely autonomously. Watch below as a Stagehand agent autonomously navigates to a URL, takes actions on the page, and extracts structured data to answer a question. +There's quite a few ways to build an agent with Stagehand. Let's look at a few of them. + +![Agent](/media/stagehand-agent.gif) + +## Stagehand MCP + +The above example is a Claude agent that uses Stagehand to control a browser. At this time of writing, [multimodal tool calling](https://sdk.vercel.ai/docs/ai-sdk-core/tools-and-tool-calling#multi-modal-tool-results) is only supported in Claude 3.5/3.7 Sonnet. +This means Claude is intelligent enough to know when to request a browser screenshot, and it can then use that screenshot to make decisions about what actions to take next. + + + + Control a browser with Browserbase MCP powered by Stagehand + + + +What's really interesting about this is that the agent is able to reason about the browser state and take actions separate from one another! +Claude is able to reason about the browser state, while Stagehand is able to take actions on the page with GPT-4o-mini or a computer use model. +Stagehand is even smart enough to know when to use GPT-4o-mini and when to use a computer use model, i.e. on iframe detection. + + + +We've found great success from having Claude as the "Trajectory" agent calling Stagehand tools when it sees fit! +While MCP is really nascent, we're excited to see where it goes. + +## Stagehand + Computer Use Models + +Stagehand lets you leverage powerful computer use APIs from OpenAI and Anthropic with just one line of code. + + +```typescript TypeScript +await page.goto("https://github.com/browserbase/stagehand"); + +// Create a Computer Use agent with just one line of code! +const agent = stagehand.agent({ +provider: "openai", +model: "computer-use-preview" +}); + +// Use the agent to execute a task +const result = await agent.execute("Extract the top contributor's username"); +console.log(result); + +```` +```python Python +await page.goto("https://github.com/browserbase/stagehand-python") + +# Create a Computer Use agent with just one line of code! +agent = stagehand.agent( + model="computer-use-preview" +) + +# Use the agent to execute a task +result = await agent.execute("Extract the top contributor's username") +print(result) +```` + + + + + + Check out our docs page for instructions on how to use computer use models + with Stagehand. + + + Check out a live demo of a Browserbase browser controlled by OpenAI's + Computer Using Agent (CUA) model. + + + +## Sequential Tool Calling (Open Operator) + +In January 2025, Browserbase released [Open Operator](https://operator.browserbase.com). +Open Operator is able to reason about the browser state and take actions accordingly to accomplish larger tasks like "order me a pizza". +It works by calling Stagehand tools in sequence: + +1. If there's no URL, go to a default URL. +1. Examine the browser state. Ask an LLM to reason about what to do next. +1. Use `page.act()` to execute the LLM-suggested action. +1. Repeat + + + +Incorporating `stagehand.agent` into your browser automation is as easy as adding a single line of code: + + + Python currently supports `stagehand.agent` with Computer Use Agent (CUA) + models. The default implementation is coming soon. + + + +```typescript TypeScript +await stagehand.page.goto("https://github.com/browserbase/stagehand"); + +// Open Operator will use the default LLM from Stagehand config +const operator = stagehand.agent(); +const { message, actions } = await operator.execute( +"Extract the top contributor's username" +); + +console.log(message); + +```` + + +### Replay the agent's actions + +You can replay the agent's actions exactly the same way you would with a regular Stagehand agent. You can even automatically cache the actions to avoid unnecessary LLM calls on a repeated run. + +Let's use the `replay` function below to save the actions to a Stagehand script file, which will reproduce the same actions the agent did, with cached actions built in. + + +```typescript +import { AgentAction, AgentResult } from "@browserbasehq/stagehand"; +import { exec } from "child_process"; +import fs from "fs/promises"; + +export async function replay(result: AgentResult) { + const history = result.actions; + const replay = history + .map((action: AgentAction) => { + switch (action.type) { + case "act": + if (!action.playwrightArguments) { + throw new Error("No playwright arguments provided"); + } + return `await page.act(${JSON.stringify( + action.playwrightArguments + )})`; + case "extract": + return `await page.extract("${action.parameters}")`; + case "goto": + return `await page.goto("${action.parameters}")`; + case "wait": + return `await page.waitForTimeout(${parseInt( + action.parameters as string + )})`; + case "navback": + return `await page.goBack()`; + case "refresh": + return `await page.reload()`; + case "close": + return `await stagehand.close()`; + default: + return `await stagehand.oops()`; + } + }) + .join("\n"); + + console.log("Replay:"); + const boilerplate = ` +import { Page, BrowserContext, Stagehand } from "@browserbasehq/stagehand"; + +export async function main(stagehand: Stagehand) { + const page = stagehand.page + ${replay} +} + `; + await fs.writeFile("replay.ts", boilerplate); + + // Format the replay file with prettier + await new Promise((resolve, reject) => { + exec( + "npx prettier --write replay.ts", + (error: any, stdout: any, stderr: any) => { + if (error) { + console.error(`Error formatting replay.ts: ${error}`); + reject(error); + return; + } + resolve(stdout); + } + ); + }); +} +```` + + + +Here's the replay output of an instruction like `"Get me the stock price of NVDA"`: + +```typescript {14-22} replay.ts +import { Page, BrowserContext, Stagehand } from "@browserbasehq/stagehand"; + +export async function main({ + page, + context, + stagehand, +}: { + page: Page; // Playwright Page with act, extract, and observe methods + context: BrowserContext; // Playwright BrowserContext + stagehand: Stagehand; // Stagehand instance +}) { + await page.goto("https://www.google.com"); + + // Replay will default to Playwright first to avoid unnecessary LLM calls! + // If the Playwright action fails, Stagehand AI will take over and self-heal + await page.act({ + description: "The search combobox where users can type their queries.", + method: "fill", + arguments: ["NVDA stock price"], + selector: + "xpath=/html/body[1]/div[1]/div[3]/form[1]/div[1]/div[1]/div[1]/div[1]/div[2]/textarea[1]", + }); + await page.extract( + "the displayed NVDA stock price in the search suggestions", + ); + await stagehand.close(); +} +``` diff --git a/sdk/stagehand-ts/docs/docs.json b/sdk/stagehand-ts/docs/docs.json new file mode 100644 index 0000000..bf5045a --- /dev/null +++ b/sdk/stagehand-ts/docs/docs.json @@ -0,0 +1,109 @@ +{ + "$schema": "https://mintlify.com/docs.json", + "theme": "willow", + "name": "🤘 Stagehand", + "colors": { + "primary": "#B88100", + "light": "#FFC83C", + "dark": "#FFC83C" + }, + "favicon": "/images/favicon.svg", + "navigation": { + "groups": [ + { + "group": "Get Started", + "pages": [ + "get_started/introduction", + "get_started/quickstart", + "get_started/integrate_stagehand" + ] + }, + { + "group": "Concepts", + "pages": ["concepts/act", "concepts/agent"] + }, + { + "group": "Playbooks", + "pages": [ + "examples/best_practices", + "examples/caching", + "examples/running_evals", + "examples/nextjs", + "examples/custom_llms", + "examples/customize_browser", + "examples/computer_use", + "examples/contributing" + ] + }, + { + "group": "Reference", + "pages": [ + "reference/initialization_config", + "reference/agent", + "reference/act", + "reference/extract", + "reference/observe", + "reference/playwright_interop", + "integrations/guides" + ] + }, + { + "group": "Integrations", + "pages": [ + { + "group": "MCP Server", + "pages": [ + "integrations/mcp/introduction", + "integrations/mcp/setup", + "integrations/mcp/tools", + "integrations/mcp/configuration" + ] + }, + "integrations/langchain", + "integrations/crew-ai" + ] + } + ], + "global": { + "anchors": [ + { + "anchor": "Changelog", + "href": "https://github.com/browserbase/stagehand/releases", + "icon": "scroll" + }, + { + "anchor": "Reference", + "href": "https://docs.stagehand.dev/reference/introduction", + "icon": "code" + } + ] + } + }, + "logo": { + "light": "/logo/light_logo.png", + "dark": "/logo/dark_logo.png", + "href": "https://stagehand.dev" + }, + "navbar": { + "links": [ + { + "label": "Support", + "href": "mailto:support@browserbase.com" + } + ] + }, + "footer": { + "socials": { + "x": "https://x.com/stagehanddev", + "github": "https://github.com/browserbase/stagehand", + "linkedin": "https://linkedin.com/company/browserbasehq", + "slack": "https://stagehand.dev/slack" + } + }, + "integrations": { + "posthog": { + "apiKey": "phc_hmwkFrlc9UVrdE1jyG8AEKoCQCSr8dScjsRpKoLBEiV", + "apiHost": "https://us.i.posthog.com" + } + } +} diff --git a/sdk/stagehand-ts/docs/examples/best_practices.mdx b/sdk/stagehand-ts/docs/examples/best_practices.mdx new file mode 100644 index 0000000..e6b5253 --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/best_practices.mdx @@ -0,0 +1,282 @@ +--- +title: "Best Practices" +description: "Prompting Stagehand places an emphasis on being atomic and specific. Here are some guidelines to help you use Stagehand effectively." +--- + +### Use Cursor rules for better AI suggestions + +Most of the Stagehand team uses [Cursor](https://www.cursor.com/) to write code. Cursor has a feature called [rules](https://docs.cursor.com/context/rules-for-ai) that allows you to customize the AI's behavior. You can use these rules to make the AI more accurate when suggesting actions. + +For Stagehand's Cursor rules, check out [this file](https://github.com/browserbase/stagehand-scaffold/blob/main/.cursorrules). + +If you're using Windsurf, you can use the same rules by adding them to your `.windsurfrules` file. + +### Manage multiple pages explicitly (Stagehand v≥ 2.4.1, TypeScript) + + + +Stagehand can now keep **multiple pages open at the same time** and run +`act()`, `observe()` and `extract()` on each of them. + +#### What changed? + +- **Before v2.4.1** Stagehand silently closed every new tab and re‑used the first tab. + A single Page instance (`stagehand.page`) was always valid. +- **Since v2.4.1** New tabs stay open. You can switch between them or operate on all of them in parallel. + +#### The live‑page proxy (`stagehand.page`) + +For backward compatibility, `stagehand.page` is now a **live proxy** that always +points to the **most recently opened page**. +We recommend using it for things like agents, which often don't have the ability to operate on multiple pages. +If you need more control and precision, we recommend managing pages yourself. + +#### Recommended workflow + + +```typescript TypeScript +// Create (or let the site create) additional pages. +await stagehand.context.newPage(); // e.g. open a blank page +const pages = stagehand.context.pages(); + +const [page1, page2] = pages; + +// Work on each page deterministically +await page1.goto('https://github.com/browserbase/stagehand'); +await page2.goto('https://github.com/browserbase/stagehand-python'); + +const [{ extraction: repo1 }, { extraction: repo2 }] = await Promise.all([ +page1.extract('extract the repository name'), +page2.extract('extract the repository name'), +]); + +// should log "page1 repo: stagehand" +console.log(`page1 repo: ${repo1}`); + +// should log "page2 repo: stagehand-python" +console.log(`page2 repo: ${repo2}`); + +```` + + + + +Multi tab support is not yet implemented in Python, but it's coming soon! +Setting `use_api=True` in your stagehand config will keep tabs open. + + + + +### Avoid sending sensitive information to LLMs + +You can use `variables` in an `act` call to avoid sending sensitive information to LLMs. + + +```typescript TypeScript +await page.act({ + action: "Type %email% into the email field", + variables: { + email: "john.doe@example.com", + }, +}); +```` + +```python Python +await page.act({ + "Type %email% into the email field", + variables={ + "email": "john.doe@example.com", + } +}) +``` + + + +### Preview actions before running them + +You can use `observe()` to get an action to run without running it. +If you're satisfied with the action, you can run it with `act()` without any LLM inference. + + +```typescript TypeScript +const [topAction] = await page.observe("Click the quickstart link"); + +/** The action will map 1:1 with a Playwright action: +{ +description: "The quickstart link", +method: "click", +selector: "/html/body/div[1]/div[1]/a", +arguments: [], +} +**/ + +// NO LLM INFERENCE on observe results +await page.act(topAction) + +```` +```python Python +actions = await page.observe("Click the quickstart link") +top_action = actions[0] + +# The action will map 1:1 with a Playwright action: +# { +# "description": "The quickstart link", +# "method": "click", +# "selector": "/html/body/div[1]/div[1]/a", +# "arguments": [], +# } + +# NO LLM INFERENCE on observe results +await page.act(top_action) +```` + + + +You can also use `observe()` with sensitive information, like below. + + +```typescript TypeScript +const [topAction] = await page.observe("Type %email% into the email field"); + +/\*_ The observe result will be an object with the following shape: +{ +description: "The email input field", +method: "type", +selector: "/html/body/div[1]/div[1]/input", +arguments: ["%email%"], +} +_/ + +await page.act({ +...topAction, +// This prevents LLMs from seeing sensitive information +// No LLM inference is taken on observe results +arguments: [sensitiveEmail], +}) + +```` + +```python Python +actions = await page.observe("Type %email% into the email field") +top_action = actions[0] + +# The observe result will be a dictionary with the following shape: +# { +# "description": "The email input field", +# "method": "type", +# "selector": "/html/body/div[1]/div[1]/input", +# "arguments": ["%email%"], +# } + +await page.act({ + **top_action, + # This prevents LLMs from seeing sensitive information + # No LLM inference is taken on observe results + "arguments": [sensitive_email], +}) +```` + + + +**Use `observe()` to get actionable suggestions from the current page** + + +```typescript TypeScript +const actions = await page.observe(); +console.log("Possible actions:", actions); + +// You can also use `observe()` with a custom prompt +const buttons = await page.observe({ +instruction: "find all the buttons on the page", +}); + +```` + +```python Python +actions = await page.observe() +print("Possible actions:", actions) + +# You can also use `observe()` with a custom prompt +buttons = await page.observe("find all the buttons on the page") +```` + + + +### Avoid broad or ambiguous instructions + +Avoid instructions that aren't specific to the current page or try to do multiple things at once. + + +```typescript TypeScript +// Too vague +await page.act({ action: "find something interesting on the page" }); + +// Avoid combining actions +await page.act({ action: "fill out the form and submit it" }); + +```` + +```python Python +# Too vague +await page.act("find something interesting on the page") + +# Avoid combining actions +await page.act("fill out the form and submit it") +```` + + + +### Use `observe()` to get entire form values + + + ```typescript TypeScript const formValues = await page.observe("get the text + inputs on the page"); ``` ```python Python form_values = await + page.observe("get the text inputs on the page") ``` + + +This will return an array of objects with the following shape: + + +```typescript TypeScript +{ + description: "The text input field", + method: "type", + selector: "/html/body/div[1]/div[1]/input", + arguments: ["some text"], +} +``` + +```python Python +{ + "description": "The text input field", + "method": "type", + "selector": "/html/body/div[1]/div[1]/input", + "arguments": ["some text"], +} +``` + + + +You can then use these actions directly in your code. + + +```typescript TypeScript +for (const formValue of formValues) { + await page.act({ + ...formValue, + arguments: [yourValueHere], + }); +} +``` + +```python Python +for form_value in form_values: + await page.act({ + **form_value, + "arguments": [your_value_here], + }) +``` + + + +For a full example, check out the example in the Stagehand repo [here](https://github.com/browserbase/stagehand/blob/main/examples/form_filling_sensible.ts). diff --git a/sdk/stagehand-ts/docs/examples/caching.mdx b/sdk/stagehand-ts/docs/examples/caching.mdx new file mode 100644 index 0000000..e1f947b --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/caching.mdx @@ -0,0 +1,217 @@ +--- +title: Caching Actions +description: You can cache actions in Stagehand to avoid redundant LLM calls. +--- + +Caching actions in Stagehand is useful for actions that are expensive to run, or when the underlying DOM structure is not expected to change. + +## Using `observe` to preview an action + +`observe` lets you preview an action before taking it. If you are satisfied with the action preview, you can run it in `page.act` with no further LLM calls. + + +```typescript TypeScript +const [actionPreview] = await page.observe("Click the quickstart link"); + +/** actionPreview is a JSON-ified version of a Playwright action: +{ +description: "The quickstart link", +method: "click", +selector: "/html/body/div[1]/div[1]/a", +arguments: [], +} +**/ + +// NO LLM INFERENCE when calling act on the preview +await page.act(actionPreview) + +```` + +```python Python +actions = await page.observe("Click the quickstart link") +action_preview = actions[0] + +# action_preview is a dictionary version of a Playwright action: +# { +# "description": "The quickstart link", +# "method": "click", +# "selector": "/html/body/div[1]/div[1]/a", +# "arguments": [], +# } + +# NO LLM INFERENCE when calling act on the preview +await page.act(action_preview) +```` + + + +## Simple caching + +Let's use a simple file-based cache for this example. We'll write a getter and a setter functions that can read and write to a JSON file: + + +```typescript TypeScript +// Get the cached value (undefined if it doesn't exist) +async function getCache(key: string): Promise { + try { + const cache = await readFile("cache.json"); + const parsed = JSON.parse(cache); + return parsed[key]; + } catch { + return undefined; + } +} + +// Set the cache value +async function setCache(key: string, value: ObserveResult): Promise { +const cache = await readFile("cache.json"); +const parsed = JSON.parse(cache); +parsed[key] = value; +await writeFile("cache.json", JSON.stringify(parsed)); +} + +```` + +```python Python +# Get the cached value (None if it doesn't exist) +async def get_cache(key: str) -> Optional[Dict[str, Any]]: + try: + async with aiofiles.open("cache.json", 'r') as f: + cache_content = await f.read() + parsed = json.loads(cache_content) + return parsed.get(key) + except (FileNotFoundError, json.JSONDecodeError): + return None + +# Set the cache value +async def set_cache(key: str, value: Dict[str, Any]) -> None: + try: + async with aiofiles.open("cache.json", 'r') as f: + cache_content = await f.read() + parsed = json.loads(cache_content) + except (FileNotFoundError, json.JSONDecodeError): + parsed = {} + + parsed[key] = value + + async with aiofiles.open("cache.json", 'w') as f: + await f.write(json.dumps(parsed)) +```` + + + +### Act with cache + +Let's write a function that will check the cache, get the action, and run it. If the action fails, we'll attempt to "self-heal", i.e. retry it with `page.act` directly. + + +```typescript TypeScript +// Check the cache, get the action, and run it +// If selfHeal is true, we'll attempt to self-heal if the action fails +async function actWithCache(page: Page, key: string, prompt: string, selfHeal = false) { + try { + const cacheExists = await getCache(key); + + let action: ObserveResult; + if (cacheExists) { + // Get the cached action + action = await getCache(prompt); + } else { + // Get the observe result (the action) + [action] = await page.observe(prompt); + + // Cache the action + await setCache(prompt, action); + } + + // Run the action (no LLM inference) + await page.act(action); + } catch (e) { + console.error(e); + // in selfHeal mode, we'll retry the action + if (selfHeal) { + console.log("Attempting to self-heal..."); + await page.act(prompt); + } + else { + throw e; + } + } + +} + +```` + +```python Python +# Check the cache, get the action, and run it +# If self_heal is true, we'll attempt to self-heal if the action fails +async def act_with_cache(page, key: str, prompt: str, self_heal: bool = False): + try: + cache_exists = await get_cache(key) + + if cache_exists: + # Get the cached action + action = await get_cache(prompt) + else: + # Get the observe result (the action) + actions = await page.observe(prompt) + action = actions[0] + + # Cache the action + await set_cache(prompt, action) + + # Run the action (no LLM inference) + await page.act(action) + except Exception as e: + print(f"Error: {e}") + # in self_heal mode, we'll retry the action + if self_heal: + print("Attempting to self-heal...") + await page.act(prompt) + else: + raise e +```` + + + +You can now use `actWithCache` to run an action with caching: + + +```typescript TypeScript +const prompt = "Click the quickstart link"; +const key = prompt; // Simple cache key +// Attempt cached action or self-heal +await actWithCache(page, key, prompt); +``` + +```python Python +prompt = "Click the quickstart link" +key = prompt # Simple cache key +# Attempt cached action or self-heal +await act_with_cache(page, key, prompt) +``` + + + +## Advanced caching + +The above example is simple, but you may want to cache actions based on the page contents. Also, if you have duplicate prompts, you should use a more unique key. + +We want to leave caching logic up to you, but give you all the tools you need to implement your own caching strategy. + +You can directly access the DOM and accessibility tree from Playwright's page object. Here's an example of how to access the page content: + + +```typescript TypeScript +// Get the page content +const pageContent = await page.content(); +``` + +```python Python +# Get the page content +page_content = await page.content() +``` + + + +You may also want to use the accessibility tree, the DOM, or any other information to create a more unique key. You can do this as you please, with very similar logic to the above example. diff --git a/sdk/stagehand-ts/docs/examples/computer_use.mdx b/sdk/stagehand-ts/docs/examples/computer_use.mdx new file mode 100644 index 0000000..0b545c2 --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/computer_use.mdx @@ -0,0 +1,208 @@ +--- +title: Computer Use Agents +description: Incorporate Computer Use APIs from Anthropic and OpenAI with one line of code in Stagehand. +--- + +## What is a Computer Use Agent? + + +You might've heard of [Claude Computer +Use](https://www.anthropic.com/news/3-5-models-and-computer-use) or [OpenAI's +Computer Using Agent](https://openai.com/index/computer-using-agent/). + +These are powerful tools that can convert natural language into actions on the computer. However, you'd otherwise need to write your own code to convert these actions into Playwright commands. + +Stagehand not only handles the execution of Computer Use outputs, but also lets you hot-swap between OpenAI and Anthropic models with one line of code. + +## How to use a Computer Use Agent in Stagehand + +Stagehand lets you use Computer Use Agents with one line of code: + + +**IMPORTANT! Configure your browser dimensions** + +Computer Use Agents will often return XY-coordinates to click on the screen, so you'll need to configure your browser dimensions. + +If not specified, the default browser dimensions are 1024x768. You can also configure the browser dimensions in the `browserbaseSessionCreateParams` or `localBrowserLaunchOptions` options. + + + +### Configuring browser dimensions + +Browser configuration differs by environment: + + + + +```typescript TypeScript +import { Stagehand } from "@browserbasehq/stagehand"; + +const stagehand = new Stagehand({ +env: "BROWSERBASE", +apiKey: process.env.BROWSERBASE*API_KEY /* API key for authentication _/, +projectId: process.env.BROWSERBASE_PROJECT_ID /_ Project identifier \_/, + + browserbaseSessionCreateParams: { + projectId: process.env.BROWSERBASE_PROJECT_ID!, + browserSettings: { + blockAds: true, + viewport: { + width: 1024, + height: 768, + }, + }, + +}, +}); + +await stagehand.init(); + +```` +```python Python +import os +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + env="BROWSERBASE", + api_key=os.getenv("BROWSERBASE_API_KEY"), # API key for authentication + project_id=os.getenv("BROWSERBASE_PROJECT_ID"), # Project identifier + + browserbase_session_create_params={ + "projectId": os.getenv("BROWSERBASE_PROJECT_ID"), + "browserSettings": { + "blockAds": True, + "viewport": { + "width": 1024, + "height": 768, + }, + }, + }, +)) + +await stagehand.init() +```` + + + + + +```typescript TypeScript +import { Stagehand } from "@browserbasehq/stagehand"; + +const stagehand = new Stagehand({ +env: "LOCAL", +localBrowserLaunchOptions: { +headless: false, +viewport: { +width: 1024, +height: 768, +}, +} +}); + +await stagehand.init(); + +```` +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + env="LOCAL", + local_browser_launch_options={ + "headless": False, + "viewport": { + "width": 1024, + "height": 768, + }, + } +)) + +await stagehand.init() +```` + + + + + +### Direct your Computer Use Agent + +Call `execute` on the agent to assign a task to the agent. + + +```typescript TypeScript +// Navigate to a website +await stagehand.page.goto("https://www.google.com"); + +const agent = stagehand.agent({ +// You can use either OpenAI or Anthropic +provider: "openai", +// The model to use (claude-3-7-sonnet-latest for Anthropic) +model: "computer-use-preview", + + // Customize the system prompt + instructions: `You are a helpful assistant that can use a web browser. + Do not ask follow up questions, the user will trust your judgement.`, + + // Customize the API key + options: { + apiKey: process.env.OPENAI_API_KEY, + }, + +}); + +// Execute the agent +await agent.execute("Apply for a library card at the San Francisco Public Library"); + +```` + +```python Python +import os + +# Navigate to a website +await stagehand.page.goto("https://www.google.com") + +agent = stagehand.agent({ + # The model to use + model="computer-use-preview", + + # Customize the system prompt + instructions="You are a helpful assistant that can use a web browser. Do not ask follow up questions, the user will trust your judgement.", + + # Customize the API key + options={ + "apiKey": os.getenv("OPENAI_API_KEY"), + }, +}) + +# Execute the agent +await agent.execute("Apply for a library card at the San Francisco Public Library") +```` + + + +You can also define the maximum number of steps the agent can take with: + + +```typescript TypeScript +await agent.execute({ + instructions: "Apply for a library card at the San Francisco Public Library", + maxSteps: 10, +}); +``` + +```python Python +await agent.execute( + "Apply for a library card at the San Francisco Public Library", + max_steps=10, +) +``` + + diff --git a/sdk/stagehand-ts/docs/examples/contributing.mdx b/sdk/stagehand-ts/docs/examples/contributing.mdx new file mode 100644 index 0000000..0aede30 --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/contributing.mdx @@ -0,0 +1,53 @@ +--- +title: "Contribute to Stagehand" +description: "Best practices for making a meaningful contribution to Stagehand" +--- + +# Codeowners and Subject-Matter Experts + +Any contribution must be explicitly approved by a codeowner. Officially, Stagehand codeowners are as follows: + +- [**Paul Klein**](https://github.com/pkiv) +- [**Miguel Gonzalez**](https://github.com/miguelg719) +- [**Sean McGuire**](https://github.com/seanmcguire12) +- [**Anirudh Kamath**](https://github.com/kamath) +- [**Sameel Arif**](https://github.com/sameelarif) +- [**Filip Michalsky**](https://github.com/filip-michalsky) + +Special thanks to [Jeremy Press](https://github.com/jeremypress), [Navid Pour](https://github.com/navidkpr), and [all the contributors](https://github.com/browserbase/stagehand/graphs/contributors) for your help in making Stagehand the best browser automation framework. + +**_Please do not hesitate to reach out to anyone listed here in the [public Slack channel](https://join.slack.com/t/stagehand-dev/shared_invite/zt-38khc8iv5-T2acb50_0OILUaX7lxeBOg)_** + +## General Workflow + +Get listed as [one of our beloved contributors](https://github.com/browserbase/stagehand/graphs/contributors)! + +1. **Discuss your proposed contribution before starting.** Not doing this runs you the risk of entirely discarding something you put considerable time and effort into. You can DM Miguel on [Slack](https://stagehand.dev/slack) for a 1on1 call. +2. **Open a Pull Request.** Create a fork of this repository, and follow [GitHub’s instructions to create a Pull Request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request-from-a-fork). This allows our team to review your contribution and leave comments. +3. **Wait for Review**. We’ll do our best to get to your contribution as soon as possible. If it’s been 2-3 days and you have yet to receive any comments, DM Miguel on [Slack](https://stagehand.dev/slack) +4. **Merge into `evals` branch.** We don’t let external contributors [run our CI via GitHub Actions](https://github.com/browserbase/stagehand/blob/main/.github/workflows/ci.yml) to prevent spam and misuse. If your contribution passes an initial screen, we’ll run our evals on it + + 1. By default, all PRs run the following tests that you can also run from the repo source: + 1. Lint (`npm run lint`) - Runs `prettier` and `eslint`. If this fails, you can most likely run `npm run format` to fix some simple linting errors. + 2. Build (`npm run build`) - Lints and builds TS → JS in `dist/` via `tsup` + 3. End-to-End (`npm run e2e`) - These are deterministic end-to-end Playwright tests to ensure the integrity of basic Playwright functionality of [`stagehand.page`](http://stagehand.page) and `stagehand.context` as well as compatibility with the Browserbase API + 4. Combination (`npm run evals category combination`) - This runs AI-based end-to-end tests using combinations of `act`, `extract`, and `observe` + 2. If you’re changing anything about `act`, `extract`, or `observe` itself, we might also run specific act/extract/observe evals to ensure existing functionality doesn’t significantly drop. + + ![CI](/images/CI.png) + +5. **Cleanup and merge to main**. Once it’s in `evals`, unfortunately the original contributor can’t make any further changes. The internal Stagehand team will be responsible for cleaning up the code and bringing it into main. + +## Contribution Guidelines + +1. **Use draft PRs.** If your PR is a work in progress, please convert it to a draft (see below) while you’re working on it, and mark it for review/add reviewers when you’re ready. This helps us prevent clutter in the review queue. + + ![Draft PR](/images/pr_draft.png) + +2. **Provide a reproducible test plan.** Include an eval (preferred) or example. We can’t merge your PR if we can’t run anything that specifically highlights your contribution. + 1. Write a script in [`evals/tasks`](https://github.com/browserbase/stagehand/tree/main/evals/tasks) as `someTask.ts` + 2. Add your script to [`evals.config.json`](https://github.com/browserbase/stagehand/blob/main/evals/evals.config.json) with default category `combination` (_or act/extract/observe if you’re_ _only_ _testing_ _act/extract/observe_). +3. **Add a changeset.** Run `npx changeset` in TS or `uvx changeset` in Python to add a changeset that will directly reflect in the `CHANGELOG` in the upcoming release. + 1. `patch` - no net new functionality to an end-user + 2. `minor` - some net new functionality to an end-user (new function parameter, new exposed type, etc.) + 3. `major` - you shouldn’t be committing a major change diff --git a/sdk/stagehand-ts/docs/examples/custom_llms.mdx b/sdk/stagehand-ts/docs/examples/custom_llms.mdx new file mode 100644 index 0000000..c794a4f --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/custom_llms.mdx @@ -0,0 +1,170 @@ +--- +title: LLM Customization +description: Stagehand supports a wide variety of LLMs. You can use any LLM that supports structured outputs with our existing clients, or by writing a custom LLM provider. +--- + + + Small models on **Ollama** are really difficult to get consistent structured + outputs from. Though these models are "supported" via an OpenAI-compatible + API, we do not recommend them yet for Stagehand. + + +## Supported LLMs + +Stagehand supports most of the hosted LLM providers. The full list of supported models is below: + +### Providers + + + - **OpenAI** - **Anthropic** - **Google** - **xAI** - **Azure** - **Groq** - + **Cerebras** - **TogetherAI** - **Mistral** - **DeepSeek** - **Perplexity** - + **Ollama** + + +### Model Name Format + +Stagehand takes the model name in the format of `provider/model`. + +For example, to use Gemini 2.0 Flash, you would pass in `google/gemini-2.0-flash`. + +### Using a Provider + +You can pass in one of these LLMs to the `llm` property in the `Stagehand` constructor. + + +```typescript TypeScript +const stagehand = new Stagehand({ + modelName: "google/gemini-2.0-flash", + modelClientOptions: { + apiKey: process.env.GOOGLE_API_KEY, + }, +}); +``` + +```python Python +stagehand = Stagehand( + model="google/gemini-2.0-flash", + model_client_options={"apiKey": os.getenv("GOOGLE_API_KEY")}, +) +``` + + + +## Custom LLMs + +Custom LLMs are currently only supported in TypeScript. + +If you'd like to use a custom LLM, you can do so by providing a custom `llmProvider` function to the `Stagehand` constructor. + +The only requirement for an LLM to be used with Stagehand is that it supports structured outputs. + +### OpenAI-compatible APIs + +Most LLMs are OpenAI-compatible, and thus can be used with Stagehand as long as they support structured outputs. This includes models like Google Gemini, Ollama, and most Llama models including Groq, Cerebras, and more. + +To get started, you can use the [OpenAI external client](https://github.com/browserbase/stagehand/blob/main/examples/external_clients/customOpenAI.ts) as a template to create a client for your model. + +```ts {7-13} +import { Stagehand } from "@browserbasehq/stagehand"; +import { CustomOpenAIClient } from "./external_clients/customOpenAI"; +import OpenAI from "openai"; + +const stagehand = new Stagehand({ + ...StagehandConfig, + llmClient: new CustomOpenAIClient({ + modelName: "llama3.3", + client: new OpenAI({ + apiKey: "ollama", + baseURL: "http://localhost:11434/v1", + }), + }), +}); + +await stagehand.init(); +``` + +### Vercel AI SDK + +The [Vercel AI SDK](https://sdk.vercel.ai/providers/ai-sdk-providers) is a popular library for interacting with LLMs. You can use any of the providers supported by the Vercel AI SDK to create a client for your model, **as long as they support structured outputs**. + +Vercel AI SDK supports providers for OpenAI, Anthropic, and Google, along with support for **Amazon Bedrock** and **Azure OpenAI**. + +To get started, you'll need to install the `ai` package and the provider you want to use. For example, to use Amazon Bedrock, you'll need to install the `@ai-sdk/amazon-bedrock` package. + +You'll also need to use the [Vercel AI SDK external client](https://github.com/browserbase/stagehand/blob/main/examples/external_clients/aisdk.ts) as a template to create a client for your model. + + + + ```bash + npm install ai @ai-sdk/amazon-bedrock + ``` + + + + ```bash + pnpm install ai @ai-sdk/amazon-bedrock + ``` + + + + ```bash + yarn add ai @ai-sdk/amazon-bedrock + ``` + + + + +To get started, you can use the [Vercel AI SDK external client](https://github.com/browserbase/stagehand/blob/84f810b4631291307a32a47addad7e26e9c1deb3/examples/external_clients/aisdk.ts) as a template to create a client for your model. + +```ts +// Install/import the provider you want to use. +// For example, to use OpenAI, import `openai` from @ai-sdk/openai +import { bedrock } from "@ai-sdk/amazon-bedrock"; +import { AISdkClient } from "./aisdkClient.ts"; + +const stagehand = new Stagehand({ + llmClient: new AISdkClient({ + model: bedrock("anthropic.claude-3-7-sonnet-20250219-v1:0"), + }), +}); +``` + +### LangChain + +LangChain is a popular library for building LLM applications. You can use any of the providers supported by LangChain to create a client for your model, **as long as they support structured outputs**. + +To get started, you'll need to install the `langchain` package and the provider you want to use. For example, to use OpenAI, you'll need to install the `@langchain/openai` package. You'll also need to install the `zod-to-json-schema` package to convert your Zod schema to a JSON schema. + +You'll also want to add the [LangChain external client](https://github.com/browserbase/stagehand/blob/84f810b4631291307a32a47addad7e26e9c1deb3/examples/external_clients/langchain.ts) to your Stagehand project. + + + + ```bash + npm install langchain @langchain/openai zod-to-json-schema + ``` + + + + ```bash + pnpm install langchain @langchain/openai zod-to-json-schema + ``` + + + + ```bash + yarn add langchain @langchain/openai zod-to-json-schema + ``` + + + + +Next, you can use the [LangChain external client](https://github.com/browserbase/stagehand/blob/84f810b4631291307a32a47addad7e26e9c1deb3/examples/external_clients/langchain.ts) as a template to create a Stagehand LLM client for your model. + +```ts +import { ChatOpenAI } from "@langchain/openai"; +import { LangchainClient } from "./external_clients/langchain"; + +const stagehand = new Stagehand({ + llmClient: new LangchainClient(new ChatOpenAI({ model: "gpt-4o" })), +}); +``` diff --git a/sdk/stagehand-ts/docs/examples/customize_browser.mdx b/sdk/stagehand-ts/docs/examples/customize_browser.mdx new file mode 100644 index 0000000..84b9068 --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/customize_browser.mdx @@ -0,0 +1,228 @@ +--- +title: Browser Customization +description: Stagehand can run on any Chromium-based browser, like Chrome, Edge, Arc, and Brave. +--- + +## Browserbase + +Stagehand is built and maintained by [Browserbase](https://www.browserbase.com/). As a result, Stagehand has supreme performance and reliability on Browserbase. + +The [Browserbase SDK](https://docs.browserbase.com/reference/sdk/nodejs) is very powerful, and allows you to handle a wide variety of use cases such as: + +- Captcha solving +- Custom contexts and extensions +- Live browser view +- Proxy rotation +- Session recordings +- Uploads/downloads + +Using Browserbase is as easy as setting `env: "BROWSERBASE"` in your Stagehand constructor: + + +```typescript TypeScript +const stagehand = new Stagehand({ + env: "BROWSERBASE", + // Stagehand will automatically read your Browserbase API key and project ID from your environment variables + // If you'd like to pass in your own API key and project ID, you can do so like this: + apiKey: process.env.BROWSERBASE_API_KEY, + projectId: process.env.BROWSERBASE_PROJECT_ID, +}); +``` + +```python Python +import os +from stagehand import Stagehand, StagehandConfig + +# Build a unified configuration object for Stagehand +config = StagehandConfig( + env="BROWSERBASE", + # Stagehand will automatically read your Browserbase API key and project ID from your environment variables + # If you'd like to pass in your own API key and project ID, you can do so like this: + api_key=os.getenv("BROWSERBASE_API_KEY"), + project_id=os.getenv("BROWSERBASE_PROJECT_ID"), +) + +# Create a Stagehand client using the configuration object. +stagehand = Stagehand(config) +``` + + + +### Create a Browserbase session + +To create a custom Browserbase session, you can pass in `browserbaseSessionCreateParams` to the `Stagehand` constructor. For full documentation on the `browserbaseSessionCreateParams` object, see the [Browserbase API documentation](https://docs.browserbase.com/reference/api/create-a-session). + + +```typescript TypeScript +const stagehand = new Stagehand({ + env: "BROWSERBASE", + browserbaseSessionCreateParams: { + projectId: "your-project-id", + extensionId: 'your-extension-id', + browserSettings: { + viewport: { + width: 1920, + height: 1080, + }, + proxies: [ + { + type: 'external', + server: 'your-proxy-server', + username: 'your-proxy-username', + password: 'your-proxy-password', + }, + ], + context: { + id: 'your-context-id', + }, + }, + }, +}); +``` + +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + env="BROWSERBASE", + browserbase_session_create_params={ + "projectId": "your-project-id", + "extensionId": "your-extension-id", + "browserSettings": { + "viewport": { + "width": 1920, + "height": 1080, + }, + "proxies": [ + { + "type": "external", + "server": "your-proxy-server", + "username": "your-proxy-username", + "password": "your-proxy-password", + }, + ], + "context": { + "id": "your-context-id", + }, + }, + }, +)) +``` + + + +### Resume an existing Browserbase session + +You can reconnect to an existing Browserbase session by passing in the `browserbaseSessionId` to the `Stagehand` constructor. + + +```typescript TypeScript +const stagehand = new Stagehand({ + env: "BROWSERBASE", + browserbaseSessionId: "your-session-id", +}); +``` + +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + env="BROWSERBASE", + browserbase_session_id="your-session-id", +)) +``` + + + +You can also pass in `browserbaseSessionCreateParams`, but it will be ignored if `browserbaseSessionId` is provided. + + +```typescript TypeScript +const stagehand = new Stagehand({ + env: "BROWSERBASE", + browserbaseSessionId: "your-session-id", + + // This will be ignored because we're providing a browserbaseSessionId + browserbaseSessionCreateParams: { + projectId: "your-project-id", + }, +}); +``` + +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + env="BROWSERBASE", + browserbase_session_id="your-session-id", + + # This will be ignored because we're providing a browserbase_session_id + browserbase_session_create_params={ + "projectId": "your-project-id", + }, +)) +``` + + + +## Local Browser Customization + +Stagehand allows you to customize your local browser in a few different ways. + +You can use [`localBrowserLaunchOptions` type](https://github.com/browserbase/stagehand/blob/84f810b4631291307a32a47addad7e26e9c1deb3/types/stagehand.ts#L134-L174) to customize the browser you want Stagehand to use. + + +```typescript TypeScript +const stagehand = new Stagehand({ + localBrowserLaunchOptions: { + cdpUrl: 'your-cdp-url', + } +}) +``` + +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + local_browser_launch_options={ + "cdp_url": "your-cdp-url", + } +)) +``` + + + +### Use your personal browser + +The `cdpUrl` config is **only supported in Stagehand 2.0+**. + +You can use Stagehand with any Chromium-based browser, like Arc, Brave, Chrome, Dia, and Edge! To do so, you can pass in a `cdpUrl` to connect to a remote browser, or pass in an `executablePath` to use a local browser executable. + +You'll also need to open your browser in "debug" mode. For example, if you're using Chrome on a Mac, you can open it with the following command: + +```bash +open -a "Google Chrome" --args --remote-debugging-port=9222 +``` + +This will open Chrome with remote debugging enabled on port 9222. You can then pass in the `cdpUrl` to Stagehand like so: + + +```typescript TypeScript +const stagehand = new Stagehand({ + localBrowserLaunchOptions: { + cdpUrl: 'http://localhost:9222', + }, +}); +``` + +```python Python +from stagehand import Stagehand, StagehandConfig + +stagehand = Stagehand(StagehandConfig( + local_browser_launch_options={ + "cdp_url": "http://localhost:9222", + }, +)) +``` + + diff --git a/sdk/stagehand-ts/docs/examples/nextjs.mdx b/sdk/stagehand-ts/docs/examples/nextjs.mdx new file mode 100644 index 0000000..f70d5e0 --- /dev/null +++ b/sdk/stagehand-ts/docs/examples/nextjs.mdx @@ -0,0 +1,160 @@ +--- +title: Stagehand in Next.js +description: Next.js is a popular framework for developing web-based applications in production. It powers Stagehand apps like [Director](https://director.ai), [Brainrot](https://brainrot.run) and [Open Operator](https://operator.browserbase.com). +--- + + + Clone our [GitHub + repo](https://github.com/browserbase/stagehand-nextjs-quickstart) to get + started with Stagehand in Next.js. + + +## Add Stagehand to an existing Next.js project + +If you'd like to add Stagehand to an existing Next.js project, you can do so by installing the dependencies: + + + + ```bash + npm install @browserbasehq/stagehand @browserbasehq/sdk playwright zod + ``` + + + + ```bash + pnpm add @browserbasehq/stagehand @browserbasehq/sdk playwright zod + ``` + + + + ```bash + yarn add @browserbasehq/stagehand @browserbasehq/sdk playwright zod + ``` + + + + +### Write a server action + +Next, let's define our `main` function as a server action in `app/stagehand/main.ts`. This file will have the following three functions: + +1. **`main`: Run the main Stagehand script** +2. **`runStagehand`: Initialize and run the `main` function** +3. **`startBBSSession`: Start a Browserbase session** + +```ts app/stagehand/main.ts +// 🤘 Welcome to Stagehand! +// This file is from the [Stagehand docs](https://docs.stagehand.dev/sections/examples/nextjs). + +"use server"; + +import { Stagehand } from "@browserbasehq/stagehand"; +import { z } from "zod/v3"; +import { Browserbase } from "@browserbasehq/sdk"; + +/** + * Run the main Stagehand script + */ +async function main(stagehand: Stagehand) { + // You can use the `page` instance to write any Playwright code + // For more info: https://playwright.dev/docs/pom + const page = stagehand.page; + + // In this example, we'll get the title of the Stagehand quickstart page + await page.goto("https://docs.stagehand.dev/"); + await page.act("click the quickstart link"); + const { title } = await page.extract({ + instruction: "extract the main heading of the page", + schema: z.object({ + title: z.string(), + }), + }); + + return title; +} + +/** + * Initialize and run the main() function + */ +export async function runStagehand(sessionId?: string) { + const stagehand = new Stagehand({ + env: "BROWSERBASE", + apiKey: process.env.BROWSERBASE_API_KEY, + projectId: process.env.BROWSERBASE_PROJECT_ID, + verbose: 1, + logger: console.log, + browserbaseSessionID: sessionId, + disablePino: true, + }); + await stagehand.init(); + await main(stagehand); + await stagehand.close(); +} + +/** + * Start a Browserbase session + */ +export async function startBBSSession() { + const browserbase = new Browserbase(); + const session = await browserbase.sessions.create({ + projectId: process.env.BROWSERBASE_PROJECT_ID!, + }); + const debugUrl = await browserbase.sessions.debug(session.id); + return { + sessionId: session.id, + debugUrl: debugUrl.debuggerFullscreenUrl, + }; +} +``` + +### Create a client component + +Next, let's create a client component that will start a Browserbase session and run the `main` function with the server actions we just defined. We'll first create a Browserbase session and embed the session in an iframe before running the `main` function. + +```tsx app/components/stagehandEmbed.tsx +"use client"; + +import { useCallback, useState } from "react"; +import { runStagehand, startBBSSession } from "@/app/stagehand/main"; + +export function StagehandEmbed() { + const [sessionId, setSessionId] = useState(null); + const [debugUrl, setDebugUrl] = useState(null); + + const startSession = useCallback(async () => { + const { sessionId, debugUrl } = await startBBSSession(); + setSessionId(sessionId); + setDebugUrl(debugUrl); + await runStagehand(sessionId); + }, []); + + return ( +
+ {!sessionId && } + {sessionId && debugUrl && ( + +
+ +
+ +
+ + ) + +} diff --git a/sdk/stagehand-ts/eslint.config.mjs b/sdk/stagehand-ts/eslint.config.mjs new file mode 100644 index 0000000..c0d192c --- /dev/null +++ b/sdk/stagehand-ts/eslint.config.mjs @@ -0,0 +1,12 @@ +import globals from "globals"; +import pluginJs from "@eslint/js"; +import tseslint from "typescript-eslint"; + +/** @type {import('eslint').Linter.Config[]} */ +export default [ + { files: ["**/*.{js,mjs,cjs,ts}"] }, + { languageOptions: { globals: globals.browser } }, + { ignores: ["**/dist/**", "lib/dom/build/**"] }, + pluginJs.configs.recommended, + ...tseslint.configs.recommended, +]; diff --git a/sdk/stagehand-ts/eval-summary.json b/sdk/stagehand-ts/eval-summary.json new file mode 100644 index 0000000..bb0f90f --- /dev/null +++ b/sdk/stagehand-ts/eval-summary.json @@ -0,0 +1,71 @@ +{ + "experimentName": "agent/onlineMind2Web_browserbase_20251002204912", + "passed": [], + "failed": [ + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + }, + { + "eval": "agent/onlineMind2Web", + "model": "computer-use-preview-10-2025", + "categories": ["external_agent_benchmarks"] + } + ], + "categories": { + "combination": null, + "regression": null, + "extract": null, + "act": null, + "llm_clients": null, + "experimental": null, + "observe": null, + "targeted_extract": null, + "agent": null, + "external_agent_benchmarks": 0 + }, + "models": { + "computer-use-preview-10-2025": 0 + } +} diff --git a/sdk/stagehand-ts/evals/args.ts b/sdk/stagehand-ts/evals/args.ts new file mode 100644 index 0000000..c1e584e --- /dev/null +++ b/sdk/stagehand-ts/evals/args.ts @@ -0,0 +1,240 @@ +import process from "process"; +import { EvalCategorySchema } from "@/types/evals"; +import chalk from "chalk"; +import { dedent } from "./utils"; + +const HELP_REGEX = /^(?:--?)?(?:h|help)$/i; +const MAN_REGEX = /^(?:--?)?man$/i; + +const rawArgs = process.argv.slice(2); + +const parsedArgs: { + evalName?: string; + env?: string; + api?: string; + trials?: number; + concurrency?: number; + provider?: string; + dataset?: string; + max_k?: number; + leftover: string[]; +} = { + leftover: [], +}; + +for (const arg of rawArgs) { + if (arg.startsWith("env=")) { + parsedArgs.env = arg.split("=")[1]?.toLowerCase(); + } else if (arg.startsWith("api=")) { + parsedArgs.api = arg.split("=")[1]?.toLowerCase(); + } else if (arg.startsWith("name=")) { + parsedArgs.evalName = arg.split("=")[1]; + } else if (arg.startsWith("trials=")) { + const val = parseInt(arg.split("=")[1], 10); + if (!isNaN(val)) { + parsedArgs.trials = val; + } + } else if (arg.startsWith("concurrency=")) { + const val = parseInt(arg.split("=")[1], 10); + if (!isNaN(val)) { + parsedArgs.concurrency = val; + } + } else if (arg.startsWith("provider=")) { + parsedArgs.provider = arg.split("=")[1]?.toLowerCase(); + } else if (arg.startsWith("--dataset=")) { + parsedArgs.dataset = arg.split("=")[1]?.toLowerCase(); + } else if (arg.startsWith("max_k=")) { + const val = parseInt(arg.split("=")[1], 10); + if (!isNaN(val)) { + parsedArgs.max_k = val; + } + } else { + parsedArgs.leftover.push(arg); + } +} + +/** Apply environment defaults or overrides */ +if (parsedArgs.env === "browserbase") { + process.env.EVAL_ENV = "BROWSERBASE"; +} else if (parsedArgs.env === "local") { + process.env.EVAL_ENV = "LOCAL"; +} + +if (parsedArgs.api === "true") { + process.env.USE_API = "true"; +} else if (parsedArgs.api === "false") { + process.env.USE_API = "false"; +} + +if (parsedArgs.trials !== undefined) { + process.env.EVAL_TRIAL_COUNT = String(parsedArgs.trials); +} +if (parsedArgs.concurrency !== undefined) { + process.env.EVAL_MAX_CONCURRENCY = String(parsedArgs.concurrency); +} +if (parsedArgs.max_k !== undefined) { + process.env.EVAL_MAX_K = String(parsedArgs.max_k); +} +if (parsedArgs.dataset !== undefined) { + process.env.EVAL_DATASET = parsedArgs.dataset; +} + +const DEFAULT_EVAL_CATEGORIES = process.env.EVAL_CATEGORIES + ? process.env.EVAL_CATEGORIES.split(",") + : [ + "observe", + "act", + "combination", + "extract", + "experimental", + "targeted_extract", + "regression_llm_providers", + "regression", + "llm_clients", + "agent", + "external_agent_benchmarks", + ]; + +const providerDefault = process.env.EVAL_PROVIDER ?? undefined; + +function buildUsage(detailed = false): string { + const header = chalk.blue.bold("Stagehand • Eval Runner"); + const synopsis = chalk.cyan( + `pnpm run evals [key=value]… [category ] | name=`, + ); + + const body = dedent` + ${chalk.magenta.underline("Keys\n")} + ${chalk.cyan("env".padEnd(12))} ${"target environment".padEnd(24)} + (default ${chalk.dim("LOCAL")}) [${chalk.yellow("BROWSERBASE")}, ${chalk.yellow("LOCAL")}] ${chalk.gray("← LOCAL sets api=false")} + + ${chalk.cyan("api".padEnd(12))} ${"use the Stagehand API".padEnd(24)} + (default ${chalk.dim("false")}) [${chalk.yellow("true")}, ${chalk.yellow("false")}] + + ${chalk.cyan("trials".padEnd(12))} ${"number of trials".padEnd(24)} + (default ${chalk.dim("10")}) + + ${chalk.cyan("concurrency".padEnd(12))} ${"max parallel sessions".padEnd(24)} + (default ${chalk.dim("10")}) + + ${chalk.cyan("provider".padEnd(12))} ${"override LLM provider".padEnd(24)} + (default ${chalk.dim(providerDefault)}) [${chalk.yellow("OPENAI")}, ${chalk.yellow("ANTHROPIC")}, ${chalk.yellow("GOOGLE")}, ${chalk.yellow("TOGETHER")}, ${chalk.yellow("GROQ")}, ${chalk.yellow("CEREBRAS")}] + + ${chalk.cyan("max_k".padEnd(12))} ${"max test cases per dataset".padEnd(24)} + (default ${chalk.dim("25")}) + + ${chalk.cyan("--dataset".padEnd(12))} ${"filter dataset for benchmarks".padEnd(24)} + (optional) [${chalk.yellow("gaia")}, ${chalk.yellow("webvoyager")}] + + + ${chalk.magenta.underline("Positional filters\n")} + category one of: ${DEFAULT_EVAL_CATEGORIES.map((c) => + chalk.yellow(c), + ).join(", ")} + + ${chalk.magenta.underline("\nExamples")} + + ${chalk.dim("# Run every evaluation locally with default settings")} + + ${chalk.green("pnpm run evals")} + + + ${chalk.dim("# Same as above but in Browserbase with three trials")} + + ${chalk.green("pnpm run evals")} ${chalk.cyan("env=")}${chalk.yellow("BROWSERBASE")} ${chalk.cyan( + "trials=", + )}${chalk.yellow("3")} + + + ${chalk.dim("# Run evals using the Stagehand API")} + + ${chalk.green("pnpm run evals")} ${chalk.cyan("env=")}${chalk.yellow("BROWSERBASE")} ${chalk.cyan( + "api=", + )}${chalk.yellow("true")} + + + ${chalk.dim( + "# Run evals from only the 'act' category with a max of 4 running at any given time", + )} + + ${chalk.green("pnpm run evals")} ${chalk.cyan("category")} ${chalk.yellow("act")} ${chalk.cyan( + "concurrency=", + )}${chalk.yellow("4")} + + + ${chalk.dim("# Execute a specific eval by filename")} + + ${chalk.green("pnpm run evals")} ${chalk.cyan("name=")}${chalk.yellow("my_eval_name")} + `; + + if (!detailed) + return `${header}\n\n${synopsis}\n\nFor more details: ${chalk.bold( + "pnpm run evals -man\n", + )}`; + + const envSection = dedent` + ${chalk.magenta.underline("\nEnvironment variables\n")} + EVAL_ENV overridable via ${chalk.cyan("env=")} + + EVAL_TRIAL_COUNT overridable via ${chalk.cyan("trials=")} + + EVAL_MAX_CONCURRENCY overridable via ${chalk.cyan("concurrency=")} + + EVAL_PROVIDER overridable via ${chalk.cyan("provider=")} + + USE_API overridable via ${chalk.cyan("api=true")} + `; + + return `${header}\n\n${synopsis}\n\n${body}\n${envSection}\n`; +} + +const wantsHelp = rawArgs.some((a) => HELP_REGEX.test(a)); +const wantsMan = rawArgs.some((a) => MAN_REGEX.test(a)); + +if (wantsHelp || wantsMan) { + console.log(buildUsage(wantsMan)); + process.exit(0); +} + +let filterByCategory: string | null = null; +let filterByEvalName: string | null = null; + +if (parsedArgs.evalName) { + filterByEvalName = parsedArgs.evalName; +} + +if (!filterByEvalName && parsedArgs.leftover.length > 0) { + if (parsedArgs.leftover[0].toLowerCase() === "category") { + filterByCategory = parsedArgs.leftover[1]; + if (!filterByCategory) { + console.error(chalk.red("Error: Category name not specified.")); + process.exit(1); + } + try { + EvalCategorySchema.parse(filterByCategory); + } catch { + console.error( + chalk.red( + `Error: Invalid category "${filterByCategory}". Valid categories are: ${DEFAULT_EVAL_CATEGORIES.join( + ", ", + )}`, + ), + ); + process.exit(1); + } + } else { + // If leftover[0] is not "category", interpret it as a task/eval name + filterByEvalName = parsedArgs.leftover[0]; + } +} + +if (parsedArgs.provider !== undefined) { + process.env.EVAL_PROVIDER = parsedArgs.provider; +} + +export { + filterByCategory, + filterByEvalName, + DEFAULT_EVAL_CATEGORIES, + parsedArgs, +}; diff --git a/sdk/stagehand-ts/evals/assets/cart.html b/sdk/stagehand-ts/evals/assets/cart.html new file mode 100644 index 0000000..cf7af6d --- /dev/null +++ b/sdk/stagehand-ts/evals/assets/cart.html @@ -0,0 +1,22 @@ + + + + + + Document + + + +
+ + diff --git a/sdk/stagehand-ts/evals/assets/peeler.html b/sdk/stagehand-ts/evals/assets/peeler.html new file mode 100644 index 0000000..75417f1 --- /dev/null +++ b/sdk/stagehand-ts/evals/assets/peeler.html @@ -0,0 +1,47 @@ + + + + + + Document + + +

Welcome to Our Page

+ +
+
+

Knife Set

+

+ High-quality stainless steel knives for all your cooking needs.my stuff + more stuff +

+
+ +
+
+
+

Peeler

+

The ultimate tool for peeling fruits and vegetables.

+
+ +
+ +
hi world
+
+

+ Baseball evolved from older + bat-and-ball games + already being played in England by the mid-18th century. This game was + brought by immigrants to North America, + where the modern version developed. +

+ + diff --git a/sdk/stagehand-ts/evals/cli.ts b/sdk/stagehand-ts/evals/cli.ts new file mode 100644 index 0000000..9560659 --- /dev/null +++ b/sdk/stagehand-ts/evals/cli.ts @@ -0,0 +1,548 @@ +#!/usr/bin/env node +import process from "process"; +import chalk from "chalk"; +import fs from "fs"; +import path from "path"; +import { spawn } from "child_process"; + +const CONFIG_PATH = path.join(__dirname, "evals.config.json"); + +interface Config { + defaults: { + env: string; + trials: number; + concurrency: number; + provider: string | null; + model: string | null; + api: boolean; + }; + benchmarks: Record< + string, + { + limit: number; + filters?: string[]; + timeout?: number; + } + >; + tasks: Array<{ name: string; categories: string[] }>; +} + +function loadConfig(): Config { + return JSON.parse(fs.readFileSync(CONFIG_PATH, "utf-8")); +} + +function saveConfig(config: Config): void { + fs.writeFileSync(CONFIG_PATH, JSON.stringify(config, null, 2)); +} + +function printHelp(): void { + console.log( + chalk.yellow(`⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⢠⡾⠻⣶⡀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⢠⡶⠛⢳⡆⠀⠀⠀⠀⢸⡇⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⢸⣷⠶⣦⣴⠶⣾⡇⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⢸⡇⠀⢸⡇⠀⢸⡇⠀⢸⡇⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠘⠷⣤⢾⡏⠉⠉⠉⠙⣾⡇⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⢸⡇⠀⠀⠀⠀⠈⣻⡿⠟⠂⠀⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⠈⣷⠀⠀⠀⠀⢰⡏⠀⠀⠀⢀⣿⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⠀⠙⣷⡀⠀⠀⠀⠀⠀⠀⢀⡾⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠈⠙⠷⣦⣤⣤⣴⠾⠋⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ +⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀`), + ); + console.log(chalk.yellow.bold("\nStagehand Evals CLI")); + console.log(chalk.cyan("\nevals [options]\n")); + + console.log(chalk.magenta.underline("Commands")); + console.log(" run Execute evals or benchmarks"); + console.log(" list List available evals/benchmarks"); + console.log(" config Get/set default configuration"); + console.log(" help Show this help message\n"); + + console.log(chalk.magenta.underline("Examples")); + console.log(chalk.dim(" # Run all custom evals")); + console.log(chalk.green(" evals run all\n")); + + console.log(chalk.dim(" # Run specific category")); + console.log( + chalk.green(" evals run act") + chalk.cyan(" -e browserbase -t 5\n"), + ); + + console.log(chalk.dim(" # Run specific eval")); + console.log(chalk.green(" evals run login\n")); + + console.log(chalk.dim(" # Run benchmark")); + console.log( + chalk.green(" evals run benchmark:onlineMind2Web") + + chalk.cyan(" -l 10 -f difficulty=easy\n"), + ); + + console.log(chalk.dim(" # Configure defaults")); + console.log(chalk.green(" evals config set env browserbase")); + console.log(chalk.green(" evals config set trials 5\n")); + + console.log(chalk.magenta.underline("Options")); + console.log( + chalk.cyan(" -e, --env".padEnd(20)) + "Environment: local|browserbase", + ); + console.log( + chalk.cyan(" -t, --trials".padEnd(20)) + "Number of trials per eval", + ); + console.log( + chalk.cyan(" -c, --concurrency".padEnd(20)) + "Max parallel sessions", + ); + console.log(chalk.cyan(" -m, --model".padEnd(20)) + "Model override"); + console.log(chalk.cyan(" -p, --provider".padEnd(20)) + "Provider override"); + console.log(chalk.cyan(" --api".padEnd(20)) + "Use Stagehand API\n"); + + console.log(chalk.dim(" Benchmark-specific:")); + console.log(chalk.cyan(" -l, --limit".padEnd(20)) + "Max tasks to run"); + console.log( + chalk.cyan(" -s, --sample".padEnd(20)) + "Random sample before limit", + ); + console.log( + chalk.cyan(" -f, --filter".padEnd(20)) + "Benchmark filters (key=value)\n", + ); +} + +function handleConfig(args: string[]): void { + const config = loadConfig(); + + if (args.length === 0) { + // Show current config + console.log(chalk.blue.bold("\nCurrent Configuration")); + console.log(chalk.cyan("\nDefaults:")); + Object.entries(config.defaults).forEach(([key, value]) => { + console.log(` ${key}: ${chalk.yellow(value ?? "not set")}`); + }); + return; + } + + if (args[0] === "set" && args.length >= 3) { + const [, key, ...valueParts] = args; + const value = valueParts.join(" "); + + if (!(key in config.defaults)) { + console.error(chalk.red(`Error: Unknown config key "${key}"`)); + console.log( + chalk.dim(`Valid keys: ${Object.keys(config.defaults).join(", ")}`), + ); + process.exit(1); + } + + // Parse value based on type + let parsedValue: string | number | boolean | null = value; + if (key === "trials" || key === "concurrency") { + parsedValue = parseInt(value, 10); + if (isNaN(parsedValue)) { + console.error(chalk.red(`Error: ${key} must be a number`)); + process.exit(1); + } + } else if (key === "api") { + parsedValue = value === "true"; + } else if (value === "null" || value === "none") { + parsedValue = null; + } + + // Type-safe assignment + if (key === "env") { + config.defaults.env = parsedValue as string; + } else if (key === "trials") { + config.defaults.trials = parsedValue as number; + } else if (key === "concurrency") { + config.defaults.concurrency = parsedValue as number; + } else if (key === "provider") { + config.defaults.provider = parsedValue as string | null; + } else if (key === "model") { + config.defaults.model = parsedValue as string | null; + } else if (key === "api") { + config.defaults.api = parsedValue as boolean; + } + saveConfig(config); + console.log(chalk.green(`✓ Set ${key} to ${parsedValue}`)); + } else if (args[0] === "reset") { + const defaultConfig: Config["defaults"] = { + env: "local", + trials: 3, + concurrency: 3, + provider: null, + model: null, + api: false, + }; + + if (args[1] && args[1] in config.defaults) { + const key = args[1]; + // Type-safe reset by key + if (key === "env") { + config.defaults.env = defaultConfig.env; + } else if (key === "trials") { + config.defaults.trials = defaultConfig.trials; + } else if (key === "concurrency") { + config.defaults.concurrency = defaultConfig.concurrency; + } else if (key === "provider") { + config.defaults.provider = defaultConfig.provider; + } else if (key === "model") { + config.defaults.model = defaultConfig.model; + } else if (key === "api") { + config.defaults.api = defaultConfig.api; + } + saveConfig(config); + console.log(chalk.green(`✓ Reset ${args[1]} to default`)); + } else if (!args[1]) { + config.defaults = defaultConfig; + saveConfig(config); + console.log(chalk.green("✓ Reset all settings to defaults")); + } else { + console.error(chalk.red(`Error: Unknown config key "${args[1]}"`)); + process.exit(1); + } + } else if (args[0] === "path") { + console.log(CONFIG_PATH); + } else { + console.error(chalk.red("Error: Invalid config command")); + console.log( + chalk.dim("Usage: evals config [set | reset [key] | path]"), + ); + process.exit(1); + } +} + +function handleList(args: string[]): void { + const config = loadConfig(); + + console.log(chalk.blue.bold("\nAvailable Evals\n")); + + // Group tasks by category + const categories = new Map(); + config.tasks.forEach((task) => { + task.categories.forEach((cat) => { + if (!categories.has(cat)) { + categories.set(cat, []); + } + categories.get(cat)!.push(task.name); + }); + }); + + // Show custom eval categories + console.log(chalk.magenta.underline("Custom Eval Categories")); + Array.from(categories.entries()) + .filter(([cat]) => !cat.includes("external_agent_benchmarks")) + .forEach(([category, tasks]) => { + console.log( + ` ${chalk.cyan(category)} ${chalk.dim(`(${tasks.length} evals)`)}`, + ); + }); + + console.log(chalk.magenta.underline("\nBenchmarks")); + Object.keys(config.benchmarks).forEach((name) => { + const shorthand = `b:${name}`; + console.log( + ` ${chalk.cyan(shorthand.padEnd(20))} ${chalk.dim(`benchmark:${name}`)}`, + ); + }); + + if (args.includes("--detailed") || args.includes("-d")) { + console.log(chalk.magenta.underline("\n\nDetailed Task List")); + categories.forEach((tasks, category) => { + if (!category.includes("external_agent_benchmarks")) { + console.log(chalk.cyan(`\n${category}:`)); + tasks.forEach((task) => { + console.log(` - ${task}`); + }); + } + }); + } else { + console.log( + chalk.yellow( + "\n💡 Tip: Use 'evals list --detailed' to see all individual tasks", + ), + ); + } +} + +function parseArgs(rawArgs: string[]): { + options: Record; + target?: string; + filters: Array<[string, string]>; +} { + const options: Record = {}; + const filters: Array<[string, string]> = []; + let target: string | undefined; + + for (let i = 0; i < rawArgs.length; i++) { + const arg = rawArgs[i]; + + if (arg.startsWith("-")) { + // Handle options + const flagName = arg.replace(/^--?/, ""); + + // Map short flags to long names + const flagMap: Record = { + e: "env", + t: "trials", + c: "concurrency", + m: "model", + p: "provider", + l: "limit", + s: "sample", + f: "filter", + }; + + const optionName = flagMap[flagName] || flagName; + + if (optionName === "api") { + options.api = true; + } else if (optionName === "filter") { + // Parse filter as key=value + const filterValue = rawArgs[++i]; + if (filterValue && filterValue.includes("=")) { + const [key, value] = filterValue.split("="); + filters.push([key, value]); + } + } else { + // Get next value + const value = rawArgs[++i]; + if (value && !value.startsWith("-")) { + // Parse numbers + if ( + ["trials", "concurrency", "limit", "sample"].includes(optionName) + ) { + options[optionName] = parseInt(value, 10); + } else { + options[optionName] = value; + } + } + } + } else if (!target) { + target = arg; + } + } + + return { options, target, filters }; +} + +function handleRun(args: string[]): void { + const config = loadConfig(); + const { options, target, filters } = parseArgs(args); + + // Merge with defaults + const finalOptions = { ...config.defaults, ...options }; + + // Build environment variables + const env = { ...process.env }; + + // Set core environment variables + if (finalOptions.env === "browserbase") { + env.EVAL_ENV = "BROWSERBASE"; + } else { + env.EVAL_ENV = "LOCAL"; + } + + if (finalOptions.api) { + env.USE_API = "true"; + } + + if (finalOptions.trials) { + env.EVAL_TRIAL_COUNT = String(finalOptions.trials); + } + + if (finalOptions.concurrency) { + env.EVAL_MAX_CONCURRENCY = String(finalOptions.concurrency); + } + + if (finalOptions.provider) { + env.EVAL_PROVIDER = finalOptions.provider; + } + + if (finalOptions.model) { + env.EVAL_MODEL_OVERRIDE = finalOptions.model; + } + + // Handle benchmark-specific options + let evalName: string | undefined; + let categoryFilter: string | undefined; + + if (target) { + if (target.startsWith("b:") || target.startsWith("benchmark:")) { + // Running a benchmark + const benchmarkName = target.replace(/^(b:|benchmark:)/, ""); + + if (!config.benchmarks[benchmarkName]) { + console.error(chalk.red(`Error: Unknown benchmark "${benchmarkName}"`)); + console.log( + chalk.dim( + `Available benchmarks: ${Object.keys(config.benchmarks).join(", ")}`, + ), + ); + process.exit(1); + } + + // Map to the actual eval name + const benchmarkMap: Record = { + webbench: "agent/webbench", + gaia: "agent/gaia", + webvoyager: "agent/webvoyager", + osworld: "agent/osworld", + onlineMind2Web: "agent/onlineMind2Web", + }; + + evalName = benchmarkMap[benchmarkName]; + env.EVAL_DATASET = benchmarkName; + + // Set benchmark-specific options + if (options.limit) { + env.EVAL_MAX_K = String(options.limit); + env[`EVAL_${benchmarkName.toUpperCase()}_LIMIT`] = String( + options.limit, + ); + } + + if (options.sample) { + env[`EVAL_${benchmarkName.toUpperCase()}_SAMPLE`] = String( + options.sample, + ); + } + + // Apply filters + filters.forEach(([key, value]) => { + const envKey = `EVAL_${benchmarkName.toUpperCase()}_${key.toUpperCase()}`; + env[envKey] = value; + }); + } else if (target === "all") { + // Run all evals (no filter) + } else if (target.includes("/") || target.includes("*")) { + // Pattern matching - treat as eval name + evalName = target; + } else { + // Check if it's a category + const categories = new Set(); + config.tasks.forEach((task) => { + task.categories.forEach((cat) => categories.add(cat)); + }); + + if (categories.has(target)) { + categoryFilter = target; + } else { + // Assume it's a specific eval name + evalName = target; + } + } + } + + // Build the legacy command + const legacyArgs: string[] = []; + + if (evalName) { + legacyArgs.push(`name=${evalName}`); + } else if (categoryFilter) { + legacyArgs.push("category", categoryFilter); + } + + // Run the existing eval system with our environment + console.log(chalk.blue.bold("\nRunning evals...\n")); + + // Build first if needed + const buildChild = spawn("pnpm", ["run", "build"], { + stdio: "inherit", + shell: true, + }); + + buildChild.on("exit", (buildCode) => { + if (buildCode !== 0) { + process.exit(buildCode || 1); + } + + const compiledEvalPath = path.join(__dirname, "index.eval.js"); + const sourceEvalPath = path.resolve( + __dirname, + "..", + "..", + "evals", + "index.eval.ts", + ); + + let child; + + if (fs.existsSync(compiledEvalPath)) { + child = spawn(process.execPath, [compiledEvalPath, ...legacyArgs], { + env, + stdio: "inherit", + shell: true, + }); + } else { + let tsxCliPath: string | undefined; + try { + // Resolve the local tsx CLI entry within this package installation + // This avoids requiring a globally installed tsx binary + tsxCliPath = require.resolve("tsx/dist/cli.js"); + } catch { + // no-op; will fall back to shell-resolved "tsx" if not found + } + + const tsxArgs = [sourceEvalPath, ...legacyArgs]; + + if (tsxCliPath) { + child = spawn(process.execPath, [tsxCliPath, ...tsxArgs], { + env, + stdio: "inherit", + shell: true, + }); + } else { + child = spawn("tsx", tsxArgs, { + env, + stdio: "inherit", + shell: true, + }); + } + } + + child.on("exit", (code) => { + process.exit(code || 0); + }); + }); +} + +// Main CLI logic +function main(): void { + const args = process.argv.slice(2); + const command = args[0]; + const commandArgs = args.slice(1); + + switch (command) { + case "run": + handleRun(commandArgs); + break; + + case "list": + handleList(commandArgs); + break; + + case "config": + handleConfig(commandArgs); + break; + + case "help": + case "--help": + case "-h": + printHelp(); + break; + + case undefined: + console.error(chalk.red("Error: No command specified")); + printHelp(); + process.exit(1); + break; + + default: + // Check if it's a direct target (backward compatibility) + if (!command.startsWith("-")) { + handleRun(args); + } else { + console.error(chalk.red(`Error: Unknown command "${command}"`)); + printHelp(); + process.exit(1); + } + } +} + +// Run the CLI +main(); diff --git a/sdk/stagehand-ts/evals/core/summary.ts b/sdk/stagehand-ts/evals/core/summary.ts new file mode 100644 index 0000000..ae67c3e --- /dev/null +++ b/sdk/stagehand-ts/evals/core/summary.ts @@ -0,0 +1,69 @@ +import fs from "fs"; +import { tasksByName } from "../taskConfig"; +import type { SummaryResult } from "@/types/evals"; + +export const generateSummary = async ( + results: SummaryResult[], + experimentName: string, +) => { + const passed = results + .filter((r) => r.output._success) + .map((r) => ({ + eval: r.input.name, + model: r.input.modelName, + categories: tasksByName[r.input.name].categories, + })); + + const failed = results + .filter((r) => !r.output._success) + .map((r) => ({ + eval: r.input.name, + model: r.input.modelName, + categories: tasksByName[r.input.name].categories, + })); + + const categorySuccessCounts: Record< + string, + { total: number; success: number } + > = {}; + for (const taskName of Object.keys(tasksByName)) { + const taskCategories = tasksByName[taskName].categories; + const taskResults = results.filter((r) => r.input.name === taskName); + const successCount = taskResults.filter((r) => r.output._success).length; + + for (const cat of taskCategories) { + if (!categorySuccessCounts[cat]) { + categorySuccessCounts[cat] = { total: 0, success: 0 }; + } + categorySuccessCounts[cat].total += taskResults.length; + categorySuccessCounts[cat].success += successCount; + } + } + + const categories: Record = {}; + for (const [cat, counts] of Object.entries(categorySuccessCounts)) { + categories[cat] = Math.round((counts.success / counts.total) * 100); + } + + const models: Record = {}; + const allModels = [...new Set(results.map((r) => r.input.modelName))]; + for (const model of allModels) { + const modelResults = results.filter((r) => r.input.modelName === model); + const successCount = modelResults.filter((r) => r.output._success).length; + models[model] = Math.round((successCount / modelResults.length) * 100); + } + + const formattedSummary = { + experimentName, + passed, + failed, + categories, + models, + }; + + fs.writeFileSync( + "eval-summary.json", + JSON.stringify(formattedSummary, null, 2), + ); + console.log("Evaluation summary written to eval-summary.json"); +}; diff --git a/sdk/stagehand-ts/evals/datasets/gaia/GAIA_web.jsonl b/sdk/stagehand-ts/evals/datasets/gaia/GAIA_web.jsonl new file mode 100644 index 0000000..b6f122b --- /dev/null +++ b/sdk/stagehand-ts/evals/datasets/gaia/GAIA_web.jsonl @@ -0,0 +1,90 @@ +{"task_id": "e1fc63a2-da7a-432f-be78-7c4a95598703", "Level": 1, "Final answer": "17", "id": "level1-0", "web": "https://www.google.com/", "ques": "If Eliud Kipchoge could maintain his record-making marathon pace indefinitely, how many thousand hours would it take him to run the distance between the Earth and the Moon its closest approach? Please use the minimum perigee value on the Wikipedia page for the Moon when carrying out your calculation. Round your result to the nearest 1000 hours and do not use any comma separators if necessary."} +{"task_id": "8e867cd7-cff9-4e6c-867a-ff5ddc2550be", "Level": 1, "Final answer": "3", "id": "level1-1", "web": "https://www.google.com/", "ques": "How many studio albums were published by Mercedes Sosa between 2000 and 2009 (included)? You can use the latest 2022 version of english wikipedia."} +{"task_id": "5d0080cb-90d7-4712-bc33-848150e917d3", "Level": 1, "Final answer": "0.1777", "id": "level1-2", "web": "https://www.google.com/", "ques": "What was the volume in m^3 of the fish bag that was calculated in the University of Leicester paper \"Can Hiccup Supply Enough Fish to Maintain a Dragon\u2019s Diet?\""} +{"task_id": "a1e91b78-d3d8-4675-bb8d-62741b4b68a6", "Level": 1, "Final answer": "3", "id": "level1-3", "web": "https://www.google.com/", "ques": "In the video https://www.youtube.com/watch?v=L1vXCYZAYYM, what is the highest number of bird species to be on camera simultaneously?"} +{"task_id": "46719c30-f4c3-4cad-be07-d5cb21eee6bb", "Level": 1, "Final answer": "Mapping Human Oriented Information to Software Agents for Online Systems Usage", "id": "level1-4", "web": "https://www.google.com/", "ques": "Of the authors (First M. Last) that worked on the paper \"Pie Menus or Linear Menus, Which Is Better?\" in 2015, what was the title of the first paper authored by the one that had authored prior papers?"} +{"task_id": "4b6bb5f7-f634-410e-815d-e673ab7f8632", "Level": 1, "Final answer": "THE CASTLE", "id": "level1-5", "web": "https://www.google.com/", "ques": "In Series 9, Episode 11 of Doctor Who, the Doctor is trapped inside an ever-shifting maze. What is this location called in the official script for the episode? Give the setting exactly as it appears in the first scene heading."} +{"task_id": "b816bfce-3d80-4913-a07d-69b752ce6377", "Level": 1, "Final answer": "fluffy", "id": "level1-6", "web": "https://www.google.com/", "ques": "In Emily Midkiff's June 2014 article in a journal named for the one of Hreidmar's sons that guarded his house, what word was quoted from two different authors in distaste for the nature of dragon depictions?"} +{"task_id": "72e110e7-464c-453c-a309-90a95aed6538", "Level": 1, "Final answer": "Guatemala", "id": "level1-7", "web": "https://www.google.com/", "ques": "Under DDC 633 on Bielefeld University Library's BASE, as of 2020, from what country was the unknown language article with a flag unique from the others?"} +{"task_id": "b415aba4-4b68-4fc6-9b89-2c812e55a3e1", "Level": 1, "Final answer": "diamond", "id": "level1-8", "web": "https://www.google.com/", "ques": "In Nature journal's Scientific Reports conference proceedings from 2012, in the article that did not mention plasmons or plasmonics, what nano-compound is studied? Don't use the prefix nano in your answer if there is one."} +{"task_id": "935e2cff-ae78-4218-b3f5-115589b19dae", "Level": 1, "Final answer": "research", "id": "level1-9", "web": "https://www.google.com/", "ques": "In the year 2022, and before December, what does \"R\" stand for in the three core policies of the type of content that was violated in the public logs on the Legume Wikipedia page?"} +{"task_id": "4fc2f1ae-8625-45b5-ab34-ad4433bc21f8", "Level": 1, "Final answer": "FunkMonk", "id": "level1-10", "web": "https://www.google.com/", "ques": "Who nominated the only Featured Article on English Wikipedia about a dinosaur that was promoted in November 2016?"} +{"task_id": "5188369a-3bbe-43d8-8b94-11558f909a08", "Level": 1, "Final answer": "Annie Levin", "id": "level1-11", "web": "https://www.google.com/", "ques": "What writer is quoted by Merriam-Webster for the Word of the Day from June 27, 2022?"} +{"task_id": "9d191bce-651d-4746-be2d-7ef8ecadb9c2", "Level": 1, "Final answer": "Extremely", "id": "level1-12", "web": "https://www.google.com/", "ques": "Examine the video at https://www.youtube.com/watch?v=1htKBjuUWec.\n\nWhat does Teal'c say in response to the question \"Isn't that hot?\""} +{"task_id": "cabe07ed-9eca-40ea-8ead-410ef5e83f91", "Level": 1, "Final answer": "Louvrier", "id": "level1-13", "web": "https://www.google.com/", "ques": "What is the surname of the equine veterinarian mentioned in 1.E Exercises from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023?"} +{"task_id": "d0633230-7067-47a9-9dbf-ee11e0a2cdd6", "Level": 1, "Final answer": "BaseLabelPropagation", "id": "level1-14", "web": "https://www.google.com/", "ques": "In the Scikit-Learn July 2017 changelog, what other predictor base command received a bug fix? Just give the name, not a path."} +{"task_id": "0383a3ee-47a7-41a4-b493-519bdefe0488", "Level": 1, "Final answer": "Rockhopper penguin", "id": "level1-15", "web": "https://www.google.com/", "ques": "On the BBC Earth YouTube video of the Top 5 Silliest Animal Moments, what species of bird is featured?"} +{"task_id": "11af4e1a-5f45-467d-9aeb-46f4bb0bf034", "Level": 1, "Final answer": "6", "id": "level1-16", "web": "https://www.google.com/", "ques": "How many more blocks (also denoted as layers) in BERT base encoder than the encoder from the architecture proposed in Attention is All You Need?"} +{"task_id": "7673d772-ef80-4f0f-a602-1bf4485c9b43", "Level": 1, "Final answer": "inference", "id": "level1-17", "web": "https://www.google.com/", "ques": "On Cornell Law School website's legal information institute, under the fifth section of federal rules alphabetically, what word was deleted in the last amendment to the first rule in the article that has \"witnesses\" in the most titles as of 2021?"} +{"task_id": "c365c1c7-a3db-4d5e-a9a1-66f56eae7865", "Level": 1, "Final answer": "Braintree, Honolulu", "id": "level1-18", "web": "https://www.google.com/", "ques": "Of the cities within the United States where U.S. presidents were born, which two are the farthest apart from the westernmost to the easternmost going east, giving the city names only? Give them to me in alphabetical order, in a comma-separated list"} +{"task_id": "7d4a7d1d-cac6-44a8-96e8-ea9584a70825", "Level": 1, "Final answer": "22", "id": "level1-19", "web": "https://www.google.com/", "ques": "According to Girls Who Code, how long did it take in years for the percentage of computer scientists that were women to change by 13% from a starting point of 37%?"} +{"task_id": "dc22a632-937f-4e6a-b72f-ba0ff3f5ff97", "Level": 1, "Final answer": "Five Hundred Things To Eat Before It's Too Late: and the Very Best Places to Eat Them", "id": "level1-20", "web": "https://www.google.com/", "ques": "What was the complete title of the book in which two James Beard Award winners recommended the restaurant where Ali Khan enjoyed a New Mexican staple in his cost-conscious TV show that started in 2015? Write the numbers in plain text if there are some in the title."} +{"task_id": "3f57289b-8c60-48be-bd80-01f8099ca449", "Level": 1, "Final answer": "519", "id": "level1-21", "web": "https://www.google.com/", "ques": "How many at bats did the Yankee with the most walks in the 1977 regular season have that same season?"} +{"task_id": "23dd907f-1261-4488-b21c-e9185af91d5e", "Level": 1, "Final answer": "2", "id": "level1-22", "web": "https://www.google.com/", "ques": "In Audre Lorde\u2019s poem \u201cFather Son and Holy Ghost\u201d, what is the number of the stanza in which some lines are indented?"} +{"task_id": "840bfca7-4f7b-481a-8794-c560c340185d", "Level": 1, "Final answer": "80GSFC21M0002", "id": "level1-23", "web": "https://www.google.com/", "ques": "On June 6, 2023, an article by Carolyn Collins Petersen was published in Universe Today. This article mentions a team that produced a paper about their observations, linked at the bottom of the article. Find this paper. Under what NASA award number was the work performed by R. G. Arendt supported by?"} +{"task_id": "a0068077-79f4-461a-adfe-75c1a4148545", "Level": 1, "Final answer": "90", "id": "level1-24", "web": "https://www.google.com/", "ques": "What was the actual enrollment count of the clinical trial on H. pylori in acne vulgaris patients from Jan-May 2018 as listed on the NIH website?"} +{"task_id": "bda648d7-d618-4883-88f4-3466eabd860e", "Level": 1, "Final answer": "Saint Petersburg", "id": "level1-25", "web": "https://www.google.com/", "ques": "Where were the Vietnamese specimens described by Kuznetzov in Nedoshivina's 2010 paper eventually deposited? Just give me the city name without abbreviations."} +{"task_id": "c61d22de-5f6c-4958-a7f6-5e9707bd3466", "Level": 2, "Final answer": "egalitarian", "id": "level2-0", "web": "https://www.google.com/", "ques": "A paper about AI regulation that was originally submitted to arXiv.org in June 2022 shows a figure with three axes, where each axis has a label word at both ends. Which of these words is used to describe a type of society in a Physics and Society article submitted to arXiv.org on August 11, 2016?"} +{"task_id": "17b5a6a3-bc87-42e8-b0fb-6ab0781ef2cc", "Level": 2, "Final answer": "34689", "id": "level2-1", "web": "https://www.google.com/", "ques": "I\u2019m researching species that became invasive after people who kept them as pets released them. There\u2019s a certain species of fish that was popularized as a pet by being the main character of the movie Finding Nemo. According to the USGS, where was this fish found as a nonnative species, before the year 2020? I need the answer formatted as the five-digit zip codes of the places the species was found, separated by commas if there is more than one place."} +{"task_id": "04a04a9b-226c-43fd-b319-d5e89743676f", "Level": 2, "Final answer": "41", "id": "level2-2", "web": "https://www.google.com/", "ques": "If we assume all articles published by Nature in 2020 (articles, only, not book reviews/columns, etc) relied on statistical significance to justify their findings and they on average came to a p-value of 0.04, how many papers would be incorrect as to their claims of statistical significance? Round the value up to the next integer."} +{"task_id": "14569e28-c88c-43e4-8c32-097d35b9a67d", "Level": 2, "Final answer": "backtick", "id": "level2-3", "web": "https://www.google.com/", "ques": "In Unlambda, what exact charcter or text needs to be added to correct the following code to output \"For penguins\"? If what is needed is a character, answer with the name of the character. If there are different names for the character, use the shortest. The text location is not needed. Code:\n\n`r```````````.F.o.r. .p.e.n.g.u.i.n.si"} +{"task_id": "3627a8be-a77f-41bb-b807-7e1bd4c0ebdf", "Level": 2, "Final answer": "142", "id": "level2-4", "web": "https://www.google.com/", "ques": "The object in the British Museum's collection with a museum number of 2012,5015.17 is the shell of a particular mollusk species. According to the abstract of a research article published in Science Advances in 2021, beads made from the shells of this species were found that are at least how many thousands of years old?"} +{"task_id": "7619a514-5fa8-43ef-9143-83b66a43d7a4", "Level": 2, "Final answer": "04/15/18", "id": "level2-5", "web": "https://www.google.com/", "ques": "According to github, when was Regression added to the oldest closed numpy.polynomial issue that has the Regression label in MM/DD/YY?"} +{"task_id": "2a649bb1-795f-4a01-b3be-9a01868dae73", "Level": 2, "Final answer": "3.1.3.1; 1.11.1.7", "id": "level2-6", "web": "https://www.google.com/", "ques": "What are the EC numbers of the two most commonly used chemicals for the virus testing method in the paper about SPFMV and SPCSV in the Pearl Of Africa from 2016? Return the semicolon-separated numbers in the order of the alphabetized chemicals."} +{"task_id": "87c610df-bef7-4932-b950-1d83ef4e282b", "Level": 2, "Final answer": "Morarji Desai", "id": "level2-7", "web": "https://www.google.com/", "ques": "In April of 1977, who was the Prime Minister of the first place mentioned by name in the Book of Esther (in the New International Version)?"} +{"task_id": "624cbf11-6a41-4692-af9c-36b3e5ca3130", "Level": 2, "Final answer": "So we had to let it die.", "id": "level2-8", "web": "https://www.google.com/", "ques": "What's the last line of the rhyme under the flavor name on the headstone visible in the background of the photo of the oldest flavor's headstone in the Ben & Jerry's online flavor graveyard as of the end of 2022?"} +{"task_id": "dd3c7503-f62a-4bd0-9f67-1b63b94194cc", "Level": 2, "Final answer": "6", "id": "level2-9", "web": "https://www.google.com/", "ques": "Use density measures from the chemistry materials licensed by Marisa Alviar-Agnew & Henry Agnew under the CK-12 license in LibreText's Introductory Chemistry materials as compiled 08/21/2023.\n\nI have a gallon of honey and a gallon of mayonnaise at 25C. I remove one cup of honey at a time from the gallon of honey. How many times will I need to remove a cup to have the honey weigh less than the mayonaise? Assume the containers themselves weigh the same."} +{"task_id": "f0f46385-fc03-4599-b5d3-f56496c3e69f", "Level": 2, "Final answer": "Indonesia, Myanmar", "id": "level2-10", "web": "https://www.google.com/", "ques": "In terms of geographical distance between capital cities, which 2 countries are the furthest from each other within the ASEAN bloc according to wikipedia? Answer using a comma separated list, ordering the countries by alphabetical order."} +{"task_id": "e4e91f1c-1dcd-439e-9fdd-cb976f5293fd", "Level": 2, "Final answer": "cloak", "id": "level2-11", "web": "https://www.google.com/", "ques": "I need to fact-check a citation. This is the citation from the bibliography:\n\nGreetham, David. \"Uncoupled: OR, How I Lost My Author(s).\" Textual Cultures: Texts, Contexts, Interpretation, vol. 3 no. 1, 2008, p. 45-46. Project MUSE, doi:10.2979/tex.2008.3.1.44.\n\nAnd this is the in-line citation:\n\nOur relationship with the authors of the works we read can often be \u201cobscured not by a \"cloak of print\" but by the veil of scribal confusion and mis-transmission\u201d (Greetham 45-46).\n\nDoes the quoted text match what is actually in the article? If Yes, answer Yes, otherwise, give me the word in my citation that does not match with the correct one (without any article)."} +{"task_id": "56137764-b4e0-45b8-9c52-1866420c3df5", "Level": 2, "Final answer": "Li Peng", "id": "level2-12", "web": "https://www.google.com/", "ques": "Which contributor to the version of OpenCV where support was added for the Mask-RCNN model has the same name as a former Chinese head of government when the names are transliterated to the Latin alphabet?"} +{"task_id": "8b3379c0-0981-4f5b-8407-6444610cb212", "Level": 2, "Final answer": "1.8", "id": "level2-13", "web": "https://www.google.com/", "ques": "What is the maximum length in meters of #9 in the first National Geographic short on YouTube that was ever released according to the Monterey Bay Aquarium website? Just give the number."} +{"task_id": "0ff53813-3367-4f43-bcbd-3fd725c1bf4b", "Level": 2, "Final answer": "beta geometric", "id": "level2-14", "web": "https://www.google.com/", "ques": "What two-word type of model did Manash Pratim Kashyap's and PS Fader's studies in customer retention studies published during 2018-2019 have in common (no punctuation)?"} +{"task_id": "a7feb290-76bb-4cb7-8800-7edaf7954f2f", "Level": 2, "Final answer": "31", "id": "level2-15", "web": "https://www.google.com/", "ques": "How many High Energy Physics - Lattice articles listed in January 2020 on Arxiv had ps versions available?"} +{"task_id": "b4cc024b-3f5e-480e-b96a-6656493255b5", "Level": 2, "Final answer": "Russian-German Legion", "id": "level2-16", "web": "https://www.google.com/", "ques": "The photograph in the Whitney Museum of American Art's collection with accession number 2022.128 shows a person holding a book. Which military unit did the author of this book join in 1813? Answer without using articles."} +{"task_id": "33d8ea3b-6c6b-4ff1-803d-7e270dea8a57", "Level": 2, "Final answer": "2", "id": "level2-17", "web": "https://www.google.com/", "ques": "What is the minimum number of page links a person must click on to go from the english Wikipedia page on The Lord of the Rings (the book) to the english Wikipedia page on A Song of Ice and Fire (the book series)? In your count, include each link you would click on to get to the page. Use the pages as they appeared at the end of the day on July 3, 2023."} +{"task_id": "e8cb5b03-41e0-4086-99e5-f6806cd97211", "Level": 2, "Final answer": "shrimp", "id": "level2-18", "web": "https://www.google.com/", "ques": "I went to Virtue restaurant & bar in Chicago for my birthday on March 22, 2021 and the main course I had was delicious! Unfortunately, when I went back about a month later on April 21, it was no longer on the dinner menu. Using the Wayback Machine, can you help me figure out which main course was on the dinner menu for Virtue on March 22, 2021 but not April 21, 2021? Answer using the singular form, without articles."} +{"task_id": "f46b4380-207e-4434-820b-f32ce04ae2a4", "Level": 2, "Final answer": "Harbinger, Tidal", "id": "level2-19", "web": "https://www.google.com/", "ques": "It is 1999. Before you party like it is 1999, please assist me in settling a bet.\n\nFiona Apple and Paula Cole released albums prior to 1999. Of these albums, which didn't receive a letter grade from Robert Christgau? Provide your answer as a comma delimited list of album titles, sorted alphabetically."} +{"task_id": "05407167-39ec-4d3a-a234-73a9120c325d", "Level": 2, "Final answer": "Format Document", "id": "level2-20", "web": "https://www.google.com/", "ques": "In the 2018 VSCode blog post on replit.com, what was the command they clicked on in the last video to remove extra lines?"} +{"task_id": "b9763138-c053-4832-9f55-86200cb1f99c", "Level": 2, "Final answer": "3", "id": "level2-21", "web": "https://www.google.com/", "ques": "Compute the check digit the Tropicos ID for the Order Helotiales would have if it were an ISBN-10 number."} +{"task_id": "16d825ff-1623-4176-a5b5-42e0f5c2b0ac", "Level": 2, "Final answer": "6:41 PM", "id": "level2-22", "web": "https://www.google.com/", "ques": "What time was the Tri-Rail train that carried the most passengers on May 27, 2019 scheduled to arrive in Pompano Beach? Express your answer in the 12-hour digital clock format without leading zero if any, and include whether it is AM or PM."} +{"task_id": "544b7f0c-173a-4377-8d56-57b36eb26ddf", "Level": 2, "Final answer": "A Nightmare on Elm Street", "id": "level2-23", "web": "https://www.google.com/", "ques": "In Valentina Re\u2019s contribution to the 2017 book \u201cWorld Building: Transmedia, Fans, Industries\u201d, what horror movie does the author cite as having popularized metalepsis between a dream world and reality? Use the complete name with article if any."} +{"task_id": "6b078778-0b90-464d-83f6-59511c811b01", "Level": 2, "Final answer": "Alfonso Visconti", "id": "level2-24", "web": "https://www.google.com/", "ques": "The Metropolitan Museum of Art has a portrait in its collection with an accession number of 29.100.5. Of the consecrators and co-consecrators of this portrait's subject as a bishop, what is the name of the one who never became pope?"} +{"task_id": "08cae58d-4084-4616-b6dd-dd6534e4825b", "Level": 2, "Final answer": "2018", "id": "level2-25", "web": "https://www.google.com/", "ques": "According to Google Finance, when was the first year the Apple stock went above $50 (without adjusting for stock split)?"} +{"task_id": "2dfc4c37-fec1-4518-84a7-10095d30ad75", "Level": 2, "Final answer": "6", "id": "level2-26", "web": "https://www.google.com/", "ques": "According to Box Office Mojo's 2020 Worldwide Box Office list, how many of the top 10 highest-grossing worldwide movies are also on the top 10 highest-grossing domestic movies? Your answer should be a numerical integer value."} +{"task_id": "9f41b083-683e-4dcf-9185-ccfeaa88fa45", "Level": 2, "Final answer": "0", "id": "level2-27", "web": "https://www.google.com/", "ques": "How many pages if the 2023 IPCC report (85 pages version) mentions nuclear energy?"} +{"task_id": "ecbc4f94-95a3-4cc7-b255-6741a458a625", "Level": 2, "Final answer": "13", "id": "level2-28", "web": "https://www.google.com/", "ques": "How many images are there in the latest 2022 Lego english wikipedia article?"} +{"task_id": "71345b0a-9c7d-4b50-b2bf-937ec5879845", "Level": 2, "Final answer": "Here be dragons", "id": "level2-29", "web": "https://www.google.com/", "ques": "On a leap day before the year 2008, a joke was removed from the Wikipedia page for \u201cDragon\u201d. What was the phrase that was removed? Give the phrase as it appeared on the page, but without punctuation."} +{"task_id": "7b5377b0-3f38-4103-8ad2-90fe89864c04", "Level": 2, "Final answer": "563.9", "id": "level2-30", "web": "https://www.google.com/", "ques": "Find the value of x to the nearest tenth: Lx = (d/dx * (A * x-squared)) + 4-thousand'n'ninety-7 minus C\nWhere L is the last two digits of the year of the Venezuelan Declaration of Independence,\nA is the number of colors in the TikTok logo as of July 2023, excluding black and white,\nand C is the height of the average woman in the Philippines according to a July 2023 Business Insider article, rounded to the nearest whole centimeter"} +{"task_id": "114d5fd0-e2ae-4b6d-a65a-870da2d19c08", "Level": 2, "Final answer": "4", "id": "level2-31", "web": "https://www.google.com/", "ques": "In the endnote found in the second-to-last paragraph of page 11 of the book with the doi 10.2307/j.ctv9b2xdv, what date in November was the Wikipedia article accessed? Just give the day of the month."} +{"task_id": "ad37a656-079a-49f9-a493-7b739c9167d1", "Level": 2, "Final answer": "Bravo", "id": "level2-32", "web": "https://www.google.com/", "ques": "On July 15, 2008, Phys.org published an article about a catastrophe. Find the explosive force of this catastrophe according to Encyclopedia Britannica, then find the name of the US nuclear test that had the same yield. Your answer should only be the last word of the name of the test."} +{"task_id": "f3917a3d-1d17-4ee2-90c5-683b072218fe", "Level": 2, "Final answer": "2732", "id": "level2-33", "web": "https://www.google.com/", "ques": "How many edits were made to the Wikipedia page on Antidisestablishmentarianism from its inception until June of 2023?"} +{"task_id": "48eb8242-1099-4c26-95d4-ef22b002457a", "Level": 2, "Final answer": "6", "id": "level2-34", "web": "https://www.google.com/", "ques": "How many nonindigenous crocodiles were found in Florida from the year 2000 through 2020? You can get the data from the USGS Nonindigenous Aquatic Species database."} +{"task_id": "c8b7e059-c60d-472e-ad64-3b04ae1166dc", "Level": 2, "Final answer": "8", "id": "level2-35", "web": "https://www.google.com/", "ques": "The work referenced in footnote 397 of Federico Lauria's 2014 dissertation is also the source for the titles of two paintings in the Smithsonian American Art Museum's collection, as of August 2023. What is the absolute difference between the chapter numbers of the chapters that the titles of these two paintings quote?"} +{"task_id": "d1af70ea-a9a4-421a-b9cc-94b5e02f1788", "Level": 2, "Final answer": "736455", "id": "level2-36", "web": "https://www.google.com/", "ques": "As of the 2020 census, what was the population difference between the largest county seat and smallest county seat, by land area of the county seat, in Washington state? For population figures, please use the official data from data.census.gov. Please report the integer difference."} +{"task_id": "ded28325-3447-4c56-860f-e497d6fb3577", "Level": 2, "Final answer": "Picnic is in Ploybius Plaza.", "id": "level2-37", "web": "https://www.google.com/", "ques": "This is a secret message my friend gave me. It says where we should meet for our picnic on Friday. The only problem is, it\u2019s encrypted in the Caesar cipher, so I can\u2019t read it. Can you tell me what it says? This is the message:\n\nZsmxsm sc sx Zyvilsec Zvkjk."} +{"task_id": "d700d50d-c707-4dca-90dc-4528cddd0c80", "Level": 2, "Final answer": "Roger Miller", "id": "level2-38", "web": "https://www.google.com/", "ques": "Who composed the song that was performed by a rooster and a hamster in separate animated videos at separate tempos with different lyrics? Answer using the format First name Last name."} +{"task_id": "0a3cd321-3e76-4622-911b-0fda2e5d6b1a", "Level": 2, "Final answer": "Brunei, China, Morocco, Singapore", "id": "level2-39", "web": "https://www.google.com/", "ques": "According to the World Bank, which countries had gross savings of over 35% of GDP for every year in the period 2001-2010? Give your answer as a comma-separated list of countries in alphabetical order. Use the countries most common names in english when answering."} +{"task_id": "f2feb6a4-363c-4c09-a804-0db564eafd68", "Level": 2, "Final answer": "900000", "id": "level2-40", "web": "https://www.google.com/", "ques": "I\u2019m thinking about selling my home, so I want to learn more about how homes in my area sold recently. I live in Pearl City, Hawaii, which is on the island of Oahu. I know two homes near me that sold in 2022 were 2072 Akaikai Loop, and 2017 Komo Mai Drive. Find which of those homes sold for more in 2022, and tell me how much it sold for. Don\u2019t put commas or decimal places in the answer."} +{"task_id": "0b260a57-3f3a-4405-9f29-6d7a1012dbfb", "Level": 2, "Final answer": "0.269", "id": "level2-41", "web": "https://www.google.com/", "ques": "On ScienceDirect, what is the difference to 3 decimal places in the sample standard deviations of the number of Reference Works in each Life Science domain compared to Health Sciences as of 2022?"} +{"task_id": "ed58682d-bc52-4baa-9eb0-4eb81e1edacc", "Level": 2, "Final answer": "stare", "id": "level2-42", "web": "https://www.google.com/", "ques": "What is the last word before the second chorus of the King of Pop's fifth single from his sixth studio album?"} +{"task_id": "023e9d44-96ae-4eed-b912-244ee8c3b994", "Level": 2, "Final answer": "8", "id": "level2-43", "web": "https://www.google.com/", "ques": "It's May 2023, and I'm about to drive across the U.S. from California to Maine. I always recycle my water bottles at the end of a trip, and I drink 5 12-ounce water bottles for every 100 miles I travel, rounded to the nearest 100. Assuming I follow I-40 from Los Angeles to Cincinnati, then take I-90 from Cincinnati to Augusta, how many dollars will I get back according to Wikipedia?"} +{"task_id": "0e9e85b8-52b9-4de4-b402-5f635ab9631f", "Level": 2, "Final answer": "1927", "id": "level2-44", "web": "https://www.google.com/", "ques": "What is the latest chronological year date written in the image on the webpage found when following the first citation reference link on the latest version of Carl Nebel's Wikipedia page as of August 2023?"} +{"task_id": "20194330-9976-4043-8632-f8485c6c71b2", "Level": 2, "Final answer": "4", "id": "level2-45", "web": "https://www.google.com/", "ques": "The YouTube channel Game Grumps began a Let\u2019s Play of the game Sonic the Hedgehog (2006) in the year 2012. Thirty seconds into the first episode, a phrase is shown on the screen in white letters on a red background. How many times does the letter \"E\" appear in this phrase?"} +{"task_id": "65638e28-7f37-4fa7-b7b9-8c19bb609879", "Level": 2, "Final answer": "Kleinpaul", "id": "level2-46", "web": "https://www.google.com/", "ques": "The book with the doi 10.1353/book.24372 concerns a certain neurologist. According to chapter 2 of the book, what author influenced this neurologist\u2019s belief in \u201cendopsychic myths\u201d? Give the last name only."} +{"task_id": "3ff6b7a9-a5bd-4412-ad92-0cd0d45c0fee", "Level": 2, "Final answer": "56000", "id": "level2-47", "web": "https://www.google.com/", "ques": "The longest-lived vertebrate is named after an island. According to Wikipedia as of January 1, 2021, what is the 2020 estimated population of that island, to the nearest thousand?"} +{"task_id": "708b99c5-e4a7-49cb-a5cf-933c8d46470d", "Level": 2, "Final answer": "Citations", "id": "level2-48", "web": "https://www.google.com/", "ques": "On the DeepFruits fruit detection graph on Connected Papers from 2016, what feature caused the largest bubble to be the size it is?"} +{"task_id": "0a65cb96-cb6e-4a6a-8aae-c1084f613456", "Level": 2, "Final answer": "Holabird", "id": "level2-49", "web": "https://www.google.com/", "ques": "During the first week of August 2015, one of the NASA Astronomy Pictures of the Day shows the lights of a city on the horizon. The namesake of this city also has a landmark building in Chicago named after him. What is the name of the architectural firm that designed this landmark building? Give the first name appearing in the name of the firm as of June 2023."} +{"task_id": "65da0822-a48a-4a68-bbad-8ed1b835a834", "Level": 2, "Final answer": "Santa Clara, Boston", "id": "level2-50", "web": "https://www.google.com/", "ques": "All of the individuals who formally held the position of United States secretary of homeland security prior to April 2019, excluding those who held the position in an acting capacity, have a bachelor's degree. Of the universities that these bachelor's degrees were from, which is the westernmost university and which is the easternmost university? Give them to me as a comma-separated list, I only want the name of the cities where the universities are located, with the westernmost city listed first."} +{"task_id": "73c1b9fe-ee1d-4cf4-96ca-35c08f97b054", "Level": 2, "Final answer": "1954", "id": "level2-51", "web": "https://www.google.com/", "ques": "According to the USGS, in what year was the American Alligator first found west of Texas (not including Texas)?"} +{"task_id": "e2d69698-bc99-4e85-9880-67eaccd66e6c", "Level": 2, "Final answer": "Michele Fitzgerald", "id": "level2-52", "web": "https://www.google.com/", "ques": "As of August 2023, who is the only winner of the US version of Survivor to be born in the month of May?"} +{"task_id": "a56f1527-3abf-41d6-91f8-7296d6336c3f", "Level": 2, "Final answer": "185", "id": "level2-53", "web": "https://www.google.com/", "ques": "The cover of the August 2021 issue of Vogue shows a famous landmark in the background behind some trees. How tall is this monument in yards, rounded to the nearest yard? Give the number only."} +{"task_id": "42d4198c-5895-4f0a-b0c0-424a66465d83", "Level": 2, "Final answer": "60", "id": "level2-54", "web": "https://www.google.com/", "ques": "I'm curious about how much information is available for popular video games before their release. Find the Wikipedia page for the 2019 game that won the British Academy Games Awards. How many revisions did that page have before the month listed as the game's release date on that Wikipedia page (as of the most recent entry from 2022)?"} +{"task_id": "a26649c6-1cb2-470a-871e-6910c64c3e53", "Level": 2, "Final answer": "116", "id": "level2-55", "web": "https://www.google.com/", "ques": "What is the absolute difference in tens of thousands between the population of chinstrap penguins on the Wikipedia page for penguin species populations as of the end of 2018 and the population recorded in the Nature.com \"global population assessment of the Chinstrap penguin\" article from 2020, assuming two penguins per breeding pair?"} +{"task_id": "d5141ca5-e7a0-469f-bf3e-e773507c86e2", "Level": 2, "Final answer": "19/02/2009", "id": "level2-56", "web": "https://www.google.com/", "ques": "When was a picture of St. Thomas Aquinas first added to the Wikipedia page on the Principle of double effect? Answer using the format DD/MM/YYYY."} +{"task_id": "1dcc160f-c187-48c2-b68e-319bd4354f3d", "Level": 2, "Final answer": "3", "id": "level2-57", "web": "https://www.google.com/", "ques": "According to Openreview.net, at the NeurIPS 2022 Conference, how many papers by an author named Yuri were accepted with a \"certain\" recommendation?"} +{"task_id": "e0c10771-d627-4fd7-9694-05348e54ee36", "Level": 2, "Final answer": "234.9", "id": "level2-58", "web": "https://www.google.com/", "ques": "Take the gender split from the 2011 Bulgarian census about those who have completed tertiary education. Subtract the smaller number from the larger number, then return the difference in thousands of women. So if there were 30.1 thousand more men, you'd give \"30.1\""} +{"task_id": "e29834fd-413a-455c-a33e-c3915b07401c", "Level": 2, "Final answer": "21", "id": "level2-59", "web": "https://www.google.com/", "ques": "I'd like to learn more about some popular reality television competition shows. As of the end of the 44th season of the American version of Survivor, how many more unique winners have there been compared to the number of winners of American Idol?"} +{"task_id": "08c0b6e9-1b43-4c2e-ae55-4e3fce2c2715", "Level": 2, "Final answer": "orange, white", "id": "level2-60", "web": "https://www.google.com/", "ques": "In the film Goldfinger, what color was the object that James Bond concealed himself and his companion Pussy Galore at the end of the film? If there are multiple colors, put them in a comma-separated list in alphabetical order."} +{"task_id": "db4fd70a-2d37-40ea-873f-9433dc5e301f", "Level": 2, "Final answer": "10", "id": "level2-61", "web": "https://www.google.com/", "ques": "As of May 2023, how many stops are between South Station and Windsor Gardens on MBTA\u2019s Franklin-Foxboro line (not included)?"} +{"task_id": "853c8244-429e-46ca-89f2-addf40dfb2bd", "Level": 2, "Final answer": "11", "id": "level2-62", "web": "https://www.google.com/", "ques": "In the 2015 Metropolitan Museum of Art exhibition titled after the Chinese zodiac animal of 2015, how many of the \"twelve animals of the Chinese zodiac\" have a hand visible?"} +{"task_id": "7a4a336d-dcfa-45a0-b014-824c7619e8de", "Level": 2, "Final answer": "1:41.614", "id": "level2-63", "web": "https://www.google.com/", "ques": "At the two-minute mark in the YouTube video uploaded by the channel \u201cGameGrumps\u201d on May 14, 2017 as part of their playthrough of the game Mario Kart 8 Deluxe, the shows\u2019 hosts are competing on one of the game\u2019s racetracks. What was the world record time for that track in the game\u2019s 150cc mode as of June 7, 2023? Express your answer in minutes and seconds, rounding the seconds to the nearest hundredth, e.g. 1:01.001."} diff --git a/sdk/stagehand-ts/evals/datasets/onlineMind2Web/onlineMind2Web.jsonl b/sdk/stagehand-ts/evals/datasets/onlineMind2Web/onlineMind2Web.jsonl new file mode 100644 index 0000000..58b3dfd --- /dev/null +++ b/sdk/stagehand-ts/evals/datasets/onlineMind2Web/onlineMind2Web.jsonl @@ -0,0 +1,300 @@ +{"task_id": "b7258ee05d75e6c50673a59914db412e", "confirmed_task": "Find the store location and hours of the closest Gamestop to zip code 90028 and set it as the home store on Gamestop.", "website": "https://www.gamestop.com/", "reference_length": 8, "level": "medium"} +{"task_id": "ade4c09ad3fdb1607209750924cd232f", "confirmed_task": "Compare available plans for the AeroAPI on Flightaware.", "website": "https://www.flightaware.com/", "reference_length": 4, "level": "easy"} +{"task_id": "fb7b4f784cfde003e2548fdf4e8d6b4f", "confirmed_task": "Open the page with an overview of the submission of releases on Discogs.", "website": "https://www.discogs.com/", "reference_length": 6, "level": "medium"} +{"task_id": "824eb7bb0ef1ce40bfd49c12182d9428", "confirmed_task": "Get the lowest priced women's plus size one piece swimsuit in color black with a customer rating of at least 5 on Kohls.", "website": "https://www.kohls.com/", "reference_length": 13, "level": "hard"} +{"task_id": "046138801a05ddf56ad94e8672942496", "confirmed_task": "Find discussions of the community and open one with the most replies on Flightaware.", "website": "https://www.flightaware.com/", "reference_length": 6, "level": "medium"} +{"task_id": "92a3d4236f167af4afdc08876a902ba6", "confirmed_task": "Find a 2022 Tesla Model 3 on CarMax.", "website": "https://www.carmax.com/", "reference_length": 10, "level": "medium"} +{"task_id": "48c73f3f53e2611c4a1052457c1033db", "confirmed_task": "Get the report from the final environmental impact statement for the Jamaica Bus Depot expansion on new.mta.info.", "website": "https://new.mta.info/", "reference_length": 10, "level": "medium"} +{"task_id": "8f2611047de227a2ca8bda13f6e2e5fb", "confirmed_task": "Find the used 2012-2013 Honda Crosstour with the lowest mileage for under $25,000 near zip code 49102 on CarGurus.", "website": "https://www.cargurus.com/", "reference_length": 17, "level": "hard"} +{"task_id": "b320c68bffc1f3c7f2a8dc9d5478fb27", "confirmed_task": "Find a walkthrough for the game \"The Legend of Zelda: Breath of the Wild\" on ign.", "website": "https://www.ign.com/", "reference_length": 6, "level": "medium"} +{"task_id": "aa4b5cb7114fcc138ade82b4b9716d24", "confirmed_task": "Find an editor's choice review with a score of 10 in the boardgame category on ign.", "website": "https://www.ign.com/", "reference_length": 8, "level": "medium"} +{"task_id": "005be9dd91c95669d6ddde9ae667125c", "confirmed_task": "Find the weight of baggage allowance for economy class on Qatar Airways.", "website": "https://www.qatarairways.com/", "reference_length": 4, "level": "easy"} +{"task_id": "323bd85e3559655d89e5496b951a25e8", "confirmed_task": "Tell me information about what identification I need to bring on my trip on Amtrak.", "website": "https://www.amtrak.com/", "reference_length": 6, "level": "medium"} +{"task_id": "123e8c2fc453f55fadd1d0b9aaf94df4", "confirmed_task": "Browse used Audi cars made before 2015 and sort by lowest price on KBB.", "website": "https://www.kbb.com/", "reference_length": 8, "level": "medium"} +{"task_id": "56f8890a837c49f7df766b9c981646f3", "confirmed_task": "Show crazy credits for the movie \" Prometheus\" on IMDb.", "website": "https://www.imdb.com/", "reference_length": 6, "level": "medium"} +{"task_id": "644a856c3897665e475e0dce50bf217d", "confirmed_task": "Find a pair of wireless headphones on Amazon with active noise canceling for $100 or less and add them to the cart.", "website": "https://www.amazon.com/", "reference_length": 8, "level": "medium"} +{"task_id": "62f1626ce249c31098854f8b38bdd6cf", "confirmed_task": "Find Playstation 5 digital edition on gamestop.", "website": "https://www.gamestop.com/", "reference_length": 6, "level": "medium"} +{"task_id": "561693d6eec7bbfba3fefe9e4b26decb", "confirmed_task": "Browse Marriott Bonvoy credit cards on Marriott.", "website": "https://www.marriott.com/", "reference_length": 4, "level": "easy"} +{"task_id": "b7a9a6b5d451164c09bbd27b670bc2ae", "confirmed_task": "Show me the list of Men's Blazers, Black, Size M on Uniqlo.", "website": "https://www.uniqlo.com/", "reference_length": 11, "level": "hard"} +{"task_id": "bfa2de159be6978acf2702be31a2eeeb", "confirmed_task": "Show me the options for a roundtrip leaving from Las Vegas on flexible dates on the interactive map on united.", "website": "https://www.united.com/", "reference_length": 12, "level": "hard"} +{"task_id": "4091bdd3fa64a5b0d912bc08eaf9c824", "confirmed_task": "Find the list of neighborhood maps for Brooklyn on new.mta.info.", "website": "https://new.mta.info/", "reference_length": 5, "level": "easy"} +{"task_id": "79f0bd7df6e685f30f20025cc6755c0a", "confirmed_task": "Find me the cheapest external Hard Drive for an Xbox One on GameStop.", "website": "https://www.gamestop.com/", "reference_length": 13, "level": "hard"} +{"task_id": "6ebde509dca8f15c0fa1bd74f071e8d6", "confirmed_task": "Search for a job in Miami, Florida, in Human Resources on target.", "website": "https://www.target.com/", "reference_length": 14, "level": "hard"} +{"task_id": "34ccd15a8ea8fd3895af83f5ccf62369", "confirmed_task": "Find out what to do when I lose an item on a bus on us.megabus.", "website": "https://us.megabus.com/", "reference_length": 3, "level": "easy"} +{"task_id": "c698ff3fc0f6cbce39947c597ab5749b", "confirmed_task": "Browse the page with event planning tips on Eventbrite.", "website": "https://www.eventbrite.com/", "reference_length": 5, "level": "easy"} +{"task_id": "b6d10e9bd19b4009a02dea0e98f4e1ae", "confirmed_task": "Check the current standings for MLS on Fox Sports.", "website": "https://www.foxsports.com/", "reference_length": 4, "level": "easy"} +{"task_id": "d71be72aa25c3eab8eea47a0e60382e2", "confirmed_task": "Find technical specs for the latest Macbook Air on Apple.", "website": "https://www.apple.com/", "reference_length": 4, "level": "easy"} +{"task_id": "0b51b4fa0295ae80ccd176ebdad6fff6", "confirmed_task": "Search for a red Toyota Corolla from model years 2018 to 2023 on CarMax.", "website": "https://www.carmax.com/", "reference_length": 13, "level": "hard"} +{"task_id": "3f312ae3efc3c3e90ababe050dd4e7ae", "confirmed_task": "Find the current NFL standings for the AFC East division on NFL.com and go to the page on which team is in first place.", "website": "https://www.nfl.com/", "reference_length": 4, "level": "easy"} +{"task_id": "95cad96f2e43f3c0d8efad1331c77c8c", "confirmed_task": "View the list of the Most Popular TV on rotten tomatoes.", "website": "https://www.rottentomatoes.com/", "reference_length": 3, "level": "easy"} +{"task_id": "bf3b311cc8dce16d3de844f4b5875dfd", "confirmed_task": "Compare Apple watches and learn more about the ultra version on apple.", "website": "https://www.apple.com/", "reference_length": 4, "level": "easy"} +{"task_id": "b64f938af842f6a1b4489d0e49a785a7", "confirmed_task": "Get the frozen vegan cheese pizza between 5 to 10 USD on Target.", "website": "https://www.target.com/", "reference_length": 17, "level": "hard"} +{"task_id": "5e1b8254c123c80178cc28e0afdb14f0", "confirmed_task": "Find a help page about buying tickets on seatgeek.", "website": "https://seatgeek.com/", "reference_length": 4, "level": "easy"} +{"task_id": "f27c0a7b8b0bb33d37698dff227fc8d7", "confirmed_task": "Browse used Mercedes-Benz cars from model years 2004 to 2012 on KBB and sort by highest price.", "website": "https://www.kbb.com/", "reference_length": 11, "level": "hard"} +{"task_id": "8fdec8eeffd3491e6526cc78c028120b", "confirmed_task": "See Nissan and Honda cars for sale near Kentwood, MI 49512 on CarMax.", "website": "https://www.carmax.com/", "reference_length": 12, "level": "hard"} +{"task_id": "7b182a5087347d494b48a29dbc0f1d3e", "confirmed_task": "Find a shelter or rescue group near zip code 90011.", "website": "https://www.adoptapet.com/", "reference_length": 4, "level": "easy"} +{"task_id": "828c2d98616a9478d5864d847d5a1b28", "confirmed_task": "Browse the list of Civil Division forms.", "website": "https://www.justice.gov/", "reference_length": 4, "level": "easy"} +{"task_id": "608c595eec271fa5dc03506923519994", "confirmed_task": "Calculate a FedEx Ground shipping rate for a 3-pound package from zip code 10019 to zip code 90028.", "website": "https://www.fedex.com/en-us/home.html", "reference_length": 9, "level": "medium"} +{"task_id": "a7a73c8fa75441fc76df9746c327bdd6", "confirmed_task": "Estimate the cost of a photographer in 07055 for a 4-hour project.", "website": "https://www.thumbtack.com/", "reference_length": 8, "level": "medium"} +{"task_id": "cfafe3771369d1d261e9f7ecd44c296d", "confirmed_task": "Find the highest-rated dealer for Cadillac with a rating above 4 stars within 20 miles of zip 60606.", "website": "https://www.cars.com/", "reference_length": 6, "level": "medium"} +{"task_id": "bbbc243b4f18a7a897f0bc84e11d293f", "confirmed_task": "Find out how many assists Chris Paul has been averaging in the current season.", "website": "https://www.nba.com/", "reference_length": 4, "level": "easy"} +{"task_id": "816851ff92ff0219acf4364dcc2c4692", "confirmed_task": "Search for boys' infant pajamas below $40.", "website": "https://www.macys.com/", "reference_length": 10, "level": "medium"} +{"task_id": "8244409b2c82043f966cad05f9afe132", "confirmed_task": "Find the best Audiologist within 50 miles of New York, NY, with a rating of 4 and above.", "website": "https://doctor.webmd.com/", "reference_length": 13, "level": "hard"} +{"task_id": "e7301bb694871429bf2eb36c3a72186c", "confirmed_task": "Find baby shoes priced under $20 with a 5-star rating.", "website": "https://www.macys.com/", "reference_length": 6, "level": "medium"} +{"task_id": "905cb53061c33aa2d77e485fe1fca516", "confirmed_task": "Browse dermatologists within 10 miles of zip code 10019 and filter by only those who accept Blue Medicare Advantage.", "website": "https://www.healthgrades.com/", "reference_length": 11, "level": "hard"} +{"task_id": "fcf4952d2a1d80ea505c555c3c3b54e7", "confirmed_task": "Find the cheapest used 8-cylinder bmw made between 2005-2015 and priced from 25,000 to 50,000 dollars with mileage less than 50,000 miles or less.", "website": "https://www.cars.com/", "reference_length": 11, "level": "hard"} +{"task_id": "3c1ffc3f494e423b3c434c79e35da8f3", "confirmed_task": "Find 12 Monkeys community and view the latest posts mentioning James Cole.", "website": "https://www.reddit.com/", "reference_length": 6, "level": "medium"} +{"task_id": "26a0e5c21c145dd8448aa92f35bec5ea", "confirmed_task": "Browse optometrists who offer telehealth services in Columbus, OH.", "website": "https://www.healthgrades.com/", "reference_length": 3, "level": "easy"} +{"task_id": "070c907d34a4ce71dfdbea38f9c5d4d8", "confirmed_task": "Find a dentist who specializes in pediatric dentistry and is located near zip code 90210 (within 5-mile distance).", "website": "https://www.healthgrades.com/", "reference_length": 7, "level": "medium"} +{"task_id": "43a1ca251f11c6b0bdd0379766cc49e6", "confirmed_task": "Find a neurosurgeon who is over 50 years old and has an appointment available tomorrow.", "website": "https://www.healthgrades.com/", "reference_length": 8, "level": "medium"} +{"task_id": "b3f8bd9198d9d157e0848109563c4b23", "confirmed_task": "Find a permanent job in Logistics within 20 miles of New York, zip 11005, in the middle-income range for a high school diploma holder.", "website": "https://ohiomeansjobs.ohio.gov/", "reference_length": 15, "level": "hard"} +{"task_id": "20a460a8fe1971b84411c5b1e6ac4186", "confirmed_task": "Show theatre events for Las Vegas and select one.", "website": "https://www.stubhub.com/", "reference_length": 3, "level": "easy"} +{"task_id": "db1ffb5e60578597d1c3aa3c389ac7b1", "confirmed_task": "Search for smart TVs with a screen size of 55 to 65 inches and filter the results to show only those that have an LED display.", "website": "https://www.google.com/shopping?udm=28", "reference_length": 5, "level": "easy"} +{"task_id": "7be8cd8dba885cddd9af5320f49bc41b", "confirmed_task": "Find roofing contractors within 5 miles of zip code 10002.", "website": "https://www.bbb.org/", "reference_length": 9, "level": "medium"} +{"task_id": "239a29bde438fe44fe17fe1390ef1634", "confirmed_task": "Find me a gluten-free diet to lose weight for a pregnant woman.", "website": "https://www.healthline.com/", "reference_length": 8, "level": "medium"} +{"task_id": "9f1cba613830ca1c6a58f9498c06e679", "confirmed_task": "Find a premier real estate agent in St Augustine, FL.", "website": "https://www.redfin.com/", "reference_length": 4, "level": "easy"} +{"task_id": "75146b7b67388b9244e0f21a1527c022", "confirmed_task": "Find a male senior boxer near zip code 90028.", "website": "https://www.adoptapet.com/", "reference_length": 10, "level": "medium"} +{"task_id": "59b7b990b4828bc305ab0d7ed6071b55", "confirmed_task": "Get owner-financing homesite land for sale in New Mexico, Luna County, listed in the last 30 days, and contact the cheapest per acre land seller.", "website": "https://www.landwatch.com/", "reference_length": 9, "level": "medium"} +{"task_id": "9c97bab9c2abfb90a426cbe9addae8d0", "confirmed_task": "Check the details of order 12345 with email 12345@gmail.com.", "website": "https://www.macys.com/", "reference_length": 4, "level": "easy"} +{"task_id": "871e7771cecb989972f138ecc373107b", "confirmed_task": "Find the weather for Vancouver, British Columbia for the next seven days.", "website": "https://www.theweathernetwork.com/", "reference_length": 3, "level": "easy"} +{"task_id": "b69eb4de621e9e265676daac44938f3f", "confirmed_task": "Find an adult husky near zip code 10019.", "website": "https://www.adoptapet.com/", "reference_length": 8, "level": "medium"} +{"task_id": "9bb63ad0e38d5691a618932a8b31c05a", "confirmed_task": "Look for reviews of a Nest Hello Video Doorbell and filter by 1-star ratings.", "website": "https://www.google.com/shopping?udm=28", "reference_length": 5, "level": "easy"} +{"task_id": "8ae510355d978424f490798f900bfa2c", "confirmed_task": "Show me the shared rooms in any university in Melbourne that has a private bathroom wifi, and gas included in the bills.", "website": "https://www.student.com/", "reference_length": 9, "level": "medium"} +{"task_id": "4c186c6ed888d0c8d4cf4adb39443080", "confirmed_task": "Find a medium Devin Booker jersey and add it to the shopping cart.", "website": "https://www.nba.com/", "reference_length": 6, "level": "medium"} +{"task_id": "2fc51dd3febd447f0fdcdabca8d944ce", "confirmed_task": "Locate a self-storage unit near zip code 60538 that can fit about a dorm room full of items and is climate-controlled.", "website": "https://www.extraspace.com/", "reference_length": 9, "level": "medium"} +{"task_id": "eb323dc584156d0eb3a2b90bb8c4b791", "confirmed_task": "Find the latest 2 bed and 1.5+ bath apartment listing for rent in New York.", "website": "https://www.redfin.com/", "reference_length": 12, "level": "hard"} +{"task_id": "87f4c5128e36cdb9366a138a7b61bb00", "confirmed_task": "View the speakers that are bluetooth and wireless and filter the results to only show models that are on sale and cost less than $50.", "website": "https://www.bestbuy.com/", "reference_length": 6, "level": "medium"} +{"task_id": "354b4ddf048815f8fd4163d0d7e1aaa3", "confirmed_task": "Browse marketing jobs and filter by Bachelor's Degree education level.", "website": "https://ohiomeansjobs.ohio.gov/", "reference_length": 6, "level": "medium"} +{"task_id": "e4e097222d13a2560db6f6892612dab6", "confirmed_task": "Search for a young spayed male dog cared for by a private owner within 50 miles of zip 33109.", "website": "https://www.adoptapet.com/", "reference_length": 6, "level": "medium"} +{"task_id": "f389398d2eeb29e5571e00439c57eb76", "confirmed_task": "Find the latest climate news.", "website": "https://www.theweathernetwork.com/", "reference_length": 3, "level": "easy"} +{"task_id": "8ea6c3a2ea3f59150619935261a76d19", "confirmed_task": "Find a staffed FedEx location near zip code 10019 to return a package.", "website": "https://www.fedex.com/en-us/home.html", "reference_length": 7, "level": "medium"} +{"task_id": "c1d6ea6f2196d25782cc3646ff3090db", "confirmed_task": "Create a list of drip coffee makers that are on sale and within $25-60 and have a black finish.", "website": "https://www.google.com/shopping?udm=28", "reference_length": 7, "level": "medium"} +{"task_id": "2dd41b1d0e8f389d0683f4a4627abfe6", "confirmed_task": "Show houses for sale in Maryland with a maximum price of $60,000.", "website": "https://www.landwatch.com/", "reference_length": 7, "level": "medium"} +{"task_id": "f2097f92a10d42a842c14179f422311e", "confirmed_task": "Add a $50 Uber gift card to the cart.", "website": "https://www.bestbuy.com/", "reference_length": 4, "level": "easy"} +{"task_id": "85b284c18d7e78c9b5a9e074e7aa3b98", "confirmed_task": "View the cheapest apartment available for students at the University of Leeds with bills that include WIFI and cleaning services.", "website": "https://www.student.com/", "reference_length": 10, "level": "medium"} +{"task_id": "853afd530c72f4b00ffc32ae854efaf8", "confirmed_task": "Show me the wind flow map for Belo Horizonte.", "website": "https://www.accuweather.com/", "reference_length": 5, "level": "easy"} +{"task_id": "c09721cc937d4dcfb391a0bc2c574b28", "confirmed_task": "Find the next available date for Albion Basin.", "website": "https://www.recreation.gov/", "reference_length": 3, "level": "easy"} +{"task_id": "4c572a627b53b0f9a734ab37f21819b8", "confirmed_task": "Browse apartments with at least 2 bedrooms and 2 bathrooms and a max price of $4000 per month.", "website": "https://craigslist.org/", "reference_length": 5, "level": "easy"} +{"task_id": "301f267f421b93045874726183e8f722", "confirmed_task": "Find healthy savory vegan snack recipes which can be cooked within 5 minutes and contain a high level of protein.", "website": "https://www.healthline.com/", "reference_length": 10, "level": "medium"} +{"task_id": "4f903626f632586fe4728d6664947bab", "confirmed_task": "Find press releases by the antitrust division in 2022.", "website": "https://www.justice.gov/", "reference_length": 4, "level": "easy"} +{"task_id": "3ec0f6138d37fadcb989347a6088ec45", "confirmed_task": "Open the page to learn more about how to get accredited.", "website": "https://www.bbb.org/", "reference_length": 2, "level": "easy"} +{"task_id": "2207bb4f21786690cfed20b37253fb8b", "confirmed_task": "Check the current wind speed in Calgary, Alberta.", "website": "https://www.theweathernetwork.com/", "reference_length": 2, "level": "easy"} +{"task_id": "9c04b71bb8db6cf8e743b2290cbc8797", "confirmed_task": "Find a UPS drop-off point near Miami Florida.", "website": "https://www.ups.com/", "reference_length": 6, "level": "medium"} +{"task_id": "4e0f5561a76478da87995dee00b09572", "confirmed_task": "Show me the monthly weather forecast for Florida City.", "website": "https://www.accuweather.com/", "reference_length": 3, "level": "easy"} +{"task_id": "7562d9b4e4829a44245aafce2e1f62db", "confirmed_task": "Find the nearest location to zip code 54620 that offers size 4 P.O. Boxes.", "website": "https://www.usps.com/", "reference_length": 8, "level": "medium"} +{"task_id": "bd1e3770b7181f6fce9c35e18caa9785", "confirmed_task": "Browse service listings for a solar panel installer and hide duplicates.", "website": "https://craigslist.org/", "reference_length": 3, "level": "easy"} +{"task_id": "330cd04c773ac498f51afa4665461ec8", "confirmed_task": "Browse couches for sale, sort by cheapest, and search in titles only.", "website": "https://craigslist.org/", "reference_length": 6, "level": "medium"} +{"task_id": "ec78d3a635e417bc2a80d03ca93d7165", "confirmed_task": "What are the benefits and financial support a single person living in England, over the state pension age, unemployed, with no health conditions, or caring for someone with one, can get?", "website": "https://www.gov.uk/", "reference_length": 16, "level": "hard"} +{"task_id": "a0a18ca6a3529f3e97c771aadd42d3a0", "confirmed_task": "Add a men's T-shirt that is in large size with a stripe pattern, short sleeve, and under the Best Sellers group to the cart.", "website": "https://www.macys.com/", "reference_length": 7, "level": "medium"} +{"task_id": "82eb3bfedd78456a0230b389f4e7a938", "confirmed_task": "Open the XRP yearly chart.", "website": "https://coinmarketcap.com/", "reference_length": 4, "level": "easy"} +{"task_id": "e7f6cca9a8875f98fee3b711ead3a444", "confirmed_task": "Find the comments made by the user Separate-Camp7202.", "website": "https://www.reddit.com/", "reference_length": 5, "level": "easy"} +{"task_id": "75a1b5dcd2c28508a971d98d51fe5767", "confirmed_task": "Open the reviews of a recipe with beef sirloin.", "website": "https://www.allrecipes.com/", "reference_length": 5, "level": "easy"} +{"task_id": "c03ee2be3d73556ab789c0ad1cbd3451", "confirmed_task": "Find a dog groomer for nail trimming within 100 miles of zip code 10005 and check the detailed service prices of the first one.", "website": "https://www.akc.org/", "reference_length": 11, "level": "hard"} +{"task_id": "05483c50cc9b04c8ac44c574758fb2bd", "confirmed_task": "Look for the best rated BBB accredited charity near 12023.", "website": "https://www.bbb.org/", "reference_length": 8, "level": "medium"} +{"task_id": "a172a5d9ffaf5ef02bd550ec4fe24e6d", "confirmed_task": "Browse the natural products database.", "website": "https://www.drugs.com/", "reference_length": 2, "level": "easy"} +{"task_id": "7e1047f4803237f319c004f7a7f6bccb", "confirmed_task": "Discover the trade-in value of my Intel 7th generation i3 Windows 10, HP laptop in fair condition, which has 8 GB memory and can be powered on, proceed for the in-store trade-in.", "website": "https://www.bestbuy.com/", "reference_length": 13, "level": "hard"} +{"task_id": "f2be37a9a60fbc25b6b11cf622d17352", "confirmed_task": "Find obedience trials in state of New York during the month of May.", "website": "https://www.akc.org/", "reference_length": 14, "level": "hard"} +{"task_id": "e24662008c3be5d56f986f232fcec447", "confirmed_task": "Find the stock price for WWE over the last month.", "website": "https://www.google.com/finance/", "reference_length": 4, "level": "easy"} +{"task_id": "0170ca95038b05fa58d463fe627ac605", "confirmed_task": "Check if a visa is required to work in the UK for longer than 6 months in Healthcare as an American citizen.", "website": "https://www.gov.uk/", "reference_length": 12, "level": "hard"} +{"task_id": "b3a7da968de13bbdcaed12ffe4993df6", "confirmed_task": "Compare the breeds Afghan Hound, Akita and Azawakh.", "website": "https://www.akc.org/", "reference_length": 9, "level": "medium"} +{"task_id": "515f2e5811cfdd5e0e669e40f17886d8", "confirmed_task": "Search for a new internal M2 Samsung SSD drive between $25 and $200.", "website": "https://www.bestbuy.com/", "reference_length": 8, "level": "medium"} +{"task_id": "4d3157aab34b54e5f0c4b965dfe930f3", "confirmed_task": "Show me community posts about pregnancy fever from the past 30 days.", "website": "https://www.babycenter.com/", "reference_length": 8, "level": "medium"} +{"task_id": "e4e19e04286f644d747d8c5a79d17fac", "confirmed_task": "Find the Drug Interaction Report for Viagra and alcohol.", "website": "https://www.drugs.com/", "reference_length": 6, "level": "medium"} +{"task_id": "cad62d2be0c53f08a416457486b3db23", "confirmed_task": "Search for adoptable dogs near 21122 zip code.", "website": "https://www.adoptapet.com/", "reference_length": 5, "level": "easy"} +{"task_id": "9ef1a8972f375db59c0e6329e11b7939", "confirmed_task": "Find Farms land in Wilkes County, NC with the lowest price.", "website": "https://www.landwatch.com/", "reference_length": 5, "level": "easy"} +{"task_id": "a11ecdff735b51372d536c866011af6f", "confirmed_task": "Explore courses related to Psychology.", "website": "https://www.coursera.org/", "reference_length": 4, "level": "easy"} +{"task_id": "7fff82864f21ddeccf4104a220892824", "confirmed_task": "Find the lowest 27\"-32\" Samsung or LG computer monitors nearby which have 4k, IPS display.", "website": "https://www.google.com/shopping?udm=28", "reference_length": 10, "level": "medium"} +{"task_id": "50d91eabde542906937ab4c5b6f8f23a", "confirmed_task": "Calculate Pregnancy Weight Gain for a 5-week pregnancy with a 169lb weight before pregnancy and a 175lb after pregnancy with a 5.6ft height.", "website": "https://www.babycenter.com/", "reference_length": 9, "level": "medium"} +{"task_id": "dcd26e662a616d373ddd339747c6ce5b", "confirmed_task": "Take a weight management quiz to find a motivating article for a non-exercising, mostly eating out and can't control portions and cravings, and who has a strong support system, enjoys traveling, loves family time and cooking.", "website": "https://www.healthline.com/", "reference_length": 22, "level": "hard"} +{"task_id": "eb2db4b769c145dbe6ba4f74f3e0de98", "confirmed_task": "Find an energetic hairless dog with medium barking.", "website": "https://www.akc.org/", "reference_length": 10, "level": "medium"} +{"task_id": "c0fa2c0e622971955cabf5bcf7b777e8", "confirmed_task": "Search for rentals in Corning, CA with a maximum price of $1500.", "website": "https://www.apartments.com/", "reference_length": 6, "level": "medium"} +{"task_id": "ce616721ce9aeda69890fbccb29677a6", "confirmed_task": "Calculate the price to ship a large flat-rate box from 77449 to 77084 at the first available date and time.", "website": "https://www.usps.com/", "reference_length": 8, "level": "medium"} +{"task_id": "9d09bc948462db032bac98968b11b008", "confirmed_task": "Find NHL events occurring in Boston.", "website": "https://www.stubhub.com/", "reference_length": 7, "level": "medium"} +{"task_id": "29526b17a32485742b5ab63507e99417", "confirmed_task": "Browse Humira dosage information.", "website": "https://www.drugs.com/", "reference_length": 3, "level": "easy"} +{"task_id": "d7c955b47af68e01766fa86d0bee08a7", "confirmed_task": "Add Elevate at Chicago, IL, to favorites and show a virtual tour.", "website": "https://www.apartments.com/", "reference_length": 4, "level": "easy"} +{"task_id": "9d090a15c214eb070d9caa8a034d03c1", "confirmed_task": "Find the lowest-priced Student housing near Liverpool International College which has been priced between 100 to 300 pounds and has a private bathroom.", "website": "https://www.student.com/", "reference_length": 14, "level": "hard"} +{"task_id": "5916018d1cad999881018cac1216a692", "confirmed_task": "Find a personal trainer service at 10040 for a 25-year-old client aiming to build muscle.", "website": "https://www.thumbtack.com/", "reference_length": 6, "level": "medium"} +{"task_id": "0059adc6b12a3822305deb68929b2de8", "confirmed_task": "Find support services jobs in Bentonville, in the state of Arkansas.", "website": "https://careers.walmart.com/", "reference_length": 8, "level": "medium"} +{"task_id": "07bdc595306729a028ba06cc7451a80a", "confirmed_task": "Select a high speed train ticket with a departure time before 23:00 from Shanghai to Beijing.", "website": "https://us.trip.com/", "reference_length": 7, "level": "medium"} +{"task_id": "64b76158720a69e4a5c31a55d54928bf", "confirmed_task": "Compare two pescatarian diets for eating healthier.", "website": "https://www.healthline.com/", "reference_length": 10, "level": "medium"} +{"task_id": "e3ab665e01e7632ce33ac1aeca14aff6", "confirmed_task": "Find the next available dates for Alley Creek Camp.", "website": "https://www.recreation.gov/", "reference_length": 3, "level": "easy"} +{"task_id": "2d5a7f95f951a26838289dfd629ae850", "confirmed_task": "Find a list of houses for sale in zip code 85747 with a private pool.", "website": "https://www.redfin.com/", "reference_length": 8, "level": "medium"} +{"task_id": "26810ed9c123a62992e3eed31db3c5ee", "confirmed_task": "Show daily weather for New York City.", "website": "https://www.accuweather.com/", "reference_length": 4, "level": "easy"} +{"task_id": "c181f903ec1107b850032c17cad88393", "confirmed_task": "Help me identify a pink round pill with 150 written on it.", "website": "https://www.webmd.com/", "reference_length": 7, "level": "medium"} +{"task_id": "ef289e34a2f59a707cb07e2a6229ff03", "confirmed_task": "Compare the Acura CL 2003 with the ILX 2022.", "website": "https://www.cars.com/", "reference_length": 9, "level": "medium"} +{"task_id": "84f806c7fc15576673915f195efa72df", "confirmed_task": "Find a nationwide nearest animal shelter for birds around zip 10012.", "website": "https://www.adoptapet.com/", "reference_length": 8, "level": "medium"} +{"task_id": "be9e7dca1222714571ef3d7d59d2a41c", "confirmed_task": "Find out the cold and flu forecast and today's air quality in Champaign, IL.", "website": "https://weather.com/", "reference_length": 6, "level": "medium"} +{"task_id": "11abb668c751dd56bb41f296a8bb3a13", "confirmed_task": "Find a store near zip 30010 that provides authorized Apple services for imacs and make this one my store.", "website": "https://www.bestbuy.com/", "reference_length": 10, "level": "medium"} +{"task_id": "207e933d1bba815bcb58664b5d82c085", "confirmed_task": "Find Ohio City apartments with parking, a fitness center, and an elevator.", "website": "https://www.apartments.com/", "reference_length": 6, "level": "medium"} +{"task_id": "29b7372d5a3884a2ba831af2d117af3c", "confirmed_task": "Browse the first top news of Microsoft stock on Google Finance.", "website": "https://www.google.com/finance/", "reference_length": 3, "level": "easy"} +{"task_id": "5c00e9561eae94789443f405525a5869", "confirmed_task": "Find the recommended dosage for Vivitrol.", "website": "https://www.healthline.com/", "reference_length": 5, "level": "easy"} +{"task_id": "2532fd402d3c741b79894e6ff2269f53", "confirmed_task": "find electricians near 10203.", "website": "https://www.thumbtack.com/", "reference_length": 3, "level": "easy"} +{"task_id": "9829f3087ab1f9c8eba6b6dd2b831d25", "confirmed_task": "Play the latest video from NBA TV.", "website": "https://www.nba.com/", "reference_length": 3, "level": "easy"} +{"task_id": "783ce6a3499fa7cf25bc12f8f0ecbbbb", "confirmed_task": "Find Florida internship programs in the Mayo Clinic College of Medicine and Science.", "website": "https://www.mayoclinic.org/", "reference_length": 5, "level": "easy"} +{"task_id": "6db4a0e346976f2729ba9afcd3208941", "confirmed_task": "Look up tracking information for shipment #3023858502.", "website": "https://www.fedex.com/en-us/home.html", "reference_length": 2, "level": "easy"} +{"task_id": "1fc28d91d25ccd1c6ba268101326a654", "confirmed_task": "Find the 5-day price chart for Bitcoin.", "website": "https://www.google.com/finance/", "reference_length": 3, "level": "easy"} +{"task_id": "255bf27c43fd3f9254d6b81a5f36d3a9", "confirmed_task": "Look for the largest hunting land for auction in Kansas high plain region with mineral rights posted in the last seven days.", "website": "https://www.landwatch.com/", "reference_length": 9, "level": "medium"} +{"task_id": "a8b9edd598561d2de901864d5f40fe67", "confirmed_task": "Calculate the shipping cost for 4 pound package from Texas to New York.", "website": "https://www.fedex.com/en-us/home.html", "reference_length": 9, "level": "medium"} +{"task_id": "a6f0434ce6aff5f9b03681241b03ad82", "confirmed_task": "Find the closing stock price for Tesla on March 17, 2023.", "website": "https://finance.yahoo.com/", "reference_length": 3, "level": "easy"} +{"task_id": "415bf9da6f3db3a735ecbba3b0c76c15", "confirmed_task": "Find the nearest vet within 50 miles of zip 75228.", "website": "https://www.akc.org/", "reference_length": 9, "level": "medium"} +{"task_id": "8103786e0e5976ebf961bd062d5f39cd", "confirmed_task": "Find possible causes for the symptoms of chest pain which is sharp which is accompanied by anxiety.", "website": "https://www.mayoclinic.org/", "reference_length": 9, "level": "medium"} +{"task_id": "92160852a6bbbc165cee4e14ab0b1d59", "confirmed_task": "Find the shipping cost of a Common medium-sized box in flat-rate shipping and compare it with other parcel services.", "website": "https://www.ups.com/", "reference_length": 5, "level": "easy"} +{"task_id": "502e864440283214e0180645015f568b", "confirmed_task": "Check permit availability for a group of 4 in Brooks Camp, Katmai National Park on May 22.", "website": "https://www.recreation.gov/", "reference_length": 8, "level": "medium"} +{"task_id": "7680a920359cb1a508fbddb001b98167", "confirmed_task": "See the prediction about the girl child's height, whose current height at seven years is 4 feet and whose weight is 55 lbs, her mother is 5 feet 2, and her father is 5 feet 8.", "website": "https://www.babycenter.com/", "reference_length": 11, "level": "hard"} +{"task_id": "07ec4a12cba8090e2dc524d558ac7675", "confirmed_task": "Check drug interaction for melatonin and Folate Forte.", "website": "https://www.drugs.com/", "reference_length": 6, "level": "medium"} +{"task_id": "987bad7c6d4726d64232a8a1c3386888", "confirmed_task": "Find the seller info and seller's notes about the used car model 2011 BMW 135 with a max price of $30000.", "website": "https://www.cars.com/", "reference_length": 11, "level": "hard"} +{"task_id": "15be05973fba714e490cd9c884e4f072", "confirmed_task": "Find the procedure to get the license for Athletic Trainer.", "website": "https://ohio.gov/", "reference_length": 6, "level": "medium"} +{"task_id": "3adeea7627f4343069f38adae40f73d0", "confirmed_task": "Within 25 Miles of 96817, find a nursing home that accepts medicare.", "website": "https://health.usnews.com/", "reference_length": 7, "level": "medium"} +{"task_id": "c94551d2b18f9ad0ab31b0bd98ca42e3", "confirmed_task": "Find cats available for adoption within 10 miles of zip code 94587, Young or adult-age cats, sorted by Oldest Addition.", "website": "https://www.petfinder.com/", "reference_length": 10, "level": "medium"} +{"task_id": "4e801ba102dfaf22c7cf7a126b107609", "confirmed_task": "Find Linux platform software developers in 10080 who master the Python language and Java language with web interface project type.", "website": "https://www.thumbtack.com/", "reference_length": 8, "level": "medium"} +{"task_id": "39c388cdc468688c8139cc2bb5157c13", "confirmed_task": "Calculate the estimated car loan payment amount for an average credit-rated person for a 15,000-dollar car with a down payment of 2000 dollars and loan tenure of 48 months in zip 65215 and shop for the lowest-priced car.", "website": "https://www.cars.com/", "reference_length": 9, "level": "medium"} +{"task_id": "c8d7f2aa7eb5dd074c48c9f76f8659ad", "confirmed_task": "Show Teen Driver Safety program information.", "website": "https://www.dmv.virginia.gov/", "reference_length": 2, "level": "easy"} +{"task_id": "fd787623166785d84093565bf945fd24", "confirmed_task": "Check the interaction between Novolin N and Novolin R.", "website": "https://www.drugs.com/", "reference_length": 6, "level": "medium"} +{"task_id": "c3307a70bb12ebf56cc9ec926b368f15", "confirmed_task": "Find the interactions between Eulexin and hepatic dysfunction.", "website": "https://www.drugs.com/", "reference_length": 5, "level": "easy"} +{"task_id": "9586827ad04ee2362f4f0076bf0f0468", "confirmed_task": "Find the side effects of taking Montelukast.", "website": "https://www.drugs.com/", "reference_length": 6, "level": "medium"} +{"task_id": "34992feb69eb8e788faa06868b365c49", "confirmed_task": "Submit a request for vehicle registration renewal with title number X123456 and last 4 digits of VIN is 1234.", "website": "https://www.dmv.virginia.gov/", "reference_length": 5, "level": "easy"} +{"task_id": "47b93b9e649eadeb8d96a6e3df715c2d", "confirmed_task": "Show me Diagnoses & Treatment for Female infertility.", "website": "https://www.mayoclinic.org/", "reference_length": 4, "level": "easy"} +{"task_id": "3443e9c3151fef19a3c3a45eb2c13640", "confirmed_task": "Search for the ovulation calculator and enter Mar 1 as the first date of the period and calculate the date of ovulation and pregnancy test day.", "website": "https://www.webmd.com/", "reference_length": 12, "level": "hard"} +{"task_id": "6b5be1764692d1dc8f17dc4375b2daa8", "confirmed_task": "Show me historical data for EUR/USD.", "website": "https://finance.yahoo.com/", "reference_length": 4, "level": "easy"} +{"task_id": "16200f51d63f0a47a58fa17acd49e368", "confirmed_task": "Find a recipe that includes eggplant and mushrooms.", "website": "https://cookpad.com/", "reference_length": 3, "level": "easy"} +{"task_id": "c2153fc053112e89c2f103869c4d6890", "confirmed_task": "Find a house cleaning service in 10001 on a weekly basis.", "website": "https://www.thumbtack.com/", "reference_length": 5, "level": "easy"} +{"task_id": "5e4e89c9b6fdaee7a41aca5601b82e04", "confirmed_task": "Identify a pill with a pink color and oval shape with 894 5 number on it.", "website": "https://www.drugs.com/", "reference_length": 8, "level": "medium"} +{"task_id": "60cbbbd58eb9d28b053aef945f464228", "confirmed_task": "Look up if the phone number 555555555 is a scam.", "website": "https://www.bbb.org/", "reference_length": 6, "level": "medium"} +{"task_id": "8f80e64e44e1fada018997b2fe869683", "confirmed_task": "What are the top posts of all time on Reddit?", "website": "https://www.reddit.com/", "reference_length": 3, "level": "easy"} +{"task_id": "65c4030f22fb6eb101acfee4825f1318", "confirmed_task": "Find a female MD Cardiologist in Jacksonville, Florida.", "website": "https://www.mayoclinic.org/", "reference_length": 8, "level": "medium"} +{"task_id": "6ca20f1da01edeb49a7a42c816d8c6fe", "confirmed_task": "Find the Eligibility to get the child benefit and How it works and how to claim", "website": "https://www.gov.uk/", "reference_length": 8, "level": "medium"} +{"task_id": "2e4e21cf1449c6894b17d571c47b77ea", "confirmed_task": "Find an English bulldog near zip code 90028 that was cared for by a private owner.", "website": "https://www.adoptapet.com/", "reference_length": 8, "level": "medium"} +{"task_id": "1df24ec81137386d6476bcf343a79012", "confirmed_task": "Search for NordicTrack with the lowest price.", "website": "https://www.bestbuy.com/", "reference_length": 6, "level": "medium"} +{"task_id": "4639a54f3ab549864fd8d60b7398b1e1", "confirmed_task": "Find a white female kitten within 35 miles of zip 77494.", "website": "https://www.adoptapet.com/", "reference_length": 10, "level": "medium"} +{"task_id": "9af05e392cf3f5a8ff17aa764ba5bda6", "confirmed_task": "Get a quote from C and above-rated solar energy equipment company within 10 miles of Miami, Florida.", "website": "https://www.bbb.org/", "reference_length": 16, "level": "hard"} +{"task_id": "627f7a18d85f29a687234f1ade4585c2", "confirmed_task": "Find the current league leader in total blocked shots.", "website": "https://www.nba.com/", "reference_length": 5, "level": "easy"} +{"task_id": "0b838cd54f826c59c71f600c56b89a11", "confirmed_task": "Find all the locations for the second-best-rated used car dealer less than 5 miles from New York.", "website": "https://www.bbb.org/", "reference_length": 11, "level": "hard"} +{"task_id": "5dec0e6620849459f29e6465982c597e", "confirmed_task": "Search for 33 to 49inch Qled gaming monitor with a 240hz refresh rate that is within $1000 to $2000.", "website": "https://www.bestbuy.com/", "reference_length": 11, "level": "hard"} +{"task_id": "52efbab520734ef9bf7c09ba0f62cdc8", "confirmed_task": "Find the app for iOS.", "website": "https://www.recreation.gov/", "reference_length": 2, "level": "easy"} +{"task_id": "b1ce968a361e1088ce8d2ade6c2c9af0", "confirmed_task": "Find young cats in Seattle and show off the newest additions.", "website": "https://www.petfinder.com/", "reference_length": 6, "level": "medium"} +{"task_id": "23204728192da9f73197a613d9681c18", "confirmed_task": "What are the Symptoms and causes of fever?", "website": "https://www.mayoclinic.org/", "reference_length": 3, "level": "easy"} +{"task_id": "a69d2934fe54fef165490a5a2d95bf38", "confirmed_task": "Show me recipes for pancakes with wheat and without beetroot.", "website": "https://cookpad.com/", "reference_length": 6, "level": "medium"} +{"task_id": "e9f4dfc67e0e6aa37f05f7cc5aa7428c", "confirmed_task": "Browse pediatricians near zip code 90028 who specialize in Internal Medicine and have a rating of at least 4 stars.", "website": "https://www.healthgrades.com/", "reference_length": 9, "level": "medium"} +{"task_id": "2218042362d8fae73756eb309848c2b2", "confirmed_task": "Compare Audi A7 with Audi A6, both made in 2023, and hide similarities.", "website": "https://www.cars.com/", "reference_length": 9, "level": "medium"} +{"task_id": "ba2a469af584f16da93ce6a7430cf7e5", "confirmed_task": "Search for a beginner\u2019s course in computer science that includes advertisement skills.", "website": "https://www.coursera.org/", "reference_length": 7, "level": "medium"} +{"task_id": "26784156ae9859a0dd6c5920eb106f91", "confirmed_task": "calculate and search rent for a $6000 monthly income with 30% rent budget near 90012 area.", "website": "https://www.apartments.com/", "reference_length": 8, "level": "medium"} +{"task_id": "47e314cc452c540524ffb7cf520285a3", "confirmed_task": "Find the park that offers the cheapest paddling permits.", "website": "https://www.recreation.gov/", "reference_length": 6, "level": "medium"} +{"task_id": "271b36efd4346721b5542488ff997042", "confirmed_task": "Browse 8K Samsung TVs that are open box.", "website": "https://www.bestbuy.com/", "reference_length": 4, "level": "easy"} +{"task_id": "6b2cfae0ef25c73d1224b6ab74cb8b63", "confirmed_task": "Find Devin Booker's highest-scoring points per game playoff run.", "website": "https://www.nba.com/", "reference_length": 7, "level": "medium"} +{"task_id": "0a54069a0ef542e571d1fee7f39c93d5", "confirmed_task": "Browse senior spayed/neutered dogs near zip code 90028.", "website": "https://www.adoptapet.com/", "reference_length": 6, "level": "medium"} +{"task_id": "4e3f6a538cc1f7321cfc50260db9545d", "confirmed_task": "Look up the current temperature for zip code 10019.", "website": "https://www.theweathernetwork.com/", "reference_length": 2, "level": "easy"} +{"task_id": "f00e7accfb4a5e09680bdb326e6274ad", "confirmed_task": "Check the hourly forecast for Boston.", "website": "https://www.accuweather.com/", "reference_length": 3, "level": "easy"} +{"task_id": "6174e5ddd40cfbdc33ee1502f40bac39", "confirmed_task": "Find a day-use park that offers horseback riding near Nashville.", "website": "https://www.recreation.gov/", "reference_length": 6, "level": "medium"} +{"task_id": "547f5729c59d5d12a457a3ebb74c31c6", "confirmed_task": "Search for 3 bedroom condos with 2 bathrooms within $1500- $2500 range in NYC.", "website": "https://www.apartments.com/", "reference_length": 14, "level": "hard"} +{"task_id": "0b2623e9fa5cea997f76490bcbc5220f", "confirmed_task": "Find a list of shorthaired dogs available for adoption within 100 miles of zip code 94587 that are good with kids and cats, and have been on Petfinder for over 30 days.", "website": "https://www.petfinder.com/", "reference_length": 13, "level": "hard"} +{"task_id": "3ae28b3c440efe87dc700480b78ac608", "confirmed_task": "Find the closest 5-star rated dentist to zip code 98011.", "website": "https://www.healthgrades.com/", "reference_length": 9, "level": "medium"} +{"task_id": "0632e496d37badee0350dad358f047c5", "confirmed_task": "Browse recipes for gluten-free chocolate chip cookies that can be made without nuts.", "website": "https://cookpad.com/", "reference_length": 4, "level": "easy"} +{"task_id": "aafd1fddea1558466ac6133934d35156", "confirmed_task": "Find a Single-Family House for Rent in Houston, TX with 1 bed.", "website": "https://www.apartments.com/", "reference_length": 8, "level": "medium"} +{"task_id": "246d654fab7c31d9651007e39e75f74f", "confirmed_task": "Open the most helpful 5-star reviews of Alpine Ridge.", "website": "https://www.recreation.gov/", "reference_length": 5, "level": "easy"} +{"task_id": "690d7b4a285fdb1e9dabf973bf46ae4d", "confirmed_task": "Browse iPhone X for sale that is in good condition, has a max price of 400, and searches in titles only.", "website": "https://craigslist.org/", "reference_length": 8, "level": "medium"} +{"task_id": "c43a7dccf5c44f7b45a821e712dd1970", "confirmed_task": "Take a newsletter subscription with my email id (buckeye.foobar@gmail.com) for Allergies and asthma, Anxiety and depression, nutrition, diabetes, breast cancer, and migraine with email id.", "website": "https://www.healthline.com/", "reference_length": 8, "level": "medium"} +{"task_id": "d5c34bf39eb6096ae5d439325cde4d32", "confirmed_task": "Find a DMV center in Richmond.", "website": "https://www.dmv.virginia.gov/", "reference_length": 5, "level": "easy"} +{"task_id": "180ed2ec377ef3a4af9035a21522091a", "confirmed_task": "Find the way to give a gift to UM-Dearborn.", "website": "https://umich.edu/", "reference_length": 5, "level": "easy"} +{"task_id": "c521933dad9c0ef9f1dfa2f38b8e4405", "confirmed_task": "See the monthly forecast for Atlanta, GA.", "website": "https://www.accuweather.com/", "reference_length": 3, "level": "easy"} +{"task_id": "9b5dfe54a1c14c5c6336bae7374c3bb5", "confirmed_task": "Find a UPS Access Point near SPRING, TX and services provided by them.", "website": "https://www.ups.com/", "reference_length": 8, "level": "medium"} +{"task_id": "c073ac1bcf40f84c599affc97edbc396", "confirmed_task": "Search for the cheapest apartment in Detroit for a student.", "website": "https://www.apartments.com/", "reference_length": 9, "level": "medium"} +{"task_id": "73d08420706ae205a9c5be28b6d4e80f", "confirmed_task": "Show me the rules and cancellation for Alley Spring.", "website": "https://www.recreation.gov/", "reference_length": 3, "level": "easy"} +{"task_id": "0a0fa834ce41b5297c6474293383759d", "confirmed_task": "What are the onboard activities of the highest-rated Regent Seven Seas Cruise ship based on Costco member reviews?", "website": "https://www.costco.com/", "reference_length": 8, "level": "medium"} +{"task_id": "a13e4231a3d6a7000c622c56448d97ba", "confirmed_task": "Find an Airbnb in Cleveland for three nights. The check-in date is the day after tomorrow. We have 2 adults, 2 kids, and 1 pet. The budget is $100 to $300 per night. Essential amenities include free parking, a washer, and a gym.", "website": "https://www.airbnb.com/", "reference_length": 19, "level": "hard"} +{"task_id": "bb518416a786fdb9b9bbf0c78515595e", "confirmed_task": "Browse the class schedule of graduate-level computer science courses.", "website": "https://www.osu.edu/", "reference_length": 4, "level": "easy"} +{"task_id": "b99c02965196d51e80ac7539e33f335b", "confirmed_task": "Please find graduate-level computer science courses scheduled on Tuesdays starting time from 2:00 to 6:00 PM in the Fall 2023 semester.", "website": "https://www.berkeley.edu/", "reference_length": 9, "level": "medium"} +{"task_id": "27fa3ac20745d3d35e89fae157f63069", "confirmed_task": "Browse the class schedule of graduate-level chemistry courses on Monday afternoons in the winter of 2023.", "website": "https://www.stanford.edu/", "reference_length": 11, "level": "hard"} +{"task_id": "b4aa7315e31dfcdc52baf7771be260c9", "confirmed_task": "Find the HGX H100 driver for Ubuntu 22.04 on AMD64 CPU.", "website": "https://www.nvidia.com/", "reference_length": 11, "level": "hard"} +{"task_id": "442a450e696a96085257db6297891a4d", "confirmed_task": "Using a calculator to determine how much I can have in my 401(k) account at retirement, if I work from age 22 to 65, with an annual rate of return of 3%, annual employee contributions of $8,000, and annual employer contributions of $8,000.", "website": "https://www.chase.com/", "reference_length": 11, "level": "hard"} +{"task_id": "9ed3827266b3b804f485859c3d00401e", "confirmed_task": "If I'm 30, plan to retire at 65, and can save $300/month, with a 3% annual return, 13% current tax rate, and 24% retirement tax rate, show the comparison chart between Traditional and Roth IRA.", "website": "https://www.chase.com/", "reference_length": 12, "level": "hard"} +{"task_id": "c801d1c951f59297f526bab84fa86c6e", "confirmed_task": "Browse the latest negative reviews from players with over 100 hours of playtime for the game that won the 2023 VR Game of the Year Award.", "website": "https://store.steampowered.com/", "reference_length": 11, "level": "hard"} +{"task_id": "7c09c2c7c87cf6bb1138701eb54284ea", "confirmed_task": "Find the comments for the most popular news in the past month under the Quantum Physics topic.", "website": "https://phys.org/", "reference_length": 8, "level": "medium"} +{"task_id": "afcebfed28bea091d58f49ea6cb8194b", "confirmed_task": "Find the most reviewed gluten-free multivitamins from CVS Health Brand under $15.", "website": "https://www.cvs.com/", "reference_length": 12, "level": "hard"} +{"task_id": "64345c365f544375357c7b67917f08a0", "confirmed_task": "Look for the newest refrigerator that is 34-36 inches wide, priced between $1,000 and $2,000, and has a customer review rating of 4 stars or higher.", "website": "https://www.costco.com/", "reference_length": 8, "level": "medium"} +{"task_id": "ab6ee3b83aab6cd283320f5e01003cff", "confirmed_task": "Find the tech specs of the MacBook Pro 16-inch introduced in November 2023.", "website": "https://www.apple.com/", "reference_length": 7, "level": "medium"} +{"task_id": "33bd2cdcea4fcc42a09a8a1e4e5841c6", "confirmed_task": "Add a 5-piece Tenders Combo to my bag with Sweet Corn as the side, Sweet Tea as the drink, and both Honey BBQ and Honey Mustard sauces. Select the store closest to Zip code 10001 for pick-up tomorrow at 12:00 PM.", "website": "https://www.kfc.com/", "reference_length": 23, "level": "hard"} +{"task_id": "47186fac8e7c7277af01144644eb4e0b", "confirmed_task": "What is the ownership cost of the first car in the list \"top buys 2025\"?", "website": "https://www.parkers.co.uk/", "reference_length": 3, "level": "easy"} +{"task_id": "fa9adb815b85d259f943d81874a052e5", "confirmed_task": "Browse a user homepage that reposted the top song from the Top 50 Rock chart.", "website": "https://soundcloud.com/", "reference_length": 6, "level": "medium"} +{"task_id": "b922508886ded315c9835457a6eb43ea", "confirmed_task": "Browse tenured/tenure-track faculty positions in Computer Sciences & Technology in California.", "website": "https://jobs.chronicle.com", "reference_length": 6, "level": "medium"} +{"task_id": "5d542a7ec1fa142ba73cc87d970caf39", "confirmed_task": "Find the most cited publication at the 2022 CVPR main conference.", "website": "https://dblp.org/", "reference_length": 6, "level": "medium"} +{"task_id": "864244b6969e0f8733b0eb1ca06cd51f", "confirmed_task": "Find the race time for who wins the first place in the last race of the 2023 Formula 1 (F1).", "website": "https://www.espn.com/", "reference_length": 6, "level": "medium"} +{"task_id": "01abae9608f2d8752a83e08f136f720c", "confirmed_task": "Show me the code for the company that is the top mover in the Cboe Europe Technology Sector Index (BEPTEC) as of the latest market close.", "website": "https://www.cboe.com/", "reference_length": 6, "level": "medium"} +{"task_id": "da8f3823a827c7d3a492f383808e7912", "confirmed_task": "Find and open the earliest press release.", "website": "https://www.instructure.com/", "reference_length": 6, "level": "medium"} +{"task_id": "8689af4d33ce00bf2cdd8987d3bbfd86", "confirmed_task": "Add the cheapest certified refurbished iPad Air with 256GB of storage in any shade of blue to my bag.", "website": "https://www.apple.com/", "reference_length": 8, "level": "medium"} +{"task_id": "78f397336b6fd1cbba0127db7a8cd502", "confirmed_task": "Browse the upcoming SuperBike events taking place in Italy.", "website": "https://www.redbull.com/", "reference_length": 8, "level": "medium"} +{"task_id": "3dca7cbe7d086619d837ff9f5312cebc", "confirmed_task": "Can you show me products under the category path 'Automotive' -> 'Car Jack', with an additional filter for the color pink?", "website": "https://us.shein.com/", "reference_length": 4, "level": "easy"} +{"task_id": "b962927dfe03bf2274a54381127ed433", "confirmed_task": "Find the best-selling vinyl record by an artist from New York City in the classical music genre.", "website": "https://bandcamp.com/", "reference_length": 8, "level": "medium"} +{"task_id": "78baf9dbe7c3532f7d7ef4cc22a7f065", "confirmed_task": "Find the most popular digital trends report in the Finance & Insurance industry within the region of China.", "website": "https://www.statista.com/", "reference_length": 8, "level": "medium"} +{"task_id": "c7c07ec10c668625a21ba64165d719bb", "confirmed_task": "Find the total monthly price for four prepaid unlimited lines without autopay discounts.", "website": "https://www.verizon.com/", "reference_length": 8, "level": "medium"} +{"task_id": "512fd4deab099b8dc0dcfc0ec48a3c63", "confirmed_task": "Identify the open issue with the most comments in the first trending open-source repository this week.", "website": "https://github.com/", "reference_length": 8, "level": "medium"} +{"task_id": "d9d8b7d84a3f8d057e368254fe8d65e2", "confirmed_task": "Find the first commit submitted by NielsRogge to the official repository of the SAM2 model.", "website": "https://github.com/", "reference_length": 8, "level": "medium"} +{"task_id": "157f4a79d55e8fa3fd55ba772ba40fbc", "confirmed_task": "Find the most popular blue Lilo & Stitch toys.", "website": "https://www.disney.com/", "reference_length": 9, "level": "medium"} +{"task_id": "62c8d970b3d13891f355911e5a8f4030", "confirmed_task": "Find the top game listed in the Steam Deck's top-played list over the past year. Then, browse reviews for that game from players who have played over 100 hours and primarily use a Steam Deck.", "website": "https://store.steampowered.com/", "reference_length": 9, "level": "medium"} +{"task_id": "11857213ca01510f12813740afd59918", "confirmed_task": "Add the most top-selling Adidas men's basketball shoe in red, size 10 to my cart.", "website": "https://www.adidas.com/", "reference_length": 10, "level": "medium"} +{"task_id": "47bfe8a7e0e4e7efc837287b407fbe90", "confirmed_task": "Compare the first and second most popular smartphones manufactured by Xiaomi and show the comparison chart.", "website": "https://versus.com/", "reference_length": 10, "level": "medium"} +{"task_id": "bb314cb80f0f8489135cbf59074d11e2", "confirmed_task": "Open the page for the first Best Paper Award video recording of talks from ICLR 2016.", "website": "https://iclr.cc/", "reference_length": 4, "level": "easy"} +{"task_id": "1aeca99e6a60b0e3aefb3ef212bdce79", "confirmed_task": "Find full-time legal occupation jobs in San Diego County with a minimum salary of $4,000+ per month.", "website": "https://www.ca.gov/", "reference_length": 10, "level": "medium"} +{"task_id": "d730f4ff450da1bd60a836163736ef6a", "confirmed_task": "Find the best-selling GORE-TEX men's hiking shoe priced between $100.00 and $199.99 with a rating of 4 stars or higher, and show its most helpful comment.", "website": "https://www.rei.com/", "reference_length": 10, "level": "medium"} +{"task_id": "fe33894188d20d7469f37a9fd855e7ff", "confirmed_task": "Find me Python 3.9 packages on PyPI that are designed for the Web Environment, licensed under MIT, have a stable production status, and are intended for developers.", "website": "https://pypi.org/", "reference_length": 11, "level": "hard"} +{"task_id": "71f8de1834599fba443f40dbbfab8edd", "confirmed_task": "Search for papers related to reinforcement learning under the topics of computer science and mathematics on arxiv, with recent submission dates between September 2024 and January 2025.", "website": "https://arxiv.org/", "reference_length": 11, "level": "hard"} +{"task_id": "c8c1ff115879b3afd14280beb1559b13", "confirmed_task": "Find the latest Doraemon video in MP4 format that is over 20 minutes long and has a medium file size.", "website": "https://www.4shared.com/", "reference_length": 12, "level": "hard"} +{"task_id": "d4fb78b7e74508cd3b33f01cf9200997", "confirmed_task": "Show the figure comparing Occupational Fatalities Trends between Ohio and New York.", "website": "https://www.americashealthrankings.org/", "reference_length": 12, "level": "hard"} +{"task_id": "0e42c3a73f2aece1f854e0ba55b7c8b0", "confirmed_task": "Find a gas station in Manhattan, NY with a rating above 4.0, and sort the user reviews by the lowest rating.", "website": "https://www.google.com/maps/", "reference_length": 7, "level": "medium"} +{"task_id": "96afb3c51146b0c2a9c55f039a5ea6d6", "confirmed_task": "Find the most frequent word that rhymes with \"thought\" and has three syllables.", "website": "https://www.merriam-webster.com/", "reference_length": 5, "level": "easy"} +{"task_id": "59912927c1fddee6ded8a49986896bc2", "confirmed_task": "Look for the most useful reviews of the highest-rated anti-reflective TVs with screen sizes from 55\" to 64\" and prices ranging from $300 to $1500.", "website": "https://www.samsung.com/", "reference_length": 14, "level": "hard"} +{"task_id": "e43cbc8a0bf9e999884928d11006f894", "confirmed_task": "Browse the list of things to do in Miami that have a rating of 9+ (wonderful), last between 1 to 4 hours per session, cost under $100 per person, and are available for booking between next Monday and next Friday.", "website": "https://www.expedia.com/", "reference_length": 15, "level": "hard"} +{"task_id": "1b867afecf072cb877ebfa4069263746", "confirmed_task": "Display the figure comparing unemployment trends among women in Illinois and Michigan.", "website": "https://www.americashealthrankings.org/", "reference_length": 15, "level": "hard"} +{"task_id": "c3a333968fc3c43d7f2688f425a0d633", "confirmed_task": "Find the cheapest certified pre-owned Porsche 911 with a model year of 2019 or newer, within a 200-mile radius of ZIP code 97007.", "website": "https://www.porsche.com/", "reference_length": 15, "level": "hard"} +{"task_id": "bb5d90e6f2fbc0ae146f7c1998c2b4a1", "confirmed_task": "Find the most viewed TED talk on the topic of robots that lasts between 12 and 18 minutes.", "website": "https://www.ted.com/", "reference_length": 15, "level": "hard"} +{"task_id": "c577a14301a725e09ccd269a3e0b271e", "confirmed_task": "Return the page for the highest-rated red wine from Oregon under $40 that pairs well with either mushrooms or veal.", "website": "https://www.vivino.com/", "reference_length": 15, "level": "hard"} +{"task_id": "c6c9dc6079677cef594cec2fa6b16602", "confirmed_task": "Add the cheapest black sofa with at least three seats, a leather finish, and at least four stars to my cart.", "website": "https://www.ikea.com/", "reference_length": 16, "level": "hard"} +{"task_id": "c39d6c245f8243993e707d54d2f4acec", "confirmed_task": "Browse the final skin in the list for the champion Ahri.", "website": "https://www.leagueoflegends.com/", "reference_length": 18, "level": "hard"} +{"task_id": "b2f4fde2fce122a93c7b578086cb0585", "confirmed_task": "Find the cheapest hotel + flight + car package from New York to San Francisco, departing tomorrow and returning on the fourth day from departure, for two adults and a six-year-old child. The package should be one room with free breakfast and spa access.", "website": "https://www.booking.com/", "reference_length": 19, "level": "hard"} +{"task_id": "d02d236836924919f35f2438d9ed2374", "confirmed_task": "Browse the top 250 movies and find one movie that is available on AMC+.", "website": "https://www.imdb.com/", "reference_length": 22, "level": "hard"} +{"task_id": "3621b099326c7aebd2e2dac6be3b52d1", "confirmed_task": "Open the profile page of the leader of the Nvidia Learning and Perception Lab.", "website": "https://www.nvidia.com/", "reference_length": 5, "level": "easy"} +{"task_id": "f27b393bbd2082f92b566270c4b74fe6", "confirmed_task": "Find a large van for sale from the year 2024 or newer with up to 10,000 miles.", "website": "https://www.parkers.co.uk/", "reference_length": 7, "level": "medium"} +{"task_id": "ba01ea557b73f864c35ebba0dd6f3cb2", "confirmed_task": "Find the top-rated hotel in Manhattan, NY, suitable for 4 guests, and identify the fastest public transportation option from the hotel to LGA airport.", "website": "https://www.google.com/maps/", "reference_length": 14, "level": "hard"} +{"task_id": "662ae0f2d3ac851dbcdd245f908277e3", "confirmed_task": "What is the second stop among the best stops along the road trip from Yellowstone National Park to Las Vegas?", "website": "https://wanderlog.com/", "reference_length": 5, "level": "easy"} +{"task_id": "461ab9b0c7b20ac5f912704480979c65", "confirmed_task": "Find the NYSE Rule 605 Market Center Files data for July 2024.", "website": "https://www.nyse.com/", "reference_length": 5, "level": "easy"} +{"task_id": "a96fca87a17d792644e736d1d10d3cbe", "confirmed_task": "View the pricing plan for 'Business'. Specifically, we have 100 users. We need a 1PB storage quota and a 50 TB transfer quota.", "website": "https://mega.io/", "reference_length": 5, "level": "easy"} +{"task_id": "2c8ef01a92c71ba9ef2e59bb17eea2b3", "confirmed_task": "If there are any discounts on the Apple Mac Studio, add the one with the largest absolute discount to my cart; otherwise, add the cheapest one.", "website": "https://www.costco.com/", "reference_length": 6, "level": "medium"} +{"task_id": "3084bc225219fcb73dc1cb0f97276c1c", "confirmed_task": "Get quotes for a package weighing 10 lbs with dimensions of 2 inches in length, width, and height, being shipped from Long Beach, 90802 to Portland, 97201.", "website": "https://www.ups.com/", "reference_length": 7, "level": "medium"} +{"task_id": "949dc965a6c23a95663b3bc2ca2c3a8a", "confirmed_task": "Find UA or AA flights from London to New York that arrive between 8:00 PM and 11:00 PM on FlightAware.", "website": "https://www.flightaware.com/", "reference_length": 13, "level": "hard"} +{"task_id": "636b07af4dd97c1793733db1fd1b90b8", "confirmed_task": "Filter handbags to evening bags that are blue, and polyester and cost less than $100.", "website": "https://www.macys.com/", "reference_length": 9, "level": "medium"} +{"task_id": "38203be65401943aea2179c4c680059a", "confirmed_task": "Check the status of bus S92 for any disruptions on new.mta.info.", "website": "https://new.mta.info/", "reference_length": 6, "level": "medium"} +{"task_id": "cf757a775fa1224acfc7998489e199a8", "confirmed_task": "Find a flight from Dublin to anywhere under $100 tomorrow on Ryanair.", "website": "https://www.ryanair.com/", "reference_length": 13, "level": "hard"} +{"task_id": "d8e2a81fa621ce4737e5ea85671b630e", "confirmed_task": "Search for regular weekday jobs around 14810 that I can start within two weeks or three.", "website": "https://hiring.amazon.com/", "reference_length": 13, "level": "hard"} +{"task_id": "63d6866fc000fcb1f153e07604bd1395", "confirmed_task": "What are the Nearby Attractions from the most popular attraction in Hong Kong?", "website": "https://us.trip.com/", "reference_length": 8, "level": "medium"} +{"task_id": "199be0b54a436daee74247971fc684ee", "confirmed_task": "Add a Macy's Happy Birthday E-Gift Card worth $50 from Shak to my cart, with the birthday wish message \"Happy birthday, wish you many more years to come\", addressed to christene (christenson@gmail.com).", "website": "https://www.macys.com/", "reference_length": 11, "level": "hard"} +{"task_id": "c00437fd76a7a83b57f3dc4e5dbc41f8", "confirmed_task": "Check the most recent full-time medical health and safety jobs, requiring 1-3 years of industry experience available in the US.", "website": "https://www.amazon.jobs/", "reference_length": 8, "level": "medium"} +{"task_id": "fc53ddd3421411a41c1020a3fdc84ec4", "confirmed_task": "I want to purchase an open-box Samsung Galaxy S25 Plus in excellent condition and trade in a gray Galaxy S20 5G (Verizon), with a perfect screen, in good condition. How much would it cost?", "website": "https://www.bestbuy.com/", "reference_length": 17, "level": "hard"} +{"task_id": "9d46ccb915eff39ee1ae1e7328f5f20d", "confirmed_task": "Get a quote for the fastest shipping available for 5 lbs with dimensions of 4 inches in length, width, and height from New York, NY 10001, USA to Truckee, California 96162, USA.", "website": "https://www.ups.com/", "reference_length": 8, "level": "medium"} +{"task_id": "d1970c16271496cbbe166ecbecc0a1d8", "confirmed_task": "I'm 25 and located in Texas. Shop for 2020 made dry red wine made in United States priced between 15-20 dollars and add 5 bottles to the cart.", "website": "https://macyswineshop.com/", "reference_length": 13, "level": "hard"} +{"task_id": "7211af65d266402f99499053924262e9", "confirmed_task": "View the most recent job posting for a full-time pharmacy position in the US.", "website": "https://www.amazon.jobs/", "reference_length": 8, "level": "medium"} +{"task_id": "4464a8421f8bc8786524a499258dfad3", "confirmed_task": "Check the specifications of the best-selling HP FHD laptop with 16 GB RAM and core i7 running on Windows 11.", "website": "https://www.bestbuy.com/", "reference_length": 12, "level": "hard"} +{"task_id": "f707d765bca668830745d20807d7bee6", "confirmed_task": "Show me the list of young female English Spot rabbits available for adoption in Chicago, IL, within 50 miles.", "website": "https://www.petfinder.com/", "reference_length": 14, "level": "hard"} +{"task_id": "d392e154c1c6ffbb26e2331c3afafc67", "confirmed_task": "Add a $100 Best Buy gift card for a birthday to my cart.", "website": "https://www.bestbuy.com/", "reference_length": 6, "level": "medium"} +{"task_id": "a5c87cc1c94a090c9a8dc2c8b6a125d0", "confirmed_task": "Find the SO2 air quality over the past hour for Maine North, County Cork, Ireland.", "website": "https://www.accuweather.com/", "reference_length": 15, "level": "hard"} +{"task_id": "367d843c640637745e8fafa741cca13b", "confirmed_task": "Find a condo for rent in Houston, TX, with a monthly rent of no more than 30% of an income of $8000. The condo should have a minimum area of 600 square feet, and the move-in date is the 1st of next month.", "website": "https://www.apartments.com/", "reference_length": 15, "level": "hard"} +{"task_id": "84ef883a37af638c3bcf7561f28ce80a", "confirmed_task": "Find the cheapest used hatchback car listing in Madison which has black interiors with a heated seat option and premium sound system.", "website": "https://www.cars.com/", "reference_length": 12, "level": "hard"} +{"task_id": "d9a8689393effeed75ea0866e44e1def", "confirmed_task": "Find the address and phone of the Office of the Inspector General (OIG).", "website": "https://www.justice.gov/", "reference_length": 8, "level": "medium"} +{"task_id": "1bc154377120ec15b18dbabdba49c741", "confirmed_task": "Book 4 tickets in the upper for any Kevin Hart show in New York in the next three months and view ticket prices with estimated fees.", "website": "https://www.stubhub.com/", "reference_length": 12, "level": "hard"} +{"task_id": "28e7574e7bd6d14f36d2988a5ef2bd23", "confirmed_task": "Get a part-time job within 5 miles of Moscow, Idaho in the accommodation and food services industry, as a chef, and show jobs for corporate only.", "website": "https://ohiomeansjobs.ohio.gov/", "reference_length": 12, "level": "hard"} +{"task_id": "1c3b747ae12ccee895745f82e3f2ef8a", "confirmed_task": "Identify the ongoing competition that offers the highest prize and find the code that received the most votes in that competition.", "website": "https://www.kaggle.com/", "reference_length": 11, "level": "hard"} +{"task_id": "d1807551297ac60ecaaabbd2a2ed301a", "confirmed_task": "Find the No.1 children's hospital in the California that specializes in Neonatology.", "website": "https://health.usnews.com/", "reference_length": 8, "level": "medium"} +{"task_id": "7abdceee212151f187ee1a1744c57606", "confirmed_task": "Can you show me the page with the filing fee for a self-petitioned I-140 application?", "website": "https://www.uscis.gov/", "reference_length": 6, "level": "medium"} +{"task_id": "0e5536aaad9d3462b06cf725e6ed535a", "confirmed_task": "Show me the page with average wait times for U.S. citizens arriving at Raleigh-Durham International Airport on 2025-03-12.", "website": "https://www.cbp.gov/", "reference_length": 11, "level": "hard"} +{"task_id": "bc2ce7f206045dd2d322e5695a947219", "confirmed_task": "Estimate the federal income tax I would owe on $158,500 of taxable income in ZIP code 97007, filing as single.", "website": "https://smartasset.com/", "reference_length": 6, "level": "medium"} +{"task_id": "7e6993f2c5cd72c44809024f0bc85dc1", "confirmed_task": "Create a meme with a frog as the background and leave the only text with \"Enjoy your life\".", "website": "https://imgur.com/", "reference_length": 8, "level": "medium"} +{"task_id": "a48e2f1ee8d87eaeea56fe5e730427e6", "confirmed_task": "Pass the first trending chess puzzle.", "website": "https://www.chess.com/", "reference_length": 7, "level": "medium"} +{"task_id": "dd44c665cec1e9c929a4c5f074e7844a", "confirmed_task": "Find parking near the San Francisco Museum of Modern Art from June 18, 1:00 PM to 5:00 PM. I'm driving a Ford F-150 and need a garage that allows in-and-out privileges. If there are multiple options, show me the details of the one with the lowest price.", "website": "https://spothero.com/", "reference_length": 17, "level": "hard"} +{"task_id": "99daaed9a83c266341d28aa40067d376", "confirmed_task": "Find the most popular board game on the 'The Hotness' list that has a rating above 7.5 and is suitable for 2 players.", "website": "https://boardgamegeek.com/", "reference_length": 5, "level": "easy"} +{"task_id": "7072d09436972a5d5fe7476e3e9f1559", "confirmed_task": "Show me the comparison of the first two personal credit cards that do not charge foreign transaction fees.", "website": "https://www.americanexpress.com/", "reference_length": 10, "level": "medium"} +{"task_id": "2c20d87a046fadcb6ff07ee877bfbf37", "confirmed_task": "Open the form 8843 for tax year 2022.", "website": "https://www.irs.gov/", "reference_length": 8, "level": "medium"} +{"task_id": "753f372c189d3b306623cb0c65b50320", "confirmed_task": "Compare the U.S. ETP Odd Lot Rate (%) between Quartile 1 and Quartile 4, viewing quartiles by price, and display the chart with a logarithmic scale on the vertical axis.", "website": "https://www.sec.gov/", "reference_length": 9, "level": "medium"} +{"task_id": "733f1d8bf79d5bc2240c5357f928ffff", "confirmed_task": "Find the cheapest travel deal or discount to Thailand that lasts more than 10 days, departs in next month, and show the total price.", "website": "https://www.tourradar.com/", "reference_length": 10, "level": "medium"} +{"task_id": "f05e87c5b92d9869e08806103c1c15a1", "confirmed_task": "Find all startup companies from the 2022 and 2023 Y Combinator batches that are based in France and currently have job openings.", "website": "https://www.ycombinator.com/", "reference_length": 12, "level": "hard"} +{"task_id": "3ef64f34eae59c9fac7ee9a4f18b4a0c", "confirmed_task": "Find and open an animal learning course on YouTube Kids for my 6-year-old without login in. As a parent born in 1992, I would prefer not to enable search.", "website": "https://www.youtube.com/", "reference_length": 16, "level": "hard"} +{"task_id": "f158345f8489e0d1d91e28768c39bca1", "confirmed_task": "Estimate the total cost (with basic support) of using 5 million input tokens and 5 million output tokens each for GPT-4o and GPT-4o Mini, both deployed in the US/EU Data Zones under Standard (On-Demand) in the East US region.", "website": "https://azure.microsoft.com/", "reference_length": 13, "level": "hard"} +{"task_id": "1ab384fb3a791edfb410213cc6b82151", "confirmed_task": "Show me the result of a proton emission decay for a Beryllium nucleus with 6 protons and 4 neutrons in the simulation.", "website": "https://phet.colorado.edu/", "reference_length": 13, "level": "hard"} +{"task_id": "1223b07536a87e0170ff87cbbebd1d3c", "confirmed_task": "Complete a multiplication quiz on https://www.coolmath4kids.com/, covering multiplication facts for 11-12. The quiz should consist of 10 questions, with unlimited time allowed for each. The goal is to achieve a perfect score of 10 out of 10.", "website": "https://www.coolmath4kids.com/", "reference_length": 24, "level": "hard"} diff --git a/sdk/stagehand-ts/evals/datasets/webvoyager/WebVoyager_data.jsonl b/sdk/stagehand-ts/evals/datasets/webvoyager/WebVoyager_data.jsonl new file mode 100644 index 0000000..7ba2ebd --- /dev/null +++ b/sdk/stagehand-ts/evals/datasets/webvoyager/WebVoyager_data.jsonl @@ -0,0 +1,643 @@ +{"web_name": "Allrecipes", "id": "Allrecipes--0", "ques": "Provide a recipe for vegetarian lasagna with more than 100 reviews and a rating of at least 4.5 stars suitable for 6 people.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--1", "ques": "Find a recipe for a vegetarian lasagna that has at least a four-star rating and uses zucchini.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--2", "ques": "Find a recipe for a vegetarian lasagna under 600 calories per serving that has a prep time of less than 1 hour.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--3", "ques": "Locate a recipe for vegan chocolate chip cookies with over 60 reviews and a rating of at least 4.5 stars on Allrecipes.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--4", "ques": "Find a recipe for Baked Salmon that takes less than 30 minutes to prepare and has at least a 4 star rating based on user reviews.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--5", "ques": "Search for a popular Pasta Sauce with more than 1000 reviews and a rating above 4 stars. Create a shopping list of ingredients for this recipe.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--6", "ques": "Search for a vegetarian lasagna recipe that has at least a four-star rating and over 500 reviews.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--7", "ques": "Find a popular recipe for a chocolate chip cookie and list the ingredients and preparation steps.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--8", "ques": "Search for a recipe for Beef Wellington on Allrecipes that has at least 200 reviews and an average rating of 4.5 stars or higher. List the main ingredients required for the dish.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--9", "ques": "Find a high-rated recipe for vegetarian lasagna, list the key ingredients required, and include the total preparation and cook time stated on the recipe.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--10", "ques": "Find The Most Popular Recipes of the 1960s, noting the recipe name, preparation time and total time of the second recipe in this collection.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--11", "ques": "Discover a suitable chocolate cupcake recipe on Allrecipes that has a preparation time of under 1 hour and at least 100 user reviews.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--12", "ques": "Search for a popular cookie recipe on Allrecipes with more than 1000 reviews and a rating of 4.5 stars or better. Provide the list of ingredients needed.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--13", "ques": "Find a recipe with over 100 reviews for Fried Fish on Allrecipes, list the Full Nutrition Label and tell me the amount of Iron per Serving.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--14", "ques": "Search for a recipe that includes \"chicken breast\" and \"quinoa\" with preparation time under 30 minutes on Allrecipes.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--15", "ques": "Choose a dessert recipe on Allrecipes with a prep time of less than 30 minutes, has chocolate as an ingredient, and has a user rating of 4 stars or higher. Provide the name of the recipe, ingredients list, and step-by-step instructions.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--16", "ques": "Find a five-star rated chocolate chip cookie recipe that takes less than 1 hour to make on Allrecipes. Note how many reviews the recipe has and the main ingredients required.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--17", "ques": "Find the Easy Vegetarian Spinach Lasagna recipe on Allrecipes and tell me what the latest review says.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--18", "ques": "Find a recipe for a vegetarian lasagna that has over 300 reviews and an average rating of 4.5 or higher on Allrecipes.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--19", "ques": "Find a vegan lasagna recipe on Allrecipes that requires 10 ingredients or less and has feedback of more than 200 reviews. Provide a brief overview of the ingredient list and the total prep and cook time.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--20", "ques": "Find a recipe for a cauliflower pizza crust that has a preparation time of under 30 minutes and a rating of at least 4 stars on Allrecipes. Include the number of calories per serving.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--21", "ques": "Locate a high-rated recipe for gluten-free brownies on Allrecipes with at least 50 reviews. List the main ingredients and the total time required for preparation and cooking.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--22", "ques": "Find a recipe for a healthy avocado salad on Allrecipes that has a preparation time of less than 20 minutes and more than 30 user reviews. Include the nutritional information per serving.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--23", "ques": "Search Allrecipes for a baked lemon chicken recipe that has a prep time under 45 minutes, with at least a 4.5-star rating based on user reviews, and over 200 reviews. List the primary ingredients required.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--24", "ques": "Locate a recipe for an eggplant Parmesan on Allrecipes with a rating of at least 4.5 stars and over 50 reviews. Include the preparation time and the number of servings provided by the recipe.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--25", "ques": "Find a popular quinoa salad recipe on Allrecipes with more than 500 reviews and a rating above 4 stars. Create a shopping list of ingredients for this recipe and include the total cooking and preparation time.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--26", "ques": "Search for a high-protein vegetarian chili recipe on Allrecipes that has at least 50 reviews and a rating of 4 stars or higher. Provide the ingredient list, cooking time, and a brief description of the cooking steps.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--27", "ques": "Locate a chicken curry recipe on Allrecipes that has been reviewed more than 30 times and has a rating of at least 4 stars. Provide a summary of the recipe including ingredients, preparation time, and cooking instructions.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--28", "ques": "On Allrecipes, find a vegan brownie recipe that has at least 40 reviews and a rating of 4.5 or higher. Include the list of ingredients, total prep and cook time, and a brief overview of the preparation steps.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--29", "ques": "Search for a Mediterranean-style grilled fish recipe on Allrecipes that includes ingredients like olives, has at least a 4-star rating, and more than 25 reviews. Detail the ingredients, cooking method, and total time required for preparation and cooking.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--30", "ques": "Find a recipe for a vegan smoothie bowl on Allrecipes that includes bananas and leaves, has more than 20 reviews, and a rating of at least 4 stars. Provide a list of ingredients, preparation time, and a summary of the recipe steps.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--31", "ques": "Search for a seafood paella recipe on Allrecipes with a minimum of 4.5 stars rating and at least 50 reviews. The recipe should include shrimp and mussels. Provide the ingredients, total time, and an overview of the preparation steps.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--32", "ques": "Find a high-rated beef stew recipe on Allrecipes that requires a slow cooker and has at least 30 reviews. Detail the cooking time and the first five ingredients listed in the recipe.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--33", "ques": "Find a recipe for a low-carb breakfast on Allrecipes with at least 25 reviews. Show the Nutrition Facts and the total carbohydrate content per serving.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--34", "ques": "Locate a baked salmon recipe on Allrecipes that has at least 50 reviews and a rating of 4.5 stars or higher. Note the primary seasoning or herb used and the estimated cooking time.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--35", "ques": "Search for an Italian-style meatball recipe on Allrecipes that has more than 100 reviews. Detail the type of meat used and the overall cooking time required.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--36", "ques": "Locate a recipe for an American apple pie on Allrecipes with a rating of at least 4 stars and more than 50 reviews. Note the maximum temperature mentioned in the Directions.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--37", "ques": "Search for a Greek salad recipe on Allrecipes that has a prep time of under 25 minutes and more than 15 reviews. Include the primary cheese used and the type of dressing recommended.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--38", "ques": "Find a French ratatouille recipe on Allrecipes with a 4-star rating or higher and at least 15 reviews. Note the variety of vegetables included and the overall cooking time.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--39", "ques": "Locate a recipe for sushi rolls on Allrecipes with a minimum of 20 reviews. Show the Nutrition Facts and the main ingredients. Tell me how to store these rolls.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--40", "ques": "Browse the about us section of Allrecipes for a brief introduction to The Allrecipes Allstars.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--41", "ques": "List 3 recommended dinner recipes in the Allrecipes Dinners section.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--42", "ques": "Find a recipe for banana bread with more than 200 reviews and a rating of at least 4.0 stars on Allrecipes.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--43", "ques": "Find a recipe for a vegan pumpkin pie on Allrecipes with a minimum four-star rating and a total cook time exceeding 1 hour.", "web": "https://www.allrecipes.com/"} +{"web_name": "Allrecipes", "id": "Allrecipes--44", "ques": "List at least 6 holiday recipes sections mentioned in the Occasions section of Allrecipes.", "web": "https://www.allrecipes.com/"} +{"web_name": "Amazon", "id": "Amazon--0", "ques": "Search an Xbox Wireless controller with green color and rated above 4 stars.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--1", "ques": "Search for women's golf polos in m size, priced between 50 to 75 dollars, and save the lowest priced among results.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--2", "ques": "Find a gaming desktop with Windows 11 Home, and the disk size should be 1TB.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--3", "ques": "Find climbing gears and sort the results by price high to low. Answer the first 3 results after sorting.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--4", "ques": "Find the used Nintendo Switch Lite on Amazon then filter by 'Used - Good', tell me the cheapest one that is 'Used - Good'.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--5", "ques": "Find a Blue iPhone 12 Pro 128gb and add to cart.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--6", "ques": "Browse black strollers within $100 to $200 on Amazon. Then find one Among these black strollers with over 20,000 reviews and a rating greater than 4 star.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--7", "ques": "Browse the women's hiking boots on Amazon and filter the results to show only those that are waterproof and have a rating of at least 4 stars and size 6.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--8", "ques": "Find the cheapest Samsung-made Android tablet with screen between 10-10.9 inches on Amazon. Only answer the cheapest one.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--9", "ques": "Find a dog bed on Amazon that is washable and has a length of at least 30 inches.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--10", "ques": "Find the cost of a 2-year protection for PS4 on Amazon.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--11", "ques": "Find a stainless steel kitchen sink with double bowls on Amazon. Sort the results and find the cheapest one with FREE delivery.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--12", "ques": "Check reviews for a Ride On Car with 100+ reviews & 4+ stars rating on Amazon. Give me the top review about this Ride On Car.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--13", "ques": "Browse best selling black hoodies in mens size Big and Tall that is between $25 and $50 on Amazon.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--14", "ques": "Find the new surge protector on Amazon with 6 to 8 outlets under 25 dollars with customer reviews above 4+ stars.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--15", "ques": "Find a pair of mens running shoes in black, size 7, 4+ stars and under $50 and add them to my cart on Amazon.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--16", "ques": "Find the Return Policy for Mens Rhinestone Skull Graphic Shirt on Amazon. Color: Black, Size: XX-Large. If Free return is avaliable, tell me how to return this item.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--17", "ques": "Show me the list of baby products that are on sale and under 10 dollars on Amazon. Provide at least 2 on sale products", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--18", "ques": "Open Amazon's home page and tell me what the deal is that is going on at the moment, list the names of at least 2 items that are on offer and tell me what percent off they are.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--19", "ques": "Look for an English language book on roman empire history in the Amazon Kindle store. Sort by newests arrivals and look for a title that will be released within a month.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--20", "ques": "Search for a wireless ergonomic keyboard with backlighting and a rating of at least 4 stars. The price should be between $40 to $60. Save the product with the 500+ customer reviews.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--21", "ques": "Find a stainless steel, 12-cup programmable coffee maker on Amazon. The price range should be between $100 to $200. Report the one with the 4+ customer rating.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--22", "ques": "Search for a set of non-stick, oven-safe cookware on Amazon. The set should include at least 10 pieces and be priced under $150.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--23", "ques": "Look for a men's waterproof digital sports watch with a heart rate monitor on Amazon. It should be priced between $50 to $100.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--24", "ques": "Browse for a compact air fryer on Amazon with a capacity of 2 to 3 quarts. It should have a digital display, auto shutoff and be priced under $100.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--25", "ques": "Search for a queen-sized, hypoallergenic mattress topper on Amazon. It should have a memory foam material and be priced between $50 to $100.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--26", "ques": "Find a portable Bluetooth speaker on Amazon with a water-resistant design, under $50. It should have a minimum battery life of 10 hours.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--27", "ques": "Look for a USB-C hub on Amazon compatible with MacBook Pro, featuring at least 4 ports, including HDMI and SD card reader. The price should be under $50. Select the one after sorting by Best Sellers.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--28", "ques": "Search for a yoga mat on Amazon that is at least 6mm thick, non-slip, and eco-friendly. The price should be under $50.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--29", "ques": "Find a set of solar-powered garden lights on Amazon with a minimum pack of 10 lights. They should be LED and priced under $50.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--30", "ques": "Locate the highest-rated fiction book released in 2024 on Amazon, with a minimum of 50 customer reviews.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--31", "ques": "Find a compact digital camera on Amazon with a zoom capability of at least 10x, rated 4 stars or higher, and priced between $100 to $300.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--32", "ques": "Search for an electric kettle on Amazon with a capacity of at least 1.5 liters, made of stainless steel, and with a customer rating of 4 stars or above.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--33", "ques": "Search for a portable air conditioner on Amazon suitable for a room size of 300 sq ft, with energy efficiency rating, and compare the prices of the top three search results.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--34", "ques": "Find a beginner's acrylic paint set on Amazon, with at least 24 colors, suitable for canvas painting, and priced under $40.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--35", "ques": "Find a men's leather wallet on Amazon with RFID blocking, at least 6 card slots, and priced below $50. Check if it's available for FREE delivery.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--36", "ques": "Search for a children's science experiment kit on Amazon suitable for ages 8-13, with at least a 4-star rating and priced under $30.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--37", "ques": "Locate a queen-sized bedspread on Amazon with a floral pattern, and check if it's available in blue color.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--38", "ques": "Find a bird feeder on Amazon suitable for small birds, with an anti-squirrel mechanism, and check if it's available with free shipping.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--39", "ques": "Locate a travel guide book on Amazon for Japan, published in 2024, with at least 20 customer reviews.", "web": "https://www.amazon.com/"} +{"web_name": "Amazon", "id": "Amazon--40", "ques": "Locate a women's yoga mat in purple, with a thickness of at least 5mm, rated 4+ stars, and priced under $30 on Amazon. Check how many colors are available in total, and what is the return and delivery policy.", "web": "https://www.amazon.com/"} +{"web_name": "Apple", "id": "Apple--0", "ques": "Compare the prices of the latest models of MacBook Air available on Apple's website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--1", "ques": "Research the new features of the iOS 17 on Apple support and check its compatibility with the iPhone 12.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--2", "ques": "Compare the prices and chips for the iPhone 14 Pro and iPhone 15 Pro models directly from Apple's website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--3", "ques": "Find the latest model of the iPhone and compare the price and screen size between the pro and pro max.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--4", "ques": "How much does it cost to buy a Macbook pro, 16-inch, Apple M3 Max chip with 16-core CPU, 40-core GPU, 64GB unified memory, 1TB SSD.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--5", "ques": "Check the release date and price for the latest version of the iPhone.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--6", "ques": "Find AirPods on Apple and how many types are currently available.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--7", "ques": "When and where the Apple Vision Pro will be released.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--8", "ques": "Identify and list the specifications of the latest iPad model released by Apple, including its storage options, processor type, and display features.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--9", "ques": "Check the Apple Store for the availability of the latest iPhone model and schedule an in-store pickup at the nearest Apple Store for January 10, 2024.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--10", "ques": "Find information on the latest (as of today's date) MacBook model, including its key features such as processor type, memory size, and storage capacity.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--11", "ques": "Get information about the latest iPad model released by Apple, including its release date, base storage capacity, and starting price available on Apple's official website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--12", "ques": "What Apple Repair ways are mentioned on apple website, answer 2 of them.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--13", "ques": "How many colors does the latest MacBook Air come in?", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--14", "ques": "Identify the upgrade options available for the cheapest base model of the MacBook Pro 14-inch with M3 chip, and calculate the total price difference from the base model to the maximum upgrade (no Pre-Installed Software) offered by Apple.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--15", "ques": "On Apple's website, how many different types of keyboards are available when customizing your 14-inch MacBook Pro?", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--16", "ques": "Find on Apple website how many types of AirPods (3rd generation) are available and what is the price difference.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--17", "ques": "Search Apple for the accessory Smart Folio for iPad and check the closest pickup availability next to zip code 90038.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--18", "ques": "Check if there are trade-in offers for the latest model of iPhone.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--19", "ques": "On Apple's website, what is the slogan for the Mac and what is the slogan for the Macbook pro.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--20", "ques": "Check the price for an Apple iPhone 14 Plus with 256GB storage in Purple color.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--21", "ques": "Identify the available storage options for the latest iPad Pro on the Apple website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--22", "ques": "Find out the trade-in value for an iPhone 13 Pro Max in good condition on the Apple website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--23", "ques": "Determine the price difference between the latest series of Apple Watch and Apple Watch SE on the Apple website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--24", "ques": "Find out the starting price for the most recent model of the iMac on the Apple website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--25", "ques": "On the Apple website, look up the processor for the latest model of the Apple TV.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--26", "ques": "Find the maximum video recording resolution supported by the latest iPad mini on the Apple website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--27", "ques": "On Apple's website, check if the HomePod mini in store is available in multiple colors and list them.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--28", "ques": "On the Apple website, find out if the Mac Mini can be configured with a GPU larger than 16-core.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--29", "ques": "On Apple's website, check the estimated battery life of the latest MacBook Air during web browsing in Tech Specs.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--30", "ques": "Check the storage options and prices for the latest iPad Pro models on Apple's website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--31", "ques": "On Apple's website, what is the slogan for the latest Apple Watch Series.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--32", "ques": "Investigate the trade-in value for an iPhone 11 Pro Max on Apple's website.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--33", "ques": "Look for the color options available for the newest iMac.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--34", "ques": "Identify the size and weight for the Apple TV 4K and list the Siri Remote features introduced.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--35", "ques": "How many types of Apple Pencil are currently available on the Apple's website? Which one supports Wireless pairing and charging.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--36", "ques": "Browse Apple Music on the entertainment section of the Apple's website, and see which singers' names are included in the pictures on this page.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--37", "ques": "Compare the color options of iPhone 13 Pro, iPhone 14 Pro and iPhone 15 Pro.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--38", "ques": "Explore accessories for Apple Vision Pro, list at least three accessories.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--39", "ques": "Find solutions on Apple's website if you forgot your Apple ID password.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--40", "ques": "Find information on Apple website, and tell me the device weight of Apple Vision Pro and list 5 Built-in Apps it supports.", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--41", "ques": "How much does it cost to buy an ipad mini with 64GB storage and Wi-Fi + Cellular connectivity? (no engraving, no apple pencil, no smart folio, no apple trade-in).", "web": "https://www.apple.com/"} +{"web_name": "Apple", "id": "Apple--42", "ques": "Find updates for Apple Watch Series 7,8,9 on Apple's website.", "web": "https://www.apple.com/"} +{"web_name": "ArXiv", "id": "ArXiv--0", "ques": "Search for the latest preprints about 'quantum computing'.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--1", "ques": "Search for the latest research papers on quantum computing submitted to ArXiv within the last two days.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--2", "ques": "Look up the most recent papers related to 'cs.CL', select one and show its abstract.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--3", "ques": "Locate the most recent research paper about 'Algebraic Topology' under Mathematics published on ArXiv. Provide the title of the paper, the name of the authors, and the abstract.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--4", "ques": "Find the most recent research papers in Astrophysics of Galaxies. How many papers have been announced in the last day?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--5", "ques": "Search papers about \"quantum computing\" which has been submitted to the Quantum Physics category on ArXiv. How many results in total. What if search in all archives?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--6", "ques": "How many figures and tables are in the paper \"On the Sentence Embeddings from Pre-trained Language Models\"?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--7", "ques": "Find the most recent paper submitted on machine learning in the Computer Science category posted on ArXiv.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--8", "ques": "What is the latest news on ArXiv?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--9", "ques": "Find the latest research paper about neural networks published on ArXiv which has been submitted within the last week.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--10", "ques": "Visit ArXiv Help on how to withdraw an article if the submission is not yet announced.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--11", "ques": "For Non-English submissions, do I need to provide a multi-language abstract, if need, answer the separator between the multiple abstracts.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--12", "ques": "Find store in arXiv Help, tell me how many styles of arXiv Logo Shirt are available?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--13", "ques": "How many articles on ArXiv with 'SimCSE' in the title?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--14", "ques": "On ArXiv, how many articles have 'SimCSE' in the article and are originally announced in October 2023?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--15", "ques": "Searching Chinese Benchmark on ArXiv, how many papers announced in December 2023 mention being accepted for AAAI 2024?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--16", "ques": "Locate the latest research about gravitational waves that were uploaded to ArXiv this week and provide a brief summary of one article's main findings.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--17", "ques": "Find the paper 'GPT-4 Technical Report', when was v3 submitted?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--18", "ques": "Download the paper 'Dense Passage Retrieval for Open-Domain Question Answering'. How many formulas are in the article and which one is the loss function?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--19", "ques": "Which university maintains and manages ArXiv. Accessing the university's website from ArXiv, how many underegraduate students are currently at the university.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--20", "ques": "Find the latest paper on 'machine learning in the Statistics section of ArXiv and provide its abstract.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--21", "ques": "Search for papers on 'neural networks for image processing' in the Computer Science category on ArXiv and report how many were submitted in the last week.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--22", "ques": "Locate the ArXiv Help section and find instructions on how to subscribe to daily listing emails for new submissions in a specific category.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--23", "ques": "Determine how many articles with the keyword 'autonomous vehicles' were published in the 'Electrical Engineering and Systems Science' section of ArXiv yesterday.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--24", "ques": "Identify the most recent paper related to 'graph neural networks' on ArXiv and determine the affiliation of the first author.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--25", "ques": "Browse the ArXiv store and let me know how many different types of merchandise are available.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--26", "ques": "Search for papers related to 'climate change modeling' on ArXiv and find out how many have been published in the Earth and Planetary Astrophysics (astro-ph.EP) category in the last week.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--27", "ques": "On ArXiv, what categories does Economics include, and what are their abbreviations?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--28", "ques": "Search 'Poly encoder' by title on ArXiv and check whether the articles in the search results provide HTML access.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--29", "ques": "On ArXiv, search for papers with 'Neural Network Optimization' in the title published in 2023, and provide the number of such papers.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--30", "ques": "Look up the submission guidelines on ArXiv for submitting a paper and tell me the formats for figures.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--31", "ques": "Search ArXiv for papers with 'Graph Neural Networks' in the abstract that were submitted between Jan 1, 2024, and Jan 3, 2024, and determine how many of these papers have more than five authors.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--32", "ques": "Locate the latest paper on ArXiv within the 'Nonlinear Sciences - Chaotic Dynamics' category, summarize the abstract and note the submission date.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--33", "ques": "Query ArXiv for the latest research article in the category of Systems and Control under Computer Science. Summarize the main objective or hypothesis presented in the paper and provide the names of the authors.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--34", "ques": "Search for the most recent paper related to non-commutative geometry submitted by an author with the first name John. Provide the title and the abstract.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--35", "ques": "Retrieve the latest research paper in Quantum Physics from ArXiv and provide the title, author(s), and date of submission.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--36", "ques": "Search 'CVPR 2023' and 'CVPR2023' through journal ref on ArXiv to see how many results there are respectively.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--37", "ques": "Find the names of people in ArXiv's Leadership Team.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--38", "ques": "Find the ArXiv Blog on the ArXiv website and summarize the content of its latest article.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--39", "ques": "Search the title 'GPT-4 Technical Report' and access this paper through HTML format. Read the paper on this page and tell me what is 'one of the main goals of developing such models' mentioned in the Introduction.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--40", "ques": "How many articles are there on each of the three most recent announce days in the Solar and Stellar Astrophysics section of ArXiv. Choose one at random and answer its title and when the first version was uploaded?", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--41", "ques": "Find the button to share arxiv non-profit store and follow the QR code to share the shop. Then add arXiv Forever short sleeve (XL) to your cart.", "web": "https://arxiv.org/"} +{"web_name": "ArXiv", "id": "ArXiv--42", "ques": "Find an article published between 1 January 2000 and 1 January 2005 that requires Support Vector Machines in the title and its Journey ref is ACL Workshop.", "web": "https://arxiv.org/"} +{"web_name": "BBC News", "id": "BBC News--0", "ques": "Find a report on the BBC News website about recent developments in renewable energy technologies in the UK.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--1", "ques": "Read the latest health-related news article published on BBC News and summarize the key points discussed.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--2", "ques": "Read the latest article regarding the environmental impacts of deforestation published within the last two days.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--3", "ques": "Check the leaderboard for Golf's DP World Tour in the SPORT section, what was the name of the most recent tournament, and how many teams have a Total of -10 strokes.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--4", "ques": "Find the latest article regarding the economic implications of climate change in Europe as reported by BBC News and summarize the central points.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--5", "ques": "Find the article \"What is climate change? A really simple guide\" and use it to answer what human activities are causing climate change.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--6", "ques": "Find the top story from BBC News in the technology section for today.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--7", "ques": "Find a AI-related story under Technology of Business. What is in the first picture in the story?", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--8", "ques": "Get a brief overview of the economic implications of the UK's latest trade deal posted on BBC News and the date when the article was published.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--9", "ques": "Find out which musician made the headlines in Music News.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--10", "ques": "Identify the main headlines covering the UK's plan to tackle climate change on BBC News.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--11", "ques": "Find out how many teams are in the Scottish Premiership of the Football Tournament and when did the Hibernian team's most recent match start?", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--12", "ques": "Find a picture in the travel section that contains food, tell me what the food is called and what region it comes from.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--13", "ques": "Search for recent news related to Trump and summarize the main points.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--14", "ques": "Find a news article on BBC News about the impact of the recent tech industry layoffs on the global economy. Summarize the key points and the name of the author, and provide the date of publication.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--15", "ques": "What does the current headline in Natural Wonders tell about.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--16", "ques": "Identify the most recent development or update in Brexit negotiations as reported on BBC News and report the key points and any stated impacts on European economies.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--17", "ques": "How many War related sections are currently in BBC News.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--18", "ques": "Visit BBC News Audio, What are the best PodCasts for 2023? List 2 of them.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--19", "ques": "Visit the Athletics calendar for the date of the next earliest game.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--20", "ques": "Find the latest article in the Green Living section on BBC News and provide a summary of its main points.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--21", "ques": "Identify the top headline in the World News section on BBC News and describe the region it is related to.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--22", "ques": "Determine the current top business story on BBC News and give a brief overview of its economic implications.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--23", "ques": "Identify the latest health-related news on BBC News and summarize the main findings or recommendations.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--24", "ques": "Search the latest article about space exploration on BBC News and summarize its key points.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--25", "ques": "Find the most recent sports analysis article on BBC News related to the English Premier League and summarize its key insights.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--26", "ques": "Locate the latest report on BBC News about the impact of recent natural disasters in Asia and summarize the key points and areas affected.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--27", "ques": "Find the most recent article on BBC News about archaeological discoveries and summarize the main findings and their significance.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--28", "ques": "Find the Market Data section on BBC News and tell me which company the data comes from.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--29", "ques": "Visit BBC News Audio and find out which podcast episode is currently featured as the \"New Releases\".", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--30", "ques": "In the Culture section, identify the latest film release reviewed and provide a brief summary of the review.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--31", "ques": "Check the Sports section for the result of the most recent Manchester United football match.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--32", "ques": "Find the artificial intelligence section, what is the top headline at this time, and which companies are involved?", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--33", "ques": "In the World News section, find the latest war situations of Middle East and provide a brief summary.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--34", "ques": "Find The SpeciaList section in Travel and browse the page to see which cities are mentioned.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--35", "ques": "In the Asia section, browse and identify the most recent report about technological advancements and summarize its content.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--36", "ques": "Look up recent articles in the Africa news section in World, summarize what topics most of these news are about", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--37", "ques": "Identify the latest book review featured in the Culture section and provide the title and author of the book.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--38", "ques": "Find news related to the storm in Weather section and indicate where and when the severe weather occurred.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--39", "ques": "Check the Horse Racing results in Sport section, browse all the games that took place yesterday and see which one had the highest number of runners.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--40", "ques": "Read and summarise a recent story on BBC News about people being injured or killed in wars.", "web": "https://www.bbc.com/news/"} +{"web_name": "BBC News", "id": "BBC News--41", "ques": "Find Golf in BBC News, check the Leaderboard at this point in Women's Majors and count which country has the most players in the top 20? Which player has the best score amongst the Australian players and in what place.", "web": "https://www.bbc.com/news/"} +{"web_name": "Booking", "id": "Booking--0", "ques": "Find a Mexico hotel with deals for December 25-26.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--1", "ques": "Find the cheapest available hotel room for a three night stay from 1st Jan in Jakarta. The room is for 2 adults, just answer the cheapest hotel room and the price.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--2", "ques": "Find a hotel in Ohio From December 20th to December 23th for 3 adults and 2 rooms.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--3", "ques": "Find a hotel with 4 star and above rating in Los Angeles for 3 days from Dec 18th.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--4", "ques": "Search for the cheapest Hotel near Kashi Vishwanath Temple that offer breakfast from Dec 25th - Dec 26th.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--5", "ques": "Search a hotel with free WiFi and air conditioning in Bali from Jan 1 to Jan 4, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--6", "ques": "Book one room which provides breakfast, and airport shuttle from Jan 22 to 25 in Los Angeles.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--7", "ques": "Find a hotel room on January 3-6 that is closest to National University of Singapore and costs less than $500", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--8", "ques": "Get the hotel with highest review score and free cancelation in Chennai for 20/12/2023 - 21/12/2023.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--9", "ques": "Find hotels for 2 adults in London with a price less than 250 dollars for four days starting from December 25. You must browse the page and offer at least 3 options.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--10", "ques": "Find a well-reviewed hotel in Paris with available bookings suitable for a couple (2 adults) on Valentine's Day week, February 14-21, 2024, that offers free cancellation options.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--11", "ques": "Reserve a hotel in downtown Chicago with a rating of 9 or higher for a stay from March 20-27, 2024, which offers free cancellation and includes a fitness center.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--12", "ques": "Find a hotel in Paris with a customer review score of 8 or higher, free Wi-Fi, and available for a 5-night stay starting on January 5th, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--13", "ques": "Find and book a hotel in Paris with suitable accommodations for a family of four (two adults and two children) offering free cancellation for the dates of February 14-21, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--14", "ques": "Book a highly-rated hotel with a swimming pool and free WiFi near the Louvre Museum in Paris for the weekend of March 3-5, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--15", "ques": "Find the highest-rated luxury hotel in Rome available for booking from January 10, 2024, to January 20, 2024, for 2 adults. Include the cost, amenities offered, and customer rating.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--16", "ques": "Look for a hotel in Paris with a user rating of 9 or higher and available for a 5-night stay starting January 15, 2024. The hotel should also offer free Wi-Fi and breakfast included in the price. Provide the name, location, and price per night.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--17", "ques": "Find a hotel in Paris with a fitness center and a rating of 8 or higher available for a 5-night stay starting from February 14, 2024, and sort the results by best reviewed.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--18", "ques": "Search a hotel in London with a user rating of 8 or higher for a stay between February 14th, 2024, and February 21st, 2024, suitable for a couple. Provide the name and a short description of the hotel.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--19", "ques": "Look for a hotel with customer ratings above an 8.0 in Paris, France for a weekend stay from March 18, 2024, to March 20, 2024, and list top three suggestions based on user reviews.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--20", "ques": "Locate a hotel in Rome with a good rating (7 or above) that offers free cancellation and breakfast included, for a three-night stay from February 28 to March 2, 2024, for two adults.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--21", "ques": "Find a hotel in Sydney with a rating of 8 or higher, providing free Wi-Fi and parking, available for a four-night stay starting on March 10, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--22", "ques": "Search for a hotel in Amsterdam with a customer review score of 9 or higher, offering bicycle rentals, for a week-long stay from March 15 to March 22, 2024, for two adults.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--23", "ques": "Identify a hotel in Tokyo with a spa and wellness center, rated 9 or above, with availability for a five-night stay starting on February 20, 2024. Check if free cancellation is offered.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--24", "ques": "Find a hotel in Barcelona for a stay from February 25-28, 2024. Please sort the results by distance from the beach and make sure they offer free Wi-Fi and breakfast.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--25", "ques": "Search for a hotel in Lisbon with airport shuttle, rated 8.5 or above, available for a six-night stay from March 1 to March 7, 2024, for two adults, breakfast included.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--26", "ques": "Check Booking.com for a 3-star hotel or higher in Paris with a guest rating above 8.0 and available parking for dates February 20-23, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--27", "ques": "Locate a hotel in Melbourne offering free parking and free WiFi, for a stay from February 28 to March 4, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--28", "ques": "Find a hotel in Dubai with a swimming pool, for a week-long stay from February 22 to February 29, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--29", "ques": "Search for a hotel in Toronto with a fitness center and a rating of 8+, available for a two-night stay from March 5 to March 7, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--30", "ques": "Search for hotels in London from March 20 to March 23, 2024, on Booking. How many hotels are left after applying the Breakfast included and Fitness center filters?", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--31", "ques": "Search for hotels in Rio de Janeiro from March 1-7, 2024, check the Brands filter to see which brand has the most hotels and which brand has the fewest.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--32", "ques": "Look for hotels in Sydney from February 24 to February 27, 2024, on Booking. Once the Swimming Pool and Airport Shuttle filters are applied, what is the total number of hotels available?", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--33", "ques": "Find the Customer Service on the Booking website, browse the questions about cancellation, and tell me 'how do I know whether my booking has been cancelled'.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--34", "ques": "Search for a hotel in Berlin available for a three-night stay from March 15 to March 18, 2024, for one adult. Tell me the price in USD and CNY for the three-night stay.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--35", "ques": "Browse the booking website to get inspiration for your next trip, and summarize at least three places mentioned in one of the travel articles.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--36", "ques": "Search for a budget hotel in Rome under $100 per night for one adult from March 20 to March 23, 2024. Sort the results by price, identify if any of top three results offer breakfast.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--37", "ques": "Search for a resort (not hotel) in Bali, detailing the available dates between March 20, 2024, and March 25, 2024, and checking any provided tour or cultural experiences.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--38", "ques": "Look up Vienna hotel options with availability for a 4-night stay from February 28 to March 4, 2024, with amenities that include a Parking, breakfast included, and a rating of 8+ on Booking.com.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--39", "ques": "Find a pet-friendly hotel with parking available in downtown Toronto for the stay of February 24-26, 2024.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--40", "ques": "I need to choose a hotel in Shenzhen, please select date (6 March to 8 March 2024) and click the search button. How much it costs when convert the price to Chinese Yuan on the page.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--41", "ques": "Browse Booking's homepage to find out which company it belongs to.", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--42", "ques": "Search for a hotel in Hokkaido for the period March 1 to March 7, 2024, with a rating of 9+, check out its user reviews, which categories are greater than 9 and which are less than 9?", "web": "https://www.booking.com/"} +{"web_name": "Booking", "id": "Booking--43", "ques": "Search for properties in Los Angeles, browse the results page to see what filters are available, list some of them.", "web": "https://www.booking.com/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--0", "ques": "Look up the pronunciation and definition of the word \"sustainability\" on the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--1", "ques": "Find the pronunciation, definition, and a sample sentence for the word 'serendipity'.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--2", "ques": "Look up the pronunciation, definition, and example sentence for the word \"ubiquitous\" in UK and US English.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--3", "ques": "Look up the definition, pronunciation, and examples of the word \"zeitgeist.\"", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--4", "ques": "Look for the British English pronunciation of the word \"innovate\" and write down the International Phonetic Alphabet (IPA) notation, then find one example sentence provided in the Cambridge Dictionary that uses this word.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--5", "ques": "Learn the UK and US pronunciation of the word \"procrastination\", and find one example sentence that reflects its use in context.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--6", "ques": "Search for the word \"sustainability\" on the Cambridge Dictionary, what is the translation of sustainability into Chinese and French in the dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--7", "ques": "Look up the meaning, pronunciation, and an example sentence of the word \"gestalt\" using the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--8", "ques": "Find three different meanings of \"dog\" in Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--9", "ques": "Look up the British pronunciation of the word \"euphoria\" and find an example sentence using that word on the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--10", "ques": "Look up the definition and pronunciation of the word \"impeccable\" and also find an example sentence using that word.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--11", "ques": "Look up the pronunciation and definition of the word \"ameliorate,\" and provide an example sentence using the word.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--12", "ques": "Find the pronunciation, definition, and a sample sentence for the word \"resilience\" in the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--13", "ques": "Find one word, one phase and one idiom related to euphoria in Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--14", "ques": "Use the Cambridge Dictionary to find the pronunciation, definition, and one example sentence for the word \"concatenate\".", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--15", "ques": "Find the pronunciation and a sample sentence for the word \"pandemic.\"", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--16", "ques": "Look up the definition of \"cryptocurrency\" on Cambridge Dictionary, provide the pronunciation, and use it in two example sentences that illustrate different contexts.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--17", "ques": "How many meanings of \"unblemished\" are given in Cambridge Dictionary? Please browse the page and give the number directly.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--18", "ques": "Search for \"to behave well\" in Cambridge Dictionary's Thesaurus and see which synonyms the dictionary gives.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--19", "ques": "Try a Cambridge Dictionary translation and tell me which company provided the translation.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--20", "ques": "Look up the definition, pronunciation (both UK and US), and find one example sentence for the word \"altruism\" in the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--21", "ques": "Search for the word \"ephemeral\" on Cambridge Dictionary and find its translation into Spanish.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--22", "ques": "Use the Cambridge Dictionary to find the definition, UK pronunciation, and an example sentence for the word \"quintessential.\"", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--23", "ques": "Find the US English pronunciation of the word \"meticulous\" using the Cambridge Dictionary and note the International Phonetic Alphabet (IPA) notation, then find one example sentence provided in the dictionary using this word.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--24", "ques": "Look up the definition and both UK and US pronunciation of the word \"reverie,\" and provide an example sentence using the word from Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--25", "ques": "Find two different meanings of the word \"harmony\" in the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--26", "ques": "Search for the word \"nostalgia\" in the Cambridge Dictionary and report the translation of this word into Chinese.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--27", "ques": "Look up the meaning, pronunciation, and an example sentence of the word \"solitude\" using the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--28", "ques": "Search for \"feel giddy\" in Cambridge Dictionary's Thesaurus and list the synonyms the dictionary provides.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--29", "ques": "Go to the Plus section of Cambridge Dictionary, find Image quizzes and do an easy quiz about Animals and tell me your final score.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--30", "ques": "Find the grammar for present perfect simple uses in English, including examples of affirmative, negative, and interrogative sentences, on the Cambridge Dictionary website.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--31", "ques": "Look up the use of modal verbs in grammar section for expressing possibility (e.g., 'might', 'could', 'may') and find examples of their usage in sentences on the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--32", "ques": "Search for the differences between \"fewer\" and \"less\" in grammar section, and provide examples illustrating their correct usage from the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--33", "ques": "Find explanations and examples of the passive voice in Grammar on the Cambridge Dictionary website.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--34", "ques": "Use the Cambridge Dictionary to understand the rules for forming and using comparative and superlative adjectives in English Grammar, including example sentences.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--35", "ques": "Find the most common prepositions that consist of groups of words on the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--36", "ques": "Search for guidelines on using indirect speech in English, with examples of how to change direct speech to indirect speech, on the Cambridge Dictionary.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--37", "ques": "Use Cambridge Dictionary to understand the use of articles ('a', 'an', 'the') in English Grammar, including examples of usage with both countable and uncountable nouns.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--38", "ques": "Go to the Plus section of Cambridge Dictionary, finish a recommended Grammar quiz without login and tell me your final score.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--39", "ques": "Try the Word Scramble game in the Plus section, Can you beat the clock by unscrambling the letters to spell the word? (Just try the first example.)", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--40", "ques": "Look up the definition, pronunciation in UK English, and at least one example using the word 'mitigate'.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--41", "ques": "Find and browse Cambridge Dictionary Shop section, listing 3 items.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Cambridge Dictionary", "id": "Cambridge Dictionary--42", "ques": "Convert the Cambridge Dictionary homepage from English (UK) to Deutsch.", "web": "https://dictionary.cambridge.org/"} +{"web_name": "Coursera", "id": "Coursera--0", "ques": "Find a beginner-level online course about '3d printing' which lasts 1-3 months, and is provided by a renowned university.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--1", "ques": "Search for a beginner-level online course about Python programming, suitable for someone who has no programming experience on Coursera.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--2", "ques": "Find a Beginner's Spanish Specialization on Coursera and show all the courses in this Specialization.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--3", "ques": "Identify a new course or Specialization on Coursera related to Python Data Science, sort the courses by newest, what the first course is and which institution offers it.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--4", "ques": "Identify a course or Specialization on Coursera that helps business process management with with a rating 4.7.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--5", "ques": "Identify a Specialization on Coursera that teaches C++ programming for beginners, provide the name and what the learning outcomes are.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--6", "ques": "Identify a course on Coursera related to 'Artificial Intelligence for Healthcare' and note the course duration along with the number of quizzes in Assessments.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--7", "ques": "Find a course on Coursera that teaches Reinforcement Learning for Intermediate with a rating of at least 4.5. Provide the name of the course, the institution offering it, and the number of reviews it has received.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--8", "ques": "Find a free course related to 'R for Data Science' available on Coursera. Scroll to find a course with the Free tag. What language the course is taught in?", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--9", "ques": "Identify a Coursera course on artificial intelligence ethics that has a duration of less than 20 hours to complete and has been rated 4+ stars by participants.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--10", "ques": "Locate an introductory course related to artificial intelligence on Coursera, ensuring it's suitable for beginners and contains at least one module discussing Ethical Considerations.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--11", "ques": "Search for a Specialization on Coursera about project management that is produced by a university, show a testimonial for this Specialization.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--12", "ques": "Look for a Coursera course (not Specialization) that teaches Java programming basics.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--13", "ques": "Look for a Specialization on Coursera that teaches Python programming, and identify the skills you will learn by taking this Specialization.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--14", "ques": "Find a course on Coursera related to Introductory Project Management that includes modules on Agile methodology.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--15", "ques": "Find a course on Coursera named 'Introduction to Mathematical Thinking' offered by Stanford, what is the percentage (rounded) of 5 star ratings in reviews and which level has the least percentage?.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--16", "ques": "Identify a course on Coursera named 'Introduction to Finance: The Basics', who is the course instructor and what other courses does he/she teach.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--17", "ques": "How many results are there for a search on Coursera for Machine Learning, then filtered by Credit Eligible and 1-4 Years duration?", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--18", "ques": "Identify a Coursera course that teaches JavaScript, which is beginner-friendly and includes a certificate upon completion.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--19", "ques": "Identify a course on Coursera that provides an introduction to Psychology, list the instructor's name, the institution offering it, and how many hours it will approximately take to complete.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--20", "ques": "Find an Intermediate-level online course on Coursera about 'Blockchain Technology' which lasts between 1 to 4 weeks, and is provided by a well-known institution. Also, note the course's main goals and the instructor's name.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--21", "ques": "Search for an online course on Coursera about 'Digital Marketing', suitable for beginner-level learners. Specify the course duration, the main learning outcomes, and the institution offering the course.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--22", "ques": "Identify a Specialization on Coursera that focuses on 'Human Resource', list the courses included in this Specialization, and the institution offering it.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--23", "ques": "Find a course on Coursera about 'Artificial Intelligence Ethics', which has a duration of less than 5 weeks and has been rated 4.5 stars or higher. Provide the course name and the instructor's name.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--24", "ques": "Locate an online course on Coursera related to 'Sustainability' that belongs to Physical Science and Engineering subject. The course should include a module on Measuring Sustainability. Note the course duration and the offering institution.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--25", "ques": "Find a course on Coursera about 'Relativity' for beginners. List the course's main topics and the estimated time (in hours) required to complete it.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--26", "ques": "Identify a Specialization on Coursera that offers an overview of 'Renewable Energy'. The Specialization should be beginner-level and include a course on Renewable Energy Futures. Note the instructor's name and the number of weeks required to complete the course if I spend 5 hours a week.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--27", "ques": "Search for a Specialization on Coursera about 'Data Visualization' that includes a project. Provide the name of the Specialization, the institution offering it, and the skills that will be developed by completing it.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--28", "ques": "Locate a Coursera Guided project related to 'Astrophysics' suitable for advanced learners. Mention the course duration, the institution offering it, and the main subjects covered in the course.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--29", "ques": "Browse the Coursera website and find the price required for one year of Coursera Plus. How much is the discount? Then list 3 companies that work with Coursera.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--30", "ques": "Locate the course 'Modern Art & Ideas' on Coursera offered by The Museum of Modern Art. Find out the percentage (rounded) of 3-star ratings in the reviews and note which star level has the lowest percentage.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--31", "ques": "Search for the course 'Exploring Quantum Physics' on Coursera, offered by the University of Maryland, College Park. Identify the percentage (rounded) of 5-star ratings in the reviews.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--32", "ques": "Search for 'Data Analysis' courses on Coursera. Apply filters to find courses that are 'Beginner Level' and have a duration ranging from 1 to 3 months. Determine the total count of courses that match these specifications.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--33", "ques": "Find a beginner level Coursera course related to \"Internet of Things (IoT)\" with a high rating. Provide the course name, instructor's name, and a brief summary of the skills that will be taught.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--34", "ques": "Find the course on Coursera named 'Essentials of Global Health'. Determine the instructor of this course and summarize his bio, note if there are any additional courses he offers on Coursera.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--35", "ques": "Find a Coursera course on Sustainable Agriculture practices, and detail the course's objectives and the background of the lead instructor.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--36", "ques": "Browse Coursera, which universities offer Master of Advanced Study in Engineering degrees? Tell me what is the latest application deadline for this degree?", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--37", "ques": "Browse the Coursera homepage and list at least three free courses.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--38", "ques": "Browse Coursera, which universities and companies from Australia are partners of Coursera? List all of them.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--39", "ques": "Find the Space Safety course offered by TUM on Coursera. How many videos are there in module 2? What is the name of each video?", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--40", "ques": "Browse Coursera for Business and Coursera for Teams and summarise some of their advantages.", "web": "https://www.coursera.org/"} +{"web_name": "Coursera", "id": "Coursera--41", "ques": "Browse online degrees section on Coursera and list 3 Bachelor's degree programmes.", "web": "https://www.coursera.org/"} +{"web_name": "ESPN", "id": "ESPN--0", "ques": "Look up the current standings for the NBA Eastern Conference on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--1", "ques": "Check the latest articles on ESPN for updates on any trades that occurred in the NBA within the past 2 days.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--2", "ques": "Show the scores and main highlight of the Milwaukee Bucks game that took place within the last 2 days on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--3", "ques": "Retrieve the final score from the most recent NBA game broadcast on ESPN, including the playing teams' names and the date of the match.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--4", "ques": "Check ESPN for the final scores of NBA games that were played yesterday.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--5", "ques": "Identify the top scorer in the NBA from the latest completed game and note down the points scored, the team they play for, and their position on the team.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--6", "ques": "Find the result of the latest basketball game between the Los Angeles Lakers and the Boston Celtics, including the final score and top scorer from the match.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--7", "ques": "Retrieve the final score and a brief summary of the latest NBA game played by the Los Angeles Lakers as reported on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--8", "ques": "Find information on ESPN about the top three scoring leaders in the NBA as of the last day of the regular season, and note which teams they play for.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--9", "ques": "Search on ESPN for how many teams have Los Angeles in their name and how many of them are NBA.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--10", "ques": "Check ESPN for the score and a brief recap of the latest college football championship game.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--11", "ques": "How many NBA teams are there and list all the teams with 'New' in their name.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--12", "ques": "The first three Top Headlines in the current ESPN home page correspond to which sports leagues?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--13", "ques": "Identify today's top headline in the Basketball section of ESPN, and summarize the main points of that article.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--14", "ques": "Find the latest news about NBA trades or player movements on ESPN and report the most recent trade deal OR player acquisition.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--15", "ques": "Check the scores of the NBA games played on December 25, 2023.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--16", "ques": "Check the schedule for the NBA game on December 25, 2023, and provide the teams that are playing and their current standings in their respective conferences.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--17", "ques": "Check out the NBA Basketball Power Index 2023-24 to see which teams are in first place and which are in last place.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--18", "ques": "How many sports leagues can you choose from on the ESPN home page?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--19", "ques": "Who has the highest salary in Boston Celtics Roster 2023-24?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--20", "ques": "Look up the current leaders in rebounds and assists in the NBA Western Conference on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--21", "ques": "Show the scores and main highlight of the Denver Nuggets game that occurred within the last 3 days on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--22", "ques": "Find the latest Team transactions in the NBA within the past week.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--23", "ques": "Find the result of the latest basketball game between the Miami Heat and the New York Knicks, including the final score and top rebounder from the match.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--24", "ques": "Find the final score from the most recent NFL game broadcast on ESPN, including the teams' names and the date of the match.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--25", "ques": "Identify the player with the most assists in the latest NBA game and show me the assists, the team they play for, and their position.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--26", "ques": "Find information on ESPN NBA schedule. Tell me yesterday's matchups in which the loser high was higher than the winner high.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--27", "ques": "Search on ESPN for how many teams have 'Golden' in their name and how many of them are in the NHL.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--28", "ques": "How many MLB teams are there and list all the teams with 'City' in their name.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--29", "ques": "Identify today's top headline in the Soccer section of ESPN, and summarize the main points of that article.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--30", "ques": "Check out the NHL Standings 2023-24 on ESPN to see which teams are at the top and which are at the bottom in Eastern and Western Conference. What about the situation in Division.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--31", "ques": "Who has the heaviest weight among infielders in the New York Yankees Roster 2023-24?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--32", "ques": "Review yesterday's NHL game results on ESPN, focusing on teams' performance.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--33", "ques": "Locate the latest ESPN articles discussing potential MVP candidates in the NFL for 2023 season.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--34", "ques": "Visit ESPN to view the Philadelphia 76ers' latest injuries.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--35", "ques": "Browse ESPN to find out when the next game of the Los Angeles Lakers will start. Then navigate to the ticket purchasing website from ESPN, what is the cheapest ticket available.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--36", "ques": "Search for Lionel Messi's last 5 games, which teams has he played for, and what are the results?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--37", "ques": "Check out LeBron James' Stats to see how many games he has played in his career so far.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--38", "ques": "Check Los Angeles Lakers Stats 2023-24, calculate Anthony Davis' games played (GP) percentage, tell me if there are other players with the same games played percentage as Anthony Davis.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--39", "ques": "Check the New York Jets Depth Chart in the NFL section of ESPN and identify the players listed as injured in the 2ND position.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--40", "ques": "Browse the ESPN+ page from ESPN for a brief summary of what ESPN+ Tools is used for.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--41", "ques": "Find out which four teams the NFC North contains in the NFL on ESPN.", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--42", "ques": "Check out NCAAM standings on ESPN, what are the teams with equal wins and losses in the America East Conference currently?", "web": "https://www.espn.com/"} +{"web_name": "ESPN", "id": "ESPN--43", "ques": "Check out NCAAW recruiting on ESPN, what colleges are the top three players from?", "web": "https://www.espn.com/"} +{"web_name": "GitHub", "id": "GitHub--0", "ques": "Search for an open-source project related to 'climate change data visualization' on GitHub and report the project with the most stars.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--1", "ques": "Search for an open-source repository for machine learning in Python, specifically focused on decision trees, updated within the last 2 days.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--2", "ques": "Look for the trending Python repositories on GitHub with most stars.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--3", "ques": "Find out how much more package storage the Enterprise version has over Team in GitHub Pricing.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--4", "ques": "Find a popular JavaScript repository created in the last 30 days on GitHub with a Readme file.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--5", "ques": "Find a Python repository on GitHub that has been updated in the past 2 days and has at least 500 stars.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--6", "ques": "Search for an open-source project related to 'cryptocurrency wallet' updated in the past 30 days and provide the top three contributors.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--7", "ques": "Find the official GitHub repository for ALBERT and show me what files the repo changed in the most recent commit.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--8", "ques": "Look up the latest stable release version of Vuex and find out when it was published.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--9", "ques": "Locate a repository on GitHub that was created in the last week and has 50 or more stars. Provide brief details about the project's purpose and its programming language.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--10", "ques": "If I start using Copilot Individual, how much US dollars will it cost per year and what features does it have?", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--11", "ques": "Find a newly created open-source project on GitHub related to 'climate change' that has been initiated in January 2023; check the main programming language used and the project's description.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--12", "ques": "Retrieve the latest release from the 'electron/electron' repository on GitHub and note down the release version number and date.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--13", "ques": "Identify the latest top-trending open-source project in the category of 'Machine Learning' on GitHub, and check the number of stars it has received.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--14", "ques": "Locate the repository for the open-source project \"vscode\" and identify the top three contributors.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--15", "ques": "Locate a repository on GitHub related to 'quantum computing' that has been updated within the last week and has at least 50 stars. Provide a brief description of the project.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--16", "ques": "Find the GitHub Skill section and how many courses are under the 'First day on GitHub' heading.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--17", "ques": "Locate a C++ project on GitHub that has been recently updated in the last week and has at least 500 stars, then describe its main purpose.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--18", "ques": "Identify and report the most popular (in terms of stars) open-source image processing tool on GitHub.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--19", "ques": "Look up the most recently updated Python repository on GitHub that is tagged with 'web scraping' and has over 100 stars.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--20", "ques": "Open GitHub Copilot's FAQs to find the official answer to when Copilot chat can be used on mobile.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--21", "ques": "Find the Security topic in GitHub Resources and answer the role of GitHub Advanced Security.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--22", "ques": "Find an open-source repository on GitHub focused on natural language processing in Ruby, updated within the last week.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--23", "ques": "Find the wiki page of ohmyzsh on GitHub and tell me how to change the theme of zsh to agnoster.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--24", "ques": "Locate the GitHub repository for the open-source project \"angular\" and identify the last three issues closed.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--25", "ques": "Search for a 'virtual reality' related repository on GitHub updated in the last 10 days with at least 200 stars and summarize its main objective.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--26", "ques": "Find the Resolve merge conflicts course in GitHub Skills and what actions learners will perform in this course.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--27", "ques": "Find a Ruby repository on GitHub that has been updated in the past 3 days and has at least 1000 stars.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--28", "ques": "Identify the most starred JavaScript repositories on GitHub that were created after 2023-12-29.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--29", "ques": "Compare the maximum number of private repositories allowed in the Free and Pro plans in GitHub Pricing.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--30", "ques": "Search for an open-source project related to 'blockchain technology' on GitHub updated in the past 15 days and list the top five contributors.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--31", "ques": "Find the official GitHub repository for TensorFlow and list the files changed in the last commit. Tell me the name of changed files, total additions and total deletion.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--32", "ques": "Discover the latest C# repository on GitHub related to 'game development' and having over 150 stars, and describe its main features.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--33", "ques": "Find Customer Stories on the GitHub page and list the 2 stories that appear on the web page.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--34", "ques": "Search for an open-source project on GitHub related to 'Protein prediction' and identify the project with the highest number of forks.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--35", "ques": "Check the latest release version of React and the date it was published on GitHub.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--36", "ques": "Identify a new open-source project on GitHub related to 'AI agriculture' that created in 2022, and note its main programming language and description.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--37", "ques": "List the 3 features mentioned in GitHub's Copilot product page.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--38", "ques": "Identify and report the most popular (by stars) open-source repo related to cybersecurity on GitHub.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--39", "ques": "Browse the GitHub Trending and find out which developer is currently ranked first this month and the corresponding repository.", "web": "https://github.com/"} +{"web_name": "GitHub", "id": "GitHub--40", "ques": "Select Sign up on the GitHub homepage to see if email 'test123@gmail.com' already exists.", "web": "https://github.com/"} +{"web_name": "Google Flights", "id": "Google Flights--0", "ques": "Book a journey with return option on same day from Edinburg to Manchester on December 28th and show me the lowest price option available.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--1", "ques": "Show me the list of one-way flights today (February 17, 2024) from Chicago to Paris.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--2", "ques": "Find the lowest fare from all eligible one-way flights for 1 adult from JFK to Heathrow on Jan. 22.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--3", "ques": "Search for the one-way flight available from Calgary to New York on Jan. 1st with the lowest carbon dioxide emissions.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--4", "ques": "Search for one-way flights from New York to London on Dec. 26th and filter the results to show only non-stop flights.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--5", "ques": "Find flights from Chicago to London on 20 December and return on 23 December.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--6", "ques": "Search for a flight on December 19 and return on December 26 from Tel Aviv to Venice and Select First Class.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--7", "ques": "Find a round trip from Phoenix to Miami (Dec. 25th - Dec. 28th), show the First Class plane tickets for me that do not exceed $1320..", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--8", "ques": "Search a one-way filght from Dublin To Athens Greece for 1 Adult that leaves on December 30 and analyse the price graph for the next 2 months.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--9", "ques": "Find a one way economy flight from Pune to New York in Jan. 15th and show me how long it will take for flight transfer.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--10", "ques": "Locate the cheapest round-trip flights from New York to Tokyo leaving on January 25, 2024, and returning on February 15, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--11", "ques": "Compare the prices for round-trip flights from New York to Tokyo for a departure on February 10, 2024, and a return on February 24, 2024, and select the option with the least number of stops.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--12", "ques": "Find the best-priced round-trip flight from New York to London leaving on December 25, 2023, and returning on January 5, 2024, with one stop or fewer.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--13", "ques": "Find the cheapest round-trip flight option from New York City to Tokyo for a departure on January 10, 2024, and a return on January 24, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--14", "ques": "Compare flight options and find the lowest round trip fare from New York to London departing on January 10, 2024, and returning on January 17, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--15", "ques": "Compare the prices and total duration of non-stop flights from New York to Tokyo Narita Airport departing on February 12th, 2024, and returning on February 26th, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--16", "ques": "Find the cheapest one-way flight from New York to Tokyo departing on January 15, 2024, and provide the airline and total flight duration.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--17", "ques": "Find the cheapest round-trip flight from New York to Paris leaving on December 27, 2023, and returning on January 10, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--18", "ques": "Compare flight options from New York to Tokyo for a round trip leaving on January 25, 2024, and returning on February 15, 2024, for one adult. Prioritize the comparisons by the shortest travel time.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--19", "ques": "Find the cheapest one-way flight from London to Paris, departing on January 25, 2024. Include the airline, total travel time, and layovers for the chosen flight.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--20", "ques": "Book a round-trip flight from San Francisco to Berlin, departing on March 5, 2024, and returning on March 12, 2024, and find the option with the shortest total travel time.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--21", "ques": "Locate the lowest-priced one-way flight from Tokyo to Sydney for an adult, departing on February 25, 2024, and include the flight duration and number of layovers.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--22", "ques": "Find a round-trip flight from Rio de Janeiro to Los Angeles, leaving on March 15, 2024, and returning on March 22, 2024, and select the option with the least carbon dioxide emissions.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--23", "ques": "Search for a one-way flight from Mumbai to Vancouver on February 28, 2024, filtering the results to show only 1-stop flights.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--24", "ques": "Compare prices for economy class round-trip flights from Dubai to Rome, departing on March 1, 2024, and returning on March 8, 2024, and select the option with the fewest stops.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--25", "ques": "Find a one-way business class flight from Buenos Aires to Amsterdam on March 10, 2024, and provide the details of the flight with the shortest duration.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--26", "ques": "Search for the cheapest round-trip flights from Bangkok to Madrid, leaving on February 26, 2024, and returning on February 28, 2024, and provide options under $1000.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--27", "ques": "Locate a one-way flight from Johannesburg to Toronto on March 30, 2024, for one adult, and analyze the price trends for the following month.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--28", "ques": "Find the best-priced round-trip flight from Seattle to Paris, departing on February 27, 2024, and returning on March 1, 2024, with a maximum of one stop.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--29", "ques": "Compare the prices and total travel time of non-stop flights from Mexico City to Frankfurt, departing on March 5, 2024, and returning on March 15, 2024.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--30", "ques": "Find the most affordable one-way flight from Cape Town to Singapore, departing on March 20, 2024, and include the airline and total number of layovers.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--31", "ques": "Find a one-way economy flight from Auckland to Honolulu on March 25, 2024, browse the full page and display a flight option with the most stops.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--32", "ques": "Search for round-trip flights from Stockholm to Toronto, departing on March 3, 2024, and returning on March 10, 2024, and sort the results to find the shortest total travel time.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--33", "ques": "Find a one-way flight from Shanghai to Vancouver on February 27, 2024, and compare the options based on carbon dioxide emissions.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--34", "ques": "Compare business class flight options from Lisbon to Singapore for a one-way trip on March 15, 2024, select one of the flights and see which websites offer its booking options. Which one is the cheapest.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--35", "ques": "Find the lowest-priced one-way flight from Cairo to Montreal on February 21, 2024, including the total travel time and number of stops.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--36", "ques": "Search for round-trip flights from Helsinki to New Delhi, departing on March 28, 2024, and returning on April 4, 2024, and filter the results to show only flights under $1000.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--37", "ques": "Locate a round-trip flight from Buenos Aires to Beijing, leaving on February 28, 2024, and returning on March 3, 2024, check out one of the options and tell me if the airline for my return flight is the same as my departure flight.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--38", "ques": "Compare the prices and flight durations for economy class flights from Oslo to Dubai, departing on March 8, 2024, and show the options with no more than two layovers.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--39", "ques": "Find a one-way flight from Prague to a city in Japan on March 20, 2024, which city in Japan is cheaper to go to, Tokyo or a certain city in Hokkaido?", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--40", "ques": "Browse destinations on the Google Flights homepage from Seattle, look at destinations on a map, and recommend some famous places to travel that are within a reasonable distance and price.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Flights", "id": "Google Flights--41", "ques": "Choose one way business class ticket from Hong Kong to Glacier National Park on 8 March 2024, offering a 1 stop ticket.", "web": "https://www.google.com/travel/flights/"} +{"web_name": "Google Map", "id": "Google Map--0", "ques": "Find 5 beauty salons with ratings greater than 4.8 in Seattle, WA.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--1", "ques": "Tell me one bus stop that is nearest to the intersection of main street and Amherst street in Altavista.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--2", "ques": "Find Apple Stores close to zip code 90028", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--3", "ques": "The least amount of walking from Central Park Zoo to the Broadway Theater in New York.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--4", "ques": "Plan a trip from Boston Logan Airport to North Station.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--5", "ques": "Search for a parking garage near Thalia Hall in Chicago that isn't open 24 hours.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--6", "ques": "Find all Uniqlo locations in Chicago, IL.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--7", "ques": "Find bus stops in Alanson, MI", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--8", "ques": "Find a place to climb within 2 miles of zip code 90028.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--9", "ques": "Find the art gallery that is nearest to Los Angeles Hindu Temple.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--10", "ques": "Search for a park in the state of California called Castle Mountains National Monument and find out it's Basic Information.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--11", "ques": "Locate a large store in Washington that has kids' and maternity products, also check if it has a parking lot.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--12", "ques": "Find 5 places that serve burgers near 44012 zip code and sort these 5 places by highest rating.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--13", "ques": "Find a parking lot in Gloucester and book a ride from there to North Plymouth, view the map to understand the route better.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--14", "ques": "Find motorcycle parking near Radio City Music Hall.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--15", "ques": "Find daytime only parking nearest to Madison Square Garden. Summarize what people are saying about it. ", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--16", "ques": "Find EV charging supported parking closest to Smithsonian museum.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--17", "ques": "Search for locksmiths open now but not open 24 hours in Texas City.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--18", "ques": "Find a route between Chicago to Los Angeles, then print the route details.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--19", "ques": "I will arrive Pittsburgh Airport soon. Provide the name of the Hilton hotel closest to the airport. Then, tell me the the walking time to the nearest supermarket from the hotel.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--20", "ques": "Find Tesla Destination Charger closest to the National Air and Space Museum.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--21", "ques": "Identify the nearest bus stop to the corner of Elm Street and Oak Street in Massachusetts.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--22", "ques": "Find a Best Buy store near zip code 33139.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--23", "ques": "Determine the shortest walking route from The Metropolitan Museum of Art to Times Square in New York.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--24", "ques": "Plan a journey from San Francisco International Airport to Union Square via driving.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--25", "ques": "Search for a parking facility near the Fox Theater in Detroit that closes at night.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--26", "ques": "Search for Los Angeles on Google Map, try to print the map as PDF and summarize the information on the map.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--27", "ques": "Locate the Target stores in Atlanta, GA. How many results are shown on the map.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--28", "ques": "Find the search settings for Google Map, what options are shown on that page?", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--29", "ques": "Identify bus stops in Ypsilanti, MI, list three of them.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--30", "ques": "Locate a parking lot near the Brooklyn Bridge that open 24 hours. Review the user comments about it.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--31", "ques": "First search New York's Central Park Zoo on Google Map, and then find the way to share the map. What is the generated sharing link?", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--32", "ques": "Search for plumbers available now but not open 24 hours in Orlando, FL.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--33", "ques": "Check out Denver International Airport's information and tell me: 1) which level has the least proportion in reviews; 2) what are its Accessibility and Amenities.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--34", "ques": "Find a hiking trail within 2 miles of zip code 80202.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--35", "ques": "Search for a natural reserve in Texas called Big Bend National Park and gather its Basic Information.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--36", "ques": "Identify 5 restaurants serving pizza near the 30309 zip code and rank them by their ratings.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--37", "ques": "Locate a parking area in Salem and find a route from there to Marblehead, including map directions for better understanding.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--38", "ques": "Search for bicycle parking near the Empire State Building.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--39", "ques": "Find a route from Miami to New Orleans, and provide the detailed route information.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Map", "id": "Google Map--40", "ques": "Find a restaurant in Boston that eats Boston lobster and asks for a rating of 4.6 or higher, and check out what a one-star review says.", "web": "https://www.google.com/maps/"} +{"web_name": "Google Search", "id": "Google Search--0", "ques": "Find the initial release date for Guardians of the Galaxy Vol. 3 the movie.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--1", "ques": "Find Kevin Durant's bio", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--2", "ques": "Search for the latest news title about the NBA team the Los Angeles Lakers.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--3", "ques": "Show me a list of comedy movies, sorted by user ratings. Show me the Top 5 movies.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--4", "ques": "Show most played games in Steam. And tell me the number of players in In game at this time", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--5", "ques": "find the score of the latest nba game played by the phoenix suns.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--6", "ques": "Browse the monthly trending searches in Columbus.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--7", "ques": "Find the software requirements for iPhones that support AirDrop's ability to continue transmitting over the web when out of range.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--8", "ques": "Find the video on YouTube: 'Oscars 2023: Must-See Moments!'. Tell me who the first comment displayed under that video belongs to, and how many thumbs up and replies it has.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--9", "ques": "Show the rating of Prometheus movie on IMDb and Rotten Tomatoes.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--10", "ques": "Find the no. 1 weekly charts ranked artist based on Billboard and tell me 10 most played song by this artist until now.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--11", "ques": "According to FlightAware, tell me the busiest airport last week and its total arrivals and departures last week.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--12", "ques": "Find the year that Tom Brady had the most touchdowns in a single seasson.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--13", "ques": "What are Jerry Trainor's upcoming projects?", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--14", "ques": "Find the retired players the year before last named James Smith and tell me which club he has been a member of from 2020\u20132021.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--15", "ques": "Please try to log in to twitter with email: webagenttest@testmail.com and password: test123456. Let me know if the login was successful.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--16", "ques": "How many members are there in the OpenAI community on Reddit, and what is the hottest news right now?", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--17", "ques": "Tell me the names of Trump's kids", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--18", "ques": "When and where the most recent World Cup was held, and which team was the winner?", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--19", "ques": "What are the first 7 bits of the SHA of the Bert's latest commit on GitHub, and what exactly was changed in that commit.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--20", "ques": "Find the release date for the latest \"Fast & Furious\" movie.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--21", "ques": "Show a list of the top 5 highest-grossing animated movies, sorted by box office earnings.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--22", "ques": "Browse and list the top three trending topics this month in New York City.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--23", "ques": "Retrieve a short biography of LeBron James.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--24", "ques": "What is the name of the star system closest to the Solar System, and what are the discovered planets in it?", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--25", "ques": "Get the latest news headline about the English Premier League football club Manchester United.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--26", "ques": "Identify the hardware requirements for using the latest version of Adobe Photoshop on a Mac.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--27", "ques": "Check the current air quality index in Paris.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--28", "ques": "Check the IMDb and Metacritic scores of the movie \"Inception.\"", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--29", "ques": "Find out the current world record for the men's 100m sprint.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--30", "ques": "Find the current number one artist on the Spotify Global Top 50 chart and list his/her top 10 songs as of now.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--31", "ques": "Discover which year Cristiano Ronaldo scored the most goals in a single season.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--32", "ques": "Find out where and when the most recent UEFA Champions League final was held, and which team won.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--33", "ques": "Find and copy the SHA of the latest commit in the TensorFlow repository on GitHub, then find a textbox to paste and tell me what the SHA is.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--34", "ques": "Determine the distance from Earth to Mars as of today's date.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--35", "ques": "Look up the latest research paper related to black holes published in the journal \"Nature Astronomy\".", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--36", "ques": "Search for the most recent Nobel Prize winner in Physics and their contribution to the field.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--37", "ques": "Find the current top 3 super-earth planets and give a brief introduction to them.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--38", "ques": "Search for the next visible solar eclipse in North America and its expected date, and what about the one after that.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--39", "ques": "Identify the top-10 trending travel destination for 2024 through a blog, how many of them are in Asian.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--40", "ques": "Look up the elevation of Mount Kilimanjaro on Google Search.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--41", "ques": "Look up the current statistics of air pollution level in Los Angeles using Google Search.", "web": "https://www.google.com/"} +{"web_name": "Google Search", "id": "Google Search--42", "ques": " Use Google Search to find an article that explains the major differences between American English and British English.", "web": "https://www.google.com/"} +{"web_name": "Huggingface", "id": "Huggingface--0", "ques": "Find a pre-trained natural language processing model on Hugging Face that can perform sentiment analysis, and make sure the model's last update is within March 2023.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--1", "ques": "Use the Huggingface Inference API to generate a short story about a dragon and a wizard.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--2", "ques": "Discover three new and popular open-source NLP models for language translation released in the past month on Huggingface.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--3", "ques": "Look up a model with a license of cc-by-sa-4.0 with the most likes on Hugging face.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--4", "ques": "Locate an open-source conversational AI model on Hugging Face, trained in English and list its main features and applications.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--5", "ques": "Find a model released on Hugging Face for recipe generation. Retrieve the information of the model, including its name, model size and tensor type.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--6", "ques": "Find the model sentence-transformers/all-MiniLM-L6-v2 and use the Inference API on the webpage to get the similarity of the following two sentences: 'Tomorrow is Sunday', 'Eat a burger on Sunday'.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--7", "ques": "Which is the most downloaded audio related dataset on Hugging face currently.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--8", "ques": "Retrieve an example of a pre-trained language model in natural language processing and identify the tasks it is specifically designed for, like translation or text summarization.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--9", "ques": "Find the most download machine translation model on Huggingface which focuses on English and Japanese (en-ja) and report the evaluation metrics stated for it.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--10", "ques": "Open space: argilla/notux-chat-ui and interact with it by asking it 'which team trained you'. What is its answer.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--11", "ques": "Identify the latest updated image to video model available on Huggingface and summarize its main features.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--12", "ques": "Find the most recently updated machine learning model on Huggingface which focuses on Error Correction.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--13", "ques": "Search for LLaMA in the huggingface doc, what type is the spaces_between_special_tokens parameter in LlamaTokenizer and what is its default value.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--14", "ques": "How much is the Pro account of Hugging face for a month and what are the features?", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--15", "ques": "Identify the most downloaded models on Hugging face that use the PaddlePaddle library.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--16", "ques": "Find information on the latest (as of today's date) pre-trained language model on Huggingface suitable for text classification and briefly describe its intended use case and architecture.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--17", "ques": "Find the most recently updated open-source project related to natural language processing on the Huggingface platform. Provide the project's name, creator, and a brief description of its functionality.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--18", "ques": "Look up TRL's forward modelling in the hugging face documentation on how to add a margin to a loss.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--19", "ques": "Explore and summarize the features of the most recent open-source NLP model released by Hugging Face for English text summarization.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--20", "ques": "Locate a pre-trained natural language processing model on Hugging Face that specializes in named entity recognition (NER), confirm that the model was last updated in 2022 and has 1M+ downloads.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--21", "ques": "Look up the tour about how to use the 'pipeline' feature in the Hugging Face Transformers library for sentiment analysis, and identify the default model it uses.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--22", "ques": "Identify the steps to convert a PyTorch model to TensorFlow using the Hugging Face Transformers library as described in their documentation.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--23", "ques": "Identify three innovative and widely recognized open-source NLP models for automatic speech recognition released in the past month on Huggingface.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--24", "ques": "Search for a model on Hugging Face with an Apache-2.0 license that has received the highest number of likes.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--25", "ques": "In the Hugging Face documentation, find the tutorial on loading adapters with PEFT, tell me how to load in 8bit or 4bit.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--26", "ques": "Identify a model on Hugging Face designed for generating travel chats. Obtain information about the model, including its name, size and training framwork.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--27", "ques": "Determine the most downloaded dataset related to Text Retrieval in NLP on Hugging Face.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--28", "ques": "Retrieve an example of a pre-trained model on Hugging Face that is optimized for question answering tasks and detail the languages it supports.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--29", "ques": "Summarize the description of the recent open-source NLP model released on Hugging Face for medical summarization.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--30", "ques": "Identify the most downloaded English-Chinese (en-zh) machine translation model on Huggingface and report its latest performance metrics and usage guidelines.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--31", "ques": "Identify the latest machine learning model on Huggingface that specializes in detecting fake news, including the date of its last update.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--32", "ques": "On the Hugging Face website, search for the model 'GPT-J-6B' and find the 'temperature' parameter in its settings. What is the default value of this parameter?", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--33", "ques": "List three hugging face docs. How many GitHub stars have they earned so far?", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--34", "ques": "List the benefits of hugging face classroom mentioned on Hugging face website.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--35", "ques": "Find the latest Diffusion-related blog on Hugging Face, and read its intro or overview section to roughly summarize the content of the blog.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--36", "ques": "Summarize all the payment plans and their advantages in huggingface pricing.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--37", "ques": "Browse the daily paper on Hugging Face. What is the title of the first article, how many upvotes has it received, and is there any related model or data release?", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--38", "ques": "Investigate the 'transformers' library in the Hugging Face documentation, focusing on how to add new tokens to a tokenizer.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--39", "ques": "Investigate in the Hugging Face documentation how to utilize the 'Trainer' API for training a model on a custom dataset, and note the configurable parameters of the Trainer class.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--40", "ques": "Check out Text Embeddings Inference in Hugging face's Doc to summarise the strengths of the toolkit.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--41", "ques": "What is the current Text-to-3D model with the highest number of downloads and tell me are there Spaces that use the model.", "web": "https://huggingface.co/"} +{"web_name": "Huggingface", "id": "Huggingface--42", "ques": "Check the Dataset Viewer for ai2lumos/lumos_complex_qa_plan_onetime on Hugging face. what is the content corresponding to user in the first message?", "web": "https://huggingface.co/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--0", "ques": "derivative of x^2 when x=5.6", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--1", "ques": "Give a constraint on the set of inequalities for the inner region of the pentagram.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--2", "ques": "Calculate 3^71 and retain 5 significant figures in scientific notation.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--3", "ques": "Let g(x) be the integral of x^2 cos(2x). Write the expression of g(x).", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--4", "ques": "Pack 24 circles in a circle radius r. Compare Densest known packing and Square packing. Then tell me the radius of the inner circles.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--5", "ques": "Show the solution of y\"(z) + sin(y(z)) = 0 from wolframalpha.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--6", "ques": "Simplify x^5-20x^4+163x^3-676x^2+1424x-1209 so that it has fewer items.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--7", "ques": "Give the final angle and final length after 6s of a Spring pendulum with spring equilibrium length=0.12m, initial length=0.24m, initial angle=80deg, mass=1kg, spring constant=120 N/m .", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--8", "ques": "Give 12 lbs of 4-cyanoindole, converted to molar and indicate the percentage of C, H, N.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--9", "ques": "Annual energy production of Diablo Canyon 2 in 2010.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--10", "ques": "Give the geomagnetic field on June 20, 2023 in Oslo.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--11", "ques": "Show the electrical resistivity of UNS A92024 and UNS G10800 at 20 degrees Celsius.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--12", "ques": "Which character in unicode 8900 to 8920 looks like a snowflake", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--13", "ques": "What is 10,000 US dollars worth now in 1980 and in 1970?", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--14", "ques": "Compare the total Calories: whopper vs baconator vs big mac. Assume that each serving of food is 300g.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--15", "ques": "Show the blood relationship fraction between you and your father's mother's sister's son.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--16", "ques": "Weight lose for a male with current weight 90 kg, 40 year old, 175 cm. If he intakes 1500 calories every day, how long will it take to lose 17 kg.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--17", "ques": "Show the average price of movie ticket in Providence, Nashville, Boise in 2023.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--18", "ques": "Plot Albert Einstein curve with Parametric equations.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--19", "ques": "Standing in the sun from 11:00 am with SPF 5 in Australia. Approximate time to sunburn for each skin type.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--20", "ques": "Compute the integral of 3e^(2x) from x=0 to x=5.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--21", "ques": "Calculate (1+0.1*i)^8 + (1\u22120.2*i)^8 where i is a complex number.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--22", "ques": "Determine the area of a regular hexagon with a side length of 7 cm.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--23", "ques": "Calculate the population growth rate of Canada from 2020 to 2023 using Wolfram Alpha.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--24", "ques": "Solve the differential equation y''(t) - 2y'(t) + 10y(t) = 0 and display its general solution.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--25", "ques": "Calculate the final position and velocity of a projectile launched at 45 degrees with an initial speed of 30 m/s after 3 seconds.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--26", "ques": "Convert 15 kilograms of sulfuric acid to moles and display the percentage composition of H, S, and O by weight.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--27", "ques": "Display the thermal conductivity of Copper (Cu) and Aluminum (Al) at 25 degrees Celsius.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--28", "ques": "Identify the character in Unicode range 9632 to 9650 that represents a hollow parallelogram.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--29", "ques": "Create a plot of cat curve using wolfram alpha.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--30", "ques": "Calculate the estimated time to sunburn for different skin types when exposed to the sun at 1:00 pm with SPF 1 in Brazil.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--31", "ques": "Using Wolfram Alpha, determine the current temperature and wind speed in Chicago, IL.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--32", "ques": "Print all prime numbers between 1000 and 1200 using Wolfram alpha.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--33", "ques": "Identify the electrical energy output of a hydroelectric power plant named Itaipu Dam in 2023 using Wolfram Alpha.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--34", "ques": "Calculate the mass of Jupiter compared to Earth using Wolfram Alpha. Also, find the length of one day on Jupiter.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--35", "ques": "Calculate the determinant of a 6x6 Hilbert matrix.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--36", "ques": "Determine the convergence or divergence of the series \u03a3 (n=1 to \u221e) of 1/(n^3 + 1).", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--37", "ques": "How many days are there between February 12, 2024 and August 9, 2050?", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--38", "ques": "Compute the length of a curve defined by y = 2x^3 - 3x^2 + 4x - 5 from x = 0 to x = 3.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--39", "ques": "Use Wolfram alpha to write the expression of the ellipse x^2 + 3 y^2 = 4 rotated 33 degrees counterclockwise.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--40", "ques": "Approximate amount of fat burned by a 28yo, 172cm tall, 70kg woman running for 30min at a pace of 6min/mile.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--41", "ques": "What is the approximate Heart Rate Reserve of a 50 year old man who has a heart rate of 60bpm at rest.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--42", "ques": "What is the raw memory of a 100.2\" * 123.5\" true colour picture at 72 ppi?", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--43", "ques": "A polyominoes of order 6 means you have 6 identical squares to combine different shapes (2-sided). How many combinations are there? Looking at all the shapes in the result, how many of them have only 2 rows in total?", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--44", "ques": "Solve the ODE, g' + cos(g) = 0, if there is a constant in the result, determine the value of the constant by the condition that g(0) = 1.", "web": "https://www.wolframalpha.com/"} +{"web_name": "Wolfram Alpha", "id": "Wolfram Alpha--45", "ques": "A 175cm tall, 85kg, 40yo man climbs 2500 steps at about 18cm per step and 40 steps per minute. summarise the Metabolic properties.", "web": "https://www.wolframalpha.com/"} \ No newline at end of file diff --git a/sdk/stagehand-ts/evals/deterministic/auxiliary/logo.png b/sdk/stagehand-ts/evals/deterministic/auxiliary/logo.png new file mode 100644 index 0000000..7ae5d48 Binary files /dev/null and b/sdk/stagehand-ts/evals/deterministic/auxiliary/logo.png differ diff --git a/sdk/stagehand-ts/evals/deterministic/bb.playwright.config.ts b/sdk/stagehand-ts/evals/deterministic/bb.playwright.config.ts new file mode 100644 index 0000000..4c01279 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/bb.playwright.config.ts @@ -0,0 +1,32 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: "./tests/browserbase", + + /* Fail the build on CI if you accidentally left test.only in the source code. */ + /* Run tests in files in parallel */ + fullyParallel: true, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + // reporter: "html", + reporter: "line", + /* Retry on CI only */ + retries: 2, + + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: "on-first-retry", + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + }, + ], + timeout: 60000, +}); diff --git a/sdk/stagehand-ts/evals/deterministic/e2e.playwright.config.ts b/sdk/stagehand-ts/evals/deterministic/e2e.playwright.config.ts new file mode 100644 index 0000000..4ed3c25 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/e2e.playwright.config.ts @@ -0,0 +1,33 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + // Look in "tests" for test files... + testDir: "./tests", + // ...but ignore anything in "tests/browserbase & "tests/local" + testIgnore: ["**/browserbase/**", "**/local/**"], + + /* Fail the build on CI if you accidentally left test.only in the source code. */ + /* Run tests in files in parallel */ + fullyParallel: true, + /* Reporter to use. See https://playwright.dev/docs/test-reporters */ + // reporter: "html", + reporter: "line", + retries: 2, + + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: "on-first-retry", + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + }, + ], +}); diff --git a/sdk/stagehand-ts/evals/deterministic/local.playwright.config.ts b/sdk/stagehand-ts/evals/deterministic/local.playwright.config.ts new file mode 100644 index 0000000..3c309ff --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/local.playwright.config.ts @@ -0,0 +1,37 @@ +import { defineConfig, devices } from "@playwright/test"; + +/** + * See https://playwright.dev/docs/test-configuration. + */ +export default defineConfig({ + testDir: "./tests/local", + + /* Maximum time one test can run for. */ + timeout: 30 * 1000, + + /* Fail the build on CI if you accidentally left test.only in the source code. */ + forbidOnly: !!process.env.CI, + + /* Run tests in files in parallel */ + fullyParallel: false, + + /* Reporter to use */ + reporter: "line", + + /* Retry on CI only */ + retries: process.env.CI ? 2 : 0, + + /* Shared settings for all the projects below. See https://playwright.dev/docs/api/class-testoptions. */ + use: { + /* Collect trace when retrying the failed test. See https://playwright.dev/docs/trace-viewer */ + trace: "on-first-retry", + }, + + /* Configure projects for major browsers */ + projects: [ + { + name: "chromium", + use: { ...devices["Desktop Chrome"] }, + }, + ], +}); diff --git a/sdk/stagehand-ts/evals/deterministic/stagehand.config.ts b/sdk/stagehand-ts/evals/deterministic/stagehand.config.ts new file mode 100644 index 0000000..7f46af4 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/stagehand.config.ts @@ -0,0 +1,18 @@ +import { default as DefaultStagehandConfig } from "@/stagehand.config"; +import type { ConstructorParams } from "@browserbasehq/stagehand"; +import dotenv from "dotenv"; +dotenv.config({ path: "../../.env" }); + +const StagehandConfig: ConstructorParams = { + ...DefaultStagehandConfig, + env: "LOCAL" /* Environment to run Stagehand in */, + verbose: 1 /* Logging verbosity level (0=quiet, 1=normal, 2=verbose) */, + browserbaseSessionCreateParams: { + projectId: process.env.BROWSERBASE_PROJECT_ID, + }, + enableCaching: false /* Enable caching functionality */, + localBrowserLaunchOptions: { + headless: true /* Run browser in headless mode */, + }, +}; +export default StagehandConfig; diff --git a/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/addInitScript.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/addInitScript.test.ts new file mode 100644 index 0000000..9211fe1 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/addInitScript.test.ts @@ -0,0 +1,45 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandContext - addInitScript", () => { + test("should inject a script on the context before pages load", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const context = stagehand.context; + + await context.addInitScript(() => { + const w = window as typeof window & { + __testContextScriptVar?: string; + }; + w.__testContextScriptVar = "Hello from context.initScript!"; + }); + + const pageA = await context.newPage(); + await pageA.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const resultA = await pageA.evaluate(() => { + const w = window as typeof window & { + __testContextScriptVar?: string; + }; + return w.__testContextScriptVar; + }); + expect(resultA).toBe("Hello from context.initScript!"); + + const pageB = await context.newPage(); + await pageB.goto("https://docs.browserbase.com"); + + const resultB = await pageB.evaluate(() => { + const w = window as typeof window & { + __testContextScriptVar?: string; + }; + return w.__testContextScriptVar; + }); + expect(resultB).toBe("Hello from context.initScript!"); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/cookies.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/cookies.test.ts new file mode 100644 index 0000000..c30af4a --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/cookies.test.ts @@ -0,0 +1,71 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandContext - Cookies", () => { + let stagehand: Stagehand; + + test.beforeEach(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterEach(async () => { + await stagehand.close(); + }); + + test("should add cookies and retrieve them", async () => { + const context = stagehand.context; // This is the wrapped BrowserContext + const url = + "https://browserbase.github.io/stagehand-eval-sites/sites/example"; + + await context.addCookies([ + { + name: "myCookie", + value: "myValue", + domain: "browserbase.github.io", + path: "/", + expires: Math.floor(Date.now() / 1000) + 3600, + httpOnly: false, + secure: false, + sameSite: "Lax", + }, + ]); + + const cookies = await context.cookies(url); + expect(cookies.length).toBeGreaterThan(0); + + const myCookie = cookies.find((c) => c.name === "myCookie"); + expect(myCookie).toBeDefined(); + expect(myCookie?.value).toBe("myValue"); + }); + + test("should clear all cookies", async () => { + const context = stagehand.context; + const url = + "https://browserbase.github.io/stagehand-eval-sites/sites/example"; + + await context.addCookies([ + { + name: "myOtherCookie", + value: "anotherValue", + domain: "browserbase.github.io", + path: "/", + expires: Math.floor(Date.now() / 1000) + 3600, + httpOnly: false, + secure: false, + sameSite: "Lax", + }, + ]); + + const cookiesBefore = await context.cookies(url); + const found = cookiesBefore.some((c) => c.name === "myOtherCookie"); + expect(found).toBe(true); + + await context.clearCookies(); + + const cookiesAfter = await context.cookies(url); + const stillFound = cookiesAfter.some((c) => c.name === "myOtherCookie"); + expect(stillFound).toBe(false); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/multiPage.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/multiPage.test.ts new file mode 100644 index 0000000..87c5cfc --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/multiPage.test.ts @@ -0,0 +1,199 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +import http from "http"; +import express from "express"; +import { Server as WebSocketServer } from "ws"; + +test.describe("StagehandContext - Multi-page Support", () => { + let stagehand: Stagehand; + let server: http.Server; + let wss: WebSocketServer; + let serverPort: number; + + test.beforeAll(async () => { + // Set up a local Express server + const app = express(); + + // Serve test pages + app.get("/page1", (_req, res) => { + res.set("Content-Type", "text/html"); + res.end(` + + Page 1 + +

Page 1 Content

+ + + + `); + }); + + app.get("/page2", (_req, res) => { + res.set("Content-Type", "text/html"); + res.end(` + + Page 2 + +

Page 2 Content

+ + + `); + }); + + // Create the server on a random free port + server = http.createServer(app); + await new Promise((resolve) => { + server.listen(0, () => resolve()); + }); + const address = server.address(); + if (typeof address === "object" && address !== null) { + serverPort = address.port; + } else { + throw new Error("Failed to get server port"); + } + + // Set up WebSocket for future tests + wss = new WebSocketServer({ server, path: "/socket" }); + wss.on("connection", (ws) => { + console.log("WebSocket client connected"); + ws.send("Hello from server WebSocket"); + }); + }); + + test.beforeEach(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterEach(async () => { + await stagehand.close(); + }); + + test.afterAll(async () => { + wss?.close(); + server?.close(); + }); + + /** + * Test enhanced page capabilities + */ + test("should provide enhanced capabilities for new pages", async () => { + const context = stagehand.context; + const newPage = await context.newPage(); + + // Verify enhanced methods + expect(typeof newPage.act).toBe("function"); + expect(typeof newPage.extract).toBe("function"); + expect(typeof newPage.observe).toBe("function"); + + // Verify basic Playwright functionality + expect(typeof newPage.goto).toBe("function"); + expect(typeof newPage.click).toBe("function"); + + // Test navigation maintains capabilities + await newPage.goto(`http://localhost:${serverPort}/page1`); + expect(typeof newPage.act).toBe("function"); + expect(await newPage.title()).toBe("Page 1"); + }); + + /** + * Test context.pages() functionality + */ + test("should return array of enhanced pages via context.pages()", async () => { + const context = stagehand.context; + + // Create multiple pages + const page1 = await context.newPage(); + const page2 = await context.newPage(); + + await page1.goto(`http://localhost:${serverPort}/page1`); + await page2.goto(`http://localhost:${serverPort}/page2`); + + const pages = context.pages(); + expect(pages).toContain(page1); + expect(pages).toContain(page2); + + // Verify all pages have enhanced capabilities + for (const page of pages) { + expect(typeof page.act).toBe("function"); + expect(typeof page.extract).toBe("function"); + expect(typeof page.observe).toBe("function"); + } + }); + + /** + * Test popup handling + */ + test("should handle popups with enhanced capabilities", async () => { + await stagehand.page.goto(`http://localhost:${serverPort}/page1`); + await stagehand.page.click("#popupBtn"); + + await expect.poll(() => stagehand.context.pages().length).toBe(2); + + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const [_original, popupPage] = stagehand.context.pages(); + + await popupPage.waitForLoadState(); + + const get = (k: string) => + (popupPage as unknown as Record)[k]; + + expect(typeof get("act")).toBe("function"); + expect(typeof get("extract")).toBe("function"); + expect(typeof get("observe")).toBe("function"); + + expect(await popupPage.title()).toBe("Page 2"); + }); + + /** + * Test page tracking and cleanup + */ + test("should properly track and cleanup pages", async () => { + const context = stagehand.context; + const initialPages = context.pages().length; + + const newPage = await context.newPage(); + await newPage.goto(`http://localhost:${serverPort}/page1`); + + expect(context.pages().length).toBe(initialPages + 1); + await newPage.close(); + expect(context.pages().length).toBe(initialPages); + }); + + /** + * Test enhanced methods across pages + */ + test("should support enhanced methods across all pages", async () => { + const page1 = await stagehand.context.newPage(); + const page2 = await stagehand.context.newPage(); + + await page1.goto(`http://localhost:${serverPort}/page1`); + await page2.goto(`http://localhost:${serverPort}/page2`); + + // Verify both pages have enhanced capabilities + expect(typeof page1.act).toBe("function"); + expect(typeof page1.extract).toBe("function"); + expect(typeof page1.observe).toBe("function"); + + expect(typeof page2.act).toBe("function"); + expect(typeof page2.extract).toBe("function"); + expect(typeof page2.observe).toBe("function"); + }); + + /** + * Test active page tracking + */ + test("should update stagehand.page when creating new pages", async () => { + const initialTitle = await stagehand.page.title(); // "about:blank" → "" + + // Create a new page + const newPage = await stagehand.context.newPage(); + await newPage.goto(`http://localhost:${serverPort}/page1`); + + // The proxy should now forward to the new page: + expect(await stagehand.page.title()).toBe("Page 1"); + expect(await stagehand.page.title()).not.toBe(initialTitle); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/page.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/page.test.ts new file mode 100644 index 0000000..5cb4692 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/page.test.ts @@ -0,0 +1,100 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +import http from "http"; +import express from "express"; +import { Server as WebSocketServer } from "ws"; + +test.describe("StagehandContext - pages and newPage", () => { + let stagehand: Stagehand; + let server: http.Server; + let wss: WebSocketServer; + let serverPort: number; + + test.beforeAll(async () => { + // 1. Spin up a local Express server + const app = express(); + + // Serve a single page at "/" + app.get("/", (_req, res) => { + res.set("Content-Type", "text/html"); + res.end(` + + + Test Page + + +

Hello from local server

+ + + + `); + }); + + // Create the server on a random free port + server = http.createServer(app); + await new Promise((resolve) => { + server.listen(0, () => resolve()); + }); + const address = server.address(); + if (typeof address === "object" && address !== null) { + serverPort = address.port; + } else { + throw new Error("Failed to get server port"); + } + + // Optionally set up a WebSocket for future tests + wss = new WebSocketServer({ server, path: "/socket" }); + wss.on("connection", (ws) => { + console.log("WebSocket client connected"); + ws.send("Hello from server WebSocket"); + }); + }); + + test.beforeEach(async () => { + // 2. Create & init Stagehand for each test + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterEach(async () => { + await stagehand.close(); + }); + + test.afterAll(async () => { + // Shut down local server + wss?.close(); + server?.close(); + }); + + /** + * Test context.newPage() and context.pages() + */ + test("should create multiple pages and list them via context.pages()", async () => { + const context = stagehand.context; + + // Create multiple pages + const page1 = await context.newPage(); + const page2 = await context.newPage(); + + // Confirm context.pages() sees them + const allPages = context.pages(); + + // We expect at least these 2 pages. If a default blank page existed, total might be more. + // The key is that page1 & page2 are in the array: + expect(allPages).toContain(page1); + expect(allPages).toContain(page2); + + // Navigate page1 to the local server + await page1.goto(`http://localhost:${serverPort}`); + expect(await page1.title()).toBe("Test Page"); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/routing.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/routing.test.ts new file mode 100644 index 0000000..3d3dda7 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/BrowserContext/routing.test.ts @@ -0,0 +1,236 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +import http from "http"; +import express from "express"; +import { Server as WebSocketServer } from "ws"; +import fs from "fs"; +import path from "path"; + +const HAR_CONTENT = `{ + "log": { + "version": "1.2", + "creator": { "name": "PlaywrightTest", "version": "1.0" }, + "entries": [ + { + "startedDateTime": "2023-01-01T00:00:00.000Z", + "time": 5, + "request": { + "method": "GET", + "url": "http://localhost/har-example.json", + "httpVersion": "HTTP/1.1", + "cookies": [], + "headers": [], + "queryString": [], + "headersSize": -1, + "bodySize": 0 + }, + "response": { + "status": 200, + "statusText": "OK", + "httpVersion": "HTTP/1.1", + "cookies": [], + "headers": [{"name":"Content-Type","value":"application/json"}], + "content": { + "size": 27, + "mimeType": "application/json", + "text": "{\\"harKey\\":\\"harValue\\"}" + }, + "redirectURL": "", + "headersSize": -1, + "bodySize": 0 + }, + "cache": {}, + "timings": { "send": 0, "wait": 5, "receive": 0 } + } + ] + } +}`; + +test.describe("StagehandContext - Routing APIs with dynamic setup", () => { + let stagehand: Stagehand; + let server: http.Server; + let wss: WebSocketServer; + let serverPort: number; + + test.beforeAll(async () => { + const app = express(); + + app.get("/example.json", (_req, res) => { + res.json({ original: "server-data" }); + }); + + app.get("/har-example.json", (_req, res) => { + res.json({ + fromServer: + "This should be replaced by HAR if routeFromHar is in effect", + }); + }); + + server = http.createServer(app); + await new Promise((resolve) => { + server.listen(0, () => resolve()); + }); + const address = server.address(); + if (typeof address === "object" && address !== null) { + serverPort = address.port; + } else { + throw new Error("Failed to get server port"); + } + + // Set up a WebSocket endpoint at "/socket" + wss = new WebSocketServer({ server, path: "/socket" }); + wss.on("connection", (ws) => { + console.log("WebSocket client connected"); + ws.send("Hello from server WebSocket"); + + // Echo messages back + ws.on("message", (message) => { + console.log("Server received WS message:", message); + ws.send(`Server echo: ${message}`); + }); + }); + }); + + test.beforeEach(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterEach(async () => { + await stagehand.close(); + }); + + test.afterAll(async () => { + wss?.close(); + server?.close(); + }); + + test("should intercept requests, mock the response, handle websockets, and unroute them", async () => { + const context = stagehand.context; + const baseURL = `http://localhost:${serverPort}`; + + // 1. route: intercept "/example.json" and fulfill with a mock response + await context.route("**/example.json", async (route) => { + console.log("[route] Intercepting:", route.request().url()); + + // Mock the response entirely: + await route.fulfill({ + status: 200, + contentType: "application/json", + body: JSON.stringify({ mockedData: 1234 }), + }); + }); + + // 2. routeWebSocket: intercept "/socket" + await context.routeWebSocket("**/socket", async (pageSideRoute) => { + console.log("Intercepting WebSocket at:", pageSideRoute.url()); + + // Connect to the real server + const serverSideRoute = pageSideRoute.connectToServer(); + + // Page -> Server + pageSideRoute.onMessage((msg) => { + console.log("Page -> Server message:", msg); + // Forward to server side + serverSideRoute.send(msg); + }); + + // Server -> Page + serverSideRoute.onMessage((msg) => { + console.log("Server -> Page message:", msg); + pageSideRoute.send(msg); + }); + }); + + // 3. Open a page and fetch /example.json + const page = await context.newPage(); + await page.goto(baseURL); + + const fetchResult = await page.evaluate(async () => { + const res = await fetch("/example.json"); + return res.json(); + }); + // We should get the mocked data from our route, not the real 'server-data' + expect(fetchResult.mockedData).toBe(1234); + + // 4. Test the WebSocket + // We'll store messages from the server in an array so we can assert them + const wsMessages: string[] = []; + page.on("console", (msg) => { + // We'll parse out the console logs we used for WebSocket + if (msg.type() === "log") { + wsMessages.push(msg.text()); + } + }); + + // Create a WS from the page + await page.evaluate((port) => { + const ws = new WebSocket(`ws://localhost:${port}/socket`); + ws.onmessage = (evt) => { + console.log(`WS message from server: ${evt.data}`); + }; + setTimeout(() => { + // send a message from the page side + ws.send("Hello from the client"); + }, 1000); + }, serverPort); + + // Wait a moment for messages + await page.waitForTimeout(3000); + + // We expect the server to have initially sent "Hello from server WebSocket" + // And also an echo of "Hello from the client" => "Server echo: Hello from the client" + const initialHello = wsMessages.find((m) => + m.includes("Hello from server WebSocket"), + ); + expect(initialHello).toBeTruthy(); + + const echoMessage = wsMessages.find((m) => + m.includes("Server echo: Hello from the client"), + ); + expect(echoMessage).toBeTruthy(); + + // 5. unroute the JSON route + await context.unroute("**/example.json"); + + // 6. confirm the WebSocket route is still active + // do a second fetch -> This time it won't be mocked + const fetchResult2 = await page.evaluate(async () => { + const res = await fetch("/example.json"); + return res.json(); + }); + // The real server returns { original: "server-data" } + expect(fetchResult2.original).toBe("server-data"); + + // 7. unrouteAll + await context.unrouteAll(); + }); + + test("should demonstrate routeFromHar usage", async () => { + const harPath = path.join(__dirname, "tmp-test.har"); + + const dynamicHar = HAR_CONTENT.replace( + "http://localhost/har-example.json", + `http://localhost:${serverPort}/har-example.json`, + ); + + fs.writeFileSync(harPath, dynamicHar, "utf-8"); + + const context = stagehand.context; + + await context.routeFromHAR(harPath, { update: false }); + + const page = await context.newPage(); + await page.goto(`http://localhost:${serverPort}/har-example.json`); + + const bodyText = await page.evaluate(() => document.body.innerText); + console.log("HAR-based body text:", bodyText); + expect(bodyText).toContain("harKey"); + expect(bodyText).toContain("harValue"); + + await context.unrouteAll(); + fs.unlinkSync(harPath); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/Errors/apiKeyError.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/Errors/apiKeyError.test.ts new file mode 100644 index 0000000..7c7d9cc --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/Errors/apiKeyError.test.ts @@ -0,0 +1,77 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; +import { z } from "zod/v3"; + +test.describe("API key/LLMClient error", () => { + test("Should confirm that we get an error if we call extract without LLM API key or LLMClient", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + await stagehand.page.goto("https://docs.browserbase.com/introduction"); + + let errorThrown: Error | null = null; + + try { + await stagehand.page.extract({ + instruction: + "From the introduction page, extract the explanation of what Browserbase is.", + schema: z.object({ + stars: z.string().describe("the explanation of what Browserbase is"), + }), + }); + } catch (error) { + errorThrown = error as Error; + } + + expect(errorThrown).toBeInstanceOf(Error); + expect(errorThrown?.message).toContain( + "No LLM API key or LLM Client configured", + ); + + await stagehand.close(); + }); + + test("Should confirm that we get an error if we call act without LLM API key or LLMClient", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + await stagehand.page.goto("https://docs.browserbase.com/introduction"); + + let errorThrown: Error | null = null; + + try { + await stagehand.page.act({ + action: "Click on the 'Quickstart' section", + }); + } catch (error) { + errorThrown = error as Error; + } + + expect(errorThrown).toBeInstanceOf(Error); + expect(errorThrown?.message).toContain( + "No LLM API key or LLM Client configured", + ); + + await stagehand.close(); + }); + + test("Should confirm that we get an error if we call observe without LLM API key or LLMClient", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + await stagehand.page.goto("https://docs.browserbase.com/introduction"); + + let errorThrown: Error | null = null; + + try { + await stagehand.page.observe(); + } catch (error) { + errorThrown = error as Error; + } + + expect(errorThrown).toBeInstanceOf(Error); + expect(errorThrown?.message).toContain( + "No LLM API key or LLM Client configured", + ); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/browserbase/contexts.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/contexts.test.ts new file mode 100644 index 0000000..44e9bd5 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/contexts.test.ts @@ -0,0 +1,149 @@ +import Browserbase from "@browserbasehq/sdk"; +import { expect, test } from "@playwright/test"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; +import { Stagehand } from "@browserbasehq/stagehand"; + +// Configuration +const CONTEXT_TEST_URL = "https://docs.browserbase.com"; +const BROWSERBASE_PROJECT_ID = process.env.BROWSERBASE_PROJECT_ID!; +const BROWSERBASE_API_KEY = process.env.BROWSERBASE_API_KEY!; + +const bb = new Browserbase({ + apiKey: BROWSERBASE_API_KEY, +}); + +// Helper functions +function addHour(date: Date): number { + const SECOND = 1000; + return new Date(date.getTime() + 60 * 60 * 1000).getTime() / SECOND; +} + +async function findCookie(stagehand: Stagehand, name: string) { + const defaultContext = stagehand.context; + const cookies = await defaultContext?.cookies(); + return cookies?.find((cookie) => cookie.name === name); +} + +async function createContext() { + console.log("Creating a new context..."); + const context = await bb.contexts.create({ + projectId: BROWSERBASE_PROJECT_ID, + }); + const contextId = context.id; + console.log(`Context created with ID: ${contextId}`); + return contextId; +} + +async function setRandomCookie(contextId: string, stagehand: Stagehand) { + console.log( + `Populating context ${contextId} during session ${stagehand.browserbaseSessionID}`, + ); + const page = stagehand.page; + + await page.goto(CONTEXT_TEST_URL, { waitUntil: "domcontentloaded" }); + + const now = new Date(); + const testCookieName = `bb_${now.getTime().toString()}`; + const testCookieValue = now.toISOString(); + + await stagehand.context.addCookies([ + { + domain: `.${new URL(CONTEXT_TEST_URL).hostname}`, + expires: addHour(now), + name: testCookieName, + path: "/", + value: testCookieValue, + }, + ]); + + expect(findCookie(stagehand, testCookieName)).toBeDefined(); + console.log(`Set test cookie: ${testCookieName}=${testCookieValue}`); + return { testCookieName, testCookieValue }; +} + +test.describe("Contexts", () => { + test("Persists and re-uses a context", async () => { + let contextId: string; + let testCookieName: string; + let testCookieValue: string; + let stagehand: Stagehand; + + await test.step("Create a context", async () => { + contextId = await createContext(); + }); + + await test.step("Instantiate Stagehand with the context to persist", async () => { + // We will be adding cookies to the context in this session, so we need mark persist=true + stagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + browserbaseSessionCreateParams: { + projectId: BROWSERBASE_PROJECT_ID, + browserSettings: { + context: { + id: contextId, + persist: true, + }, + }, + }, + }); + await stagehand.init(); + }); + + await test.step("Set a random cookie on the page", async () => { + ({ testCookieName } = await setRandomCookie(contextId, stagehand)); + + const page = stagehand.page; + await page.goto("https://www.google.com", { + waitUntil: "domcontentloaded", + }); + await page.goBack(); + }); + + await test.step("Validate cookie persistence between pages", async () => { + const cookie = await findCookie(stagehand, testCookieName); + const found = !!cookie; + expect(found).toBe(true); + console.log("Cookie persisted between pages:", found); + + await stagehand.close(); + // Wait for context to persist + console.log("Waiting for context to persist..."); + await new Promise((resolve) => setTimeout(resolve, 5000)); + }); + + await test.step("Create another session with the same context", async () => { + // We don't need to persist cookies in this session, so we can mark persist=false + const newStagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + browserbaseSessionCreateParams: { + projectId: BROWSERBASE_PROJECT_ID, + browserSettings: { + context: { + id: contextId, + persist: false, + }, + }, + }, + }); + await newStagehand.init(); + console.log( + `Reusing context ${contextId} during session ${newStagehand.browserbaseSessionID}`, + ); + const newPage = newStagehand.page; + await newPage.goto(CONTEXT_TEST_URL, { waitUntil: "domcontentloaded" }); + + const foundCookie = await findCookie(newStagehand, testCookieName); + console.log("Cookie found in new session:", !!foundCookie); + console.log( + "Cookie value matches:", + foundCookie?.value === testCookieValue, + ); + + await newStagehand.close(); + }); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/browserbase/downloads.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/downloads.test.ts new file mode 100644 index 0000000..8260188 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/downloads.test.ts @@ -0,0 +1,131 @@ +import { test, expect } from "@playwright/test"; +import AdmZip from "adm-zip"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; +import { Stagehand } from "@browserbasehq/stagehand"; +import Browserbase from "@browserbasehq/sdk"; + +const downloadRe = /sandstorm-(\d{13})+\.mp3/; +const pdfRe = /sample-(\d{13})+\.pdf/; + +test("Downloads", async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + }); + await stagehand.init(); + const page = stagehand.page; + + const context = stagehand.context; + + const client = await context.newCDPSession(page); + await client.send("Browser.setDownloadBehavior", { + behavior: "allow", + // `downloadPath` gets appended to the browser's default download directory. + // set to "downloads", it ends up being "/app/apps/browser/downloads/". + downloadPath: "downloads", + eventsEnabled: true, + }); + + await page.goto("https://browser-tests-alpha.vercel.app/api/download-test"); + + const [download] = await Promise.all([ + page.waitForEvent("download"), + page.locator("#download").click(), + ]); + + const downloadError = await download.failure(); + + await stagehand.close(); + + if (downloadError !== null) { + throw new Error( + `Download for session ${stagehand.browserbaseSessionID} failed: ${downloadError}`, + ); + } + + await expect(async () => { + const bb = new Browserbase(); + const zipBuffer = await bb.sessions.downloads.list( + stagehand.browserbaseSessionID, + ); + if (!zipBuffer) { + throw new Error( + `Download buffer is empty for session ${stagehand.browserbaseSessionID}`, + ); + } + + const zip = new AdmZip(Buffer.from(await zipBuffer.arrayBuffer())); + const zipEntries = zip.getEntries(); + const mp3Entry = zipEntries.find((entry) => + downloadRe.test(entry.entryName), + ); + + if (!mp3Entry) { + throw new Error( + `Session ${stagehand.browserbaseSessionID} is missing a file matching "${downloadRe.toString()}" in its zip entries: ${JSON.stringify(zipEntries.map((entry) => entry.entryName))}`, + ); + } + + const expectedFileSize = 6137541; + expect(mp3Entry.header.size).toBe(expectedFileSize); + }).toPass({ + timeout: 30_000, + }); +}); + +test("Default download behaviour", async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + }); + await stagehand.init(); + const page = stagehand.page; + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/download-on-click/", + ); + + const [download] = await Promise.all([ + page.waitForEvent("download"), + page.locator("xpath=/html/body/button").click(), + ]); + + const downloadError = await download.failure(); + + await stagehand.close(); + + if (downloadError !== null) { + throw new Error( + `Download for session ${stagehand.browserbaseSessionID} failed: ${downloadError}`, + ); + } + + await expect(async () => { + const bb = new Browserbase(); + const zipBuffer = await bb.sessions.downloads.list( + stagehand.browserbaseSessionID, + ); + if (!zipBuffer) { + throw new Error( + `Download buffer is empty for session ${stagehand.browserbaseSessionID}`, + ); + } + + const zip = new AdmZip(Buffer.from(await zipBuffer.arrayBuffer())); + const zipEntries = zip.getEntries(); + const pdfEntry = zipEntries.find((entry) => pdfRe.test(entry.entryName)); + + if (!pdfEntry) { + throw new Error( + `Session ${stagehand.browserbaseSessionID} is missing a file matching "${pdfRe.toString()}" in its zip entries: ${JSON.stringify(zipEntries.map((entry) => entry.entryName))}`, + ); + } + + const expectedFileSize = 13264; + expect(pdfEntry.header.size).toBe(expectedFileSize); + }).toPass({ + timeout: 30_000, + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/browserbase/sessions.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/sessions.test.ts new file mode 100644 index 0000000..fab5940 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/sessions.test.ts @@ -0,0 +1,69 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; +import Browserbase from "@browserbasehq/sdk"; + +test.describe("Browserbase Sessions", () => { + let browserbase: Browserbase; + let sessionId: string; + let bigStagehand: Stagehand; + + test.beforeAll(async () => { + browserbase = new Browserbase({ + apiKey: process.env.BROWSERBASE_API_KEY, + }); + bigStagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + browserbaseSessionCreateParams: { + projectId: process.env.BROWSERBASE_PROJECT_ID, + keepAlive: true, + }, + }); + await bigStagehand.init(); + await bigStagehand.page.goto( + "https://docs.stagehand.dev/first-steps/introduction", + ); + sessionId = bigStagehand.browserbaseSessionID; + if (!sessionId) { + throw new Error("Failed to get browserbase session ID"); + } + }); + test.afterAll(async () => { + await bigStagehand.close(); + }); + test("resumes a session via sessionId", async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + useAPI: false, + env: "BROWSERBASE", + browserbaseSessionID: sessionId, + }); + await stagehand.init(); + + const page = stagehand.page; + + expect(page.url()).toBe( + "https://docs.stagehand.dev/first-steps/introduction", + ); + }); + test("resumes a session via CDP URL", async () => { + const session = await browserbase.sessions.retrieve(sessionId); + + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "LOCAL", + localBrowserLaunchOptions: { + headless: true, + cdpUrl: session.connectUrl, + }, + }); + await stagehand.init(); + const page = stagehand.page; + + expect(page.url()).toBe( + "https://docs.stagehand.dev/first-steps/introduction", + ); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/browserbase/uploads.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/uploads.test.ts new file mode 100644 index 0000000..281fa8e --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/browserbase/uploads.test.ts @@ -0,0 +1,40 @@ +import { join } from "node:path"; +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("Playwright Upload", () => { + let stagehand: Stagehand; + + test.beforeAll(async () => { + stagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + useAPI: false, + }); + await stagehand.init(); + }); + + test.afterAll(async () => { + await stagehand.close(); + }); + + test("uploads a file", async () => { + const page = stagehand.page; + await page.goto("https://browser-tests-alpha.vercel.app/api/upload-test"); + + const fileInput = page.locator("#fileUpload"); + await fileInput.setInputFiles( + join(__dirname, "../..", "auxiliary", "logo.png"), + ); + + const fileNameSpan = page.locator("#fileName"); + const fileName = await fileNameSpan.innerText(); + + const fileSizeSpan = page.locator("#fileSize"); + const fileSize = Number(await fileSizeSpan.innerText()); + + expect(fileName).toBe("logo.png"); + expect(fileSize).toBeGreaterThan(0); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/local/create.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/local/create.test.ts new file mode 100644 index 0000000..c893bba --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/local/create.test.ts @@ -0,0 +1,239 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import path from "path"; +import fs from "fs"; +import os from "os"; +import type { Cookie } from "@playwright/test"; +import StagehandConfig from "../../stagehand.config"; + +test.describe("Local browser launch options", () => { + test("launches with default options when no localBrowserLaunchOptions provided", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const context = stagehand.context; + expect(context.browser()).toBeDefined(); + expect(context.pages().length).toBe(1); + + await stagehand.close(); + }); + + test("respects custom userDataDir", async () => { + const customUserDataDir = path.join(os.tmpdir(), "custom-user-data"); + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + userDataDir: customUserDataDir, + headless: true, + preserveUserDataDir: true, + }, + }); + await stagehand.init(); + + expect(fs.existsSync(customUserDataDir)).toBeTruthy(); + + await stagehand.close(); + + expect(fs.existsSync(customUserDataDir)).toBeTruthy(); + + // Cleanup + fs.rmSync(customUserDataDir, { recursive: true, force: true }); + }); + + test("cleans up userDataDir by default when preserveUserDataDir is false", async () => { + const customUserDataDir = path.join(os.tmpdir(), "cleanup-user-data"); + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + userDataDir: customUserDataDir, + headless: true, + preserveUserDataDir: false, + }, + }); + await stagehand.init(); + + expect(fs.existsSync(customUserDataDir)).toBeTruthy(); + + await stagehand.close(); + + expect(fs.existsSync(customUserDataDir)).toBeFalsy(); + }); + + test("cleans up userDataDir by default when no preserveUserDataDir flag is provided", async () => { + const customUserDataDir = path.join( + os.tmpdir(), + "default-cleanup-user-data", + ); + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + userDataDir: customUserDataDir, + headless: true, + // No preserveUserDataDir flag provided - should default to cleanup + }, + }); + await stagehand.init(); + + expect(fs.existsSync(customUserDataDir)).toBeTruthy(); + + await stagehand.close(); + + expect(fs.existsSync(customUserDataDir)).toBeFalsy(); + }); + + test("applies custom viewport settings", async () => { + const customViewport = { width: 1920, height: 1080 }; + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + ...StagehandConfig.localBrowserLaunchOptions, + viewport: customViewport, + }, + }); + await stagehand.init(); + + const page = await stagehand.context.newPage(); + const viewport = page.viewportSize(); + + expect(viewport).toEqual(customViewport); + + await stagehand.close(); + }); + + test("applies custom cookies", async () => { + const testCookies: Cookie[] = [ + { + name: "testCookie", + value: "testValue", + domain: "browserbase.github.io", + path: "/", + expires: -1, + httpOnly: false, + secure: false, + sameSite: "Lax" as const, + }, + ]; + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + ...StagehandConfig.localBrowserLaunchOptions, + cookies: testCookies, + }, + }); + await stagehand.init(); + + const page = await stagehand.context.newPage(); + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + const cookies = await stagehand.context.cookies(); + + expect(cookies[0]).toMatchObject( + testCookies[0] as unknown as Record, + ); + + await stagehand.close(); + }); + + test("applies custom geolocation settings", async () => { + const customGeolocation = { + latitude: 40.7128, + longitude: -74.006, + }; + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + ...StagehandConfig.localBrowserLaunchOptions, + geolocation: customGeolocation, + permissions: ["geolocation"], + }, + }); + await stagehand.init(); + + const page = await stagehand.context.newPage(); + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const location = await page.evaluate(() => { + return new Promise((resolve) => { + navigator.geolocation.getCurrentPosition( + (position) => { + resolve({ + latitude: position.coords.latitude, + longitude: position.coords.longitude, + }); + }, + () => resolve(null), + ); + }); + }); + + expect(location).toEqual(customGeolocation); + + await stagehand.close(); + }); + + test("applies custom timezone and locale", async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + ...StagehandConfig.localBrowserLaunchOptions, + locale: "ja-JP", + timezoneId: "Asia/Tokyo", + }, + }); + await stagehand.init(); + + const page = await stagehand.context.newPage(); + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const { locale, timezone } = await page.evaluate(() => ({ + locale: navigator.language, + timezone: Intl.DateTimeFormat().resolvedOptions().timeZone, + })); + + expect(locale).toBe("ja-JP"); + expect(timezone).toBe("Asia/Tokyo"); + + await stagehand.close(); + }); + + test("records video when enabled", async () => { + const videoDir = path.join(os.tmpdir(), "test-videos"); + fs.mkdirSync(videoDir, { recursive: true }); + + const stagehand = new Stagehand({ + ...StagehandConfig, + localBrowserLaunchOptions: { + ...StagehandConfig.localBrowserLaunchOptions, + recordVideo: { + dir: videoDir, + size: { width: 800, height: 600 }, + }, + }, + }); + await stagehand.init(); + + const page = await stagehand.context.newPage(); + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + await stagehand.close(); + + const videos = fs.readdirSync(videoDir); + expect(videos.length).toBeGreaterThan(0); + expect(videos[0]).toMatch(/\.webm$/); + + // Cleanup + fs.rmSync(videoDir, { recursive: true, force: true }); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/local/downloads.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/local/downloads.test.ts new file mode 100644 index 0000000..c36440b --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/local/downloads.test.ts @@ -0,0 +1,105 @@ +import { expect, test } from "@playwright/test"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; +import { Stagehand } from "@browserbasehq/stagehand"; +import { promises as fs } from "fs"; +import path from "path"; + +test("Default download behaviour (local)", async () => { + const downloadsDir: string = path.resolve(process.cwd(), "downloads"); + await fs.rm(downloadsDir, { recursive: true, force: true }); + await fs.mkdir(downloadsDir, { recursive: true }); + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "LOCAL", + }); + await stagehand.init(); + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/download-on-click/", + ); + + const [download] = await Promise.all([ + page.waitForEvent("download"), + page.locator("xpath=/html/body/button").click(), + ]); + if ((await download.failure()) !== null) { + await stagehand.close(); + throw new Error("Local download reported a failure"); + } + + // Wait until Playwright has the real file path (guarantees it’s done) + const downloadPath: string | null = await download.path(); + if (downloadPath === null) { + await stagehand.close(); + throw new Error("Download completed, but path() returned null"); + } + + const expectedFileSize = 13_264; // bytes + const suggested: string = download.suggestedFilename(); + const finalPath: string = path.join(downloadsDir, suggested); + + await expect + .poll( + async () => { + try { + const stat = await fs.stat(finalPath); + return stat.isFile() && stat.size === expectedFileSize; + } catch { + return false; + } + }, + { + message: `Expected "${suggested}" in ${downloadsDir}`, + timeout: 10_000, + }, + ) + .toBe(true); + + const { size } = await fs.stat(finalPath); + expect(size).toBe(expectedFileSize); + + await stagehand.close(); +}); + +const downloadRe = /sandstorm\.mp3/; + +test("Downloads", async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "LOCAL", + }); + await stagehand.init(); + const page = stagehand.page; + + await page.goto("https://browser-tests-alpha.vercel.app/api/download-test"); + + const [download] = await Promise.all([ + page.waitForEvent("download"), + page.locator("#download").click(), + ]); + + const downloadError = await download.failure(); + + if (downloadError !== null) { + throw new Error(`Download failed: ${downloadError}`); + } + + const suggestedFilename = download.suggestedFilename(); + const filePath = path.join(stagehand.downloadsPath, suggestedFilename); + + await stagehand.close(); + + // Verify the download exists and matches expected pattern + expect( + await fs + .access(filePath) + .then(() => true) + .catch(() => false), + ).toBe(true); + expect(suggestedFilename).toMatch(downloadRe); + + // Verify file size + const stats = await fs.stat(filePath); + const expectedFileSize = 6137541; + expect(stats.size).toBe(expectedFileSize); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/addInitScript.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/addInitScript.test.ts new file mode 100644 index 0000000..aff5872 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/addInitScript.test.ts @@ -0,0 +1,70 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - addInitScript", () => { + test("should inject a script before the page loads", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + + await page.addInitScript(() => { + const w = window as typeof window & { + __testInitScriptVar?: string; + }; + w.__testInitScriptVar = "Hello from init script!"; + }); + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const result = await page.evaluate(() => { + const w = window as typeof window & { + __testInitScriptVar?: string; + }; + return w.__testInitScriptVar; + }); + expect(result).toBe("Hello from init script!"); + + await page.goto("https://docs.browserbase.com/"); + const resultAfterNavigation = await page.evaluate(() => { + const w = window as typeof window & { + __testInitScriptVar?: string; + }; + return w.__testInitScriptVar; + }); + expect(resultAfterNavigation).toBe("Hello from init script!"); + + await stagehand.close(); + }); + + test("checks if init scripts are re-added and available even if they've been deleted", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/aigrant/", + ); + + // delete the __stagehandInjected flag, and delete the + // getScrollableElementXpaths function + await page.evaluate(() => { + delete window.getScrollableElementXpaths; + delete window.__stagehandInjected; + }); + + // attempt to call the getScrollableElementXpaths function + // which we previously deleted. page.evaluate should realize + // its been deleted and re-inject it + const xpaths = await page.evaluate(() => { + return window.getScrollableElementXpaths(); + }); + + await stagehand.close(); + // this is the only scrollable element on the page + expect(xpaths).toContain("/html"); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/addRemoveLocatorHandler.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/addRemoveLocatorHandler.test.ts new file mode 100644 index 0000000..86f5eff --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/addRemoveLocatorHandler.test.ts @@ -0,0 +1,97 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - addLocatorHandler and removeLocatorHandler", () => { + // This HTML snippet is reused by both tests. + // The "Sign up to the newsletter" overlay appears after 2 seconds. + // The "No thanks" button hides it. + const overlayHTML = ` + + + + + + + + `; + + test("should use a custom locator handler to dismiss the overlay", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const { page } = stagehand; + + await page.addLocatorHandler( + page.getByText("Sign up to the newsletter"), + async () => { + console.log("Overlay detected. Clicking 'No thanks' to remove it..."); + await page.getByRole("button", { name: "No thanks" }).click(); + }, + ); + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + await page.setContent(overlayHTML); + + await page.waitForTimeout(5000); + + await page.getByRole("button", { name: "Start here" }).click(); + + const isOverlayVisible = await page + .getByText("Sign up to the newsletter") + .isVisible() + .catch(() => false); + + await stagehand.close(); + + expect(isOverlayVisible).toBeFalsy(); + }); + + test("should remove a custom locator handler so overlay stays visible", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const { page } = stagehand; + + const locator = page.getByText("Sign up to the newsletter"); + await page.addLocatorHandler(locator, async () => { + console.log("Overlay detected. Clicking 'No thanks' to remove it..."); + await page.getByRole("button", { name: "No thanks" }).click(); + }); + + await page.removeLocatorHandler(locator); + console.log("Locator handler removed — overlay will not be dismissed now."); + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + await page.setContent(overlayHTML); + + await page.waitForTimeout(5000); + + await page.getByRole("button", { name: "Start here" }).click(); + + const isOverlayVisible = await page + .getByText("Sign up to the newsletter") + .isVisible() + .catch(() => false); + + await stagehand.close(); + expect(isOverlayVisible).toBe(true); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/addTags.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/addTags.test.ts new file mode 100644 index 0000000..41cd89e --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/addTags.test.ts @@ -0,0 +1,79 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - addScriptTag and addStyleTag", () => { + let stagehand: Stagehand; + + test.beforeAll(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterAll(async () => { + await stagehand.close(); + }); + + test("should inject a script tag and have access to the defined function", async () => { + const { page } = stagehand; + + await page.setContent(` + + +

Hello, world!

+ + + `); + + await page.addScriptTag({ + content: ` + window.sayHello = function() { + document.getElementById("greeting").textContent = "Hello from injected script!"; + } + `, + }); + + await page.evaluate(() => { + const w = window as typeof window & { + sayHello?: () => void; + }; + w.sayHello?.(); + }); + + const text = await page.locator("#greeting").textContent(); + expect(text).toBe("Hello from injected script!"); + }); + + test("should inject a style tag and apply styles", async () => { + const { page } = stagehand; + + await page.setContent(` + + +
Some text
+ + + `); + + await page.addStyleTag({ + content: ` + #styledDiv { + color: red; + font-weight: bold; + } + `, + }); + + const color = await page.evaluate(() => { + const el = document.getElementById("styledDiv"); + return window.getComputedStyle(el!).color; + }); + expect(color).toBe("rgb(255, 0, 0)"); + + const fontWeight = await page.evaluate(() => { + const el = document.getElementById("styledDiv"); + return window.getComputedStyle(el!).fontWeight; + }); + expect(["bold", "700"]).toContain(fontWeight); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/bringToFront.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/bringToFront.test.ts new file mode 100644 index 0000000..2698802 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/bringToFront.test.ts @@ -0,0 +1,39 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - bringToFront", () => { + test("should bring a background page to the front and allow further actions", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const { page: page1 } = stagehand; + + const page2 = await stagehand.context.newPage(); + await page2.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + const page2Title = await page2.title(); + console.log("Page2 Title:", page2Title); + + await page1.goto("https://www.google.com"); + const page1TitleBefore = await page1.title(); + console.log("Page1 Title before:", page1TitleBefore); + + await page1.bringToFront(); + + await page1.goto("https://docs.browserbase.com"); + const page1TitleAfter = await page1.title(); + console.log("Page1 Title after:", page1TitleAfter); + + await page2.bringToFront(); + const page2URLBefore = page2.url(); + console.log("Page2 URL before navigation:", page2URLBefore); + + await stagehand.close(); + + expect(page1TitleBefore).toContain("Google"); + expect(page1TitleAfter).toContain("Browserbase"); + expect(page2Title).toContain("Example Domain"); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/content.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/content.test.ts new file mode 100644 index 0000000..9d1920d --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/content.test.ts @@ -0,0 +1,20 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - content", () => { + test("should retrieve the full HTML content of the page", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + const html = await page.content(); + expect(html).toContain("Example Domain"); + expect(html).toContain("

Example Domain

"); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/evaluate.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/evaluate.test.ts new file mode 100644 index 0000000..9d9641d --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/evaluate.test.ts @@ -0,0 +1,33 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - JavaScript Evaluation", () => { + test("can evaluate JavaScript in the page context", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const sum = await page.evaluate(() => 2 + 2); + expect(sum).toBe(4); + + const pageTitle = await page.evaluate(() => document.title); + expect(pageTitle).toMatch(/example/i); + + const obj = await page.evaluate(() => { + return { + message: "Hello from the browser", + userAgent: navigator.userAgent, + }; + }); + expect(obj).toHaveProperty("message", "Hello from the browser"); + expect(obj.userAgent).toBeDefined(); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/expose.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/expose.test.ts new file mode 100644 index 0000000..9f20d00 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/expose.test.ts @@ -0,0 +1,63 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - evaluateHandle, exposeBinding, exposeFunction", () => { + let stagehand: Stagehand; + + test.beforeAll(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterAll(async () => { + await stagehand.close(); + }); + + test("demonstrates evaluateHandle, exposeBinding, and exposeFunction", async () => { + const { page } = stagehand; + + await page.setContent(` + + +
Initial Text
+ + + `); + + const divHandle = await page.evaluateHandle(() => { + return document.getElementById("myDiv"); + }); + await divHandle.evaluate((div, newText) => { + div.textContent = newText; + }, "Text updated via evaluateHandle"); + + const text = await page.locator("#myDiv").textContent(); + expect(text).toBe("Text updated via evaluateHandle"); + + await page.exposeBinding("myBinding", async (source, arg: string) => { + console.log("myBinding called from page with arg:", arg); + return `Node responded with: I got your message: "${arg}"`; + }); + + const responseFromBinding = await page.evaluate(async () => { + const w = window as typeof window & { + myBinding?: (arg: string) => Promise; + }; + return w.myBinding?.("Hello from the browser"); + }); + expect(responseFromBinding).toMatch(/I got your message/); + + await page.exposeFunction("addNumbers", (a: number, b: number) => { + return a + b; + }); + + const sum = await page.evaluate(async () => { + const w = window as typeof window & { + addNumbers?: (a: number, b: number) => number; + }; + return w.addNumbers?.(3, 7); + }); + expect(sum).toBe(10); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/frames.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/frames.test.ts new file mode 100644 index 0000000..2e4d80d --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/frames.test.ts @@ -0,0 +1,66 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - frame operations", () => { + let stagehand: Stagehand; + + test.beforeAll(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterAll(async () => { + await stagehand.close(); + }); + + test("should use page.mainFrame(), page.frames(), page.frame(), and page.frameLocator()", async () => { + const { page } = stagehand; + + await page.setContent(` + + + + + + + + `); + + await page.waitForSelector('iframe[name="frame-one"]'); + await page.waitForSelector('iframe[name="frame-two"]'); + + const frames = page.frames(); + console.log( + "All frames found:", + frames.map((f) => f.name()), + ); + expect(frames).toHaveLength(3); + + const mainFrame = page.mainFrame(); + console.log("Main frame name:", mainFrame.name()); + expect(mainFrame.name()).toBe(""); + + const frameOne = page.frame({ name: "frame-one" }); + expect(frameOne).not.toBeNull(); + + const frameOneText = await frameOne?.locator("h1").textContent(); + expect(frameOneText).toBe("Hello from Frame 1"); + + const frameTwoLocator = page.frameLocator("iframe[name='frame-two']"); + const frameTwoText = await frameTwoLocator.locator("h1").textContent(); + expect(frameTwoText).toBe("Hello from Frame 2"); + + const frameTwo = page.frame({ name: "frame-two" }); + expect(frameTwo).not.toBeNull(); + + const frameTwoTextAgain = await frameTwo?.locator("h1").textContent(); + expect(frameTwoTextAgain).toBe("Hello from Frame 2"); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/getBy.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/getBy.test.ts new file mode 100644 index 0000000..081eb31 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/getBy.test.ts @@ -0,0 +1,50 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - Built-in locators", () => { + let stagehand: Stagehand; + + test.beforeAll(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterAll(async () => { + await stagehand.close(); + }); + + test("demonstrates getByAltText, getByLabel, getByPlaceholder, getByRole, getByTestId, getByText, getByTitle", async () => { + const { page } = stagehand; + await page.setContent(` + + + Profile picture + + + + +
Hello World!
+

This is some descriptive text on the page.

+

Site Title

+ + + `); + const image = page.getByAltText("Profile picture"); + await expect(image).toBeVisible(); + const usernameInput = page.getByLabel("Username"); + await expect(usernameInput).toBeVisible(); + const emailInput = page.getByPlaceholder("Enter your email"); + await expect(emailInput).toBeVisible(); + const signInButton = page.getByRole("button", { name: "Sign in" }); + await expect(signInButton).toBeVisible(); + const greetingDiv = page.getByTestId("greeting"); + await expect(greetingDiv).toHaveText("Hello World!"); + const descriptiveText = page.getByText( + "This is some descriptive text on the page.", + ); + await expect(descriptiveText).toBeVisible(); + const heading = page.getByTitle("A heading for the page"); + await expect(heading).toHaveText("Site Title"); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/livePageProxy.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/livePageProxy.test.ts new file mode 100644 index 0000000..b8408d4 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/livePageProxy.test.ts @@ -0,0 +1,45 @@ +import { expect, test } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - live page proxy", () => { + test("tests that the page URL reflects the URL of the newest opened tab", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/", + ); + await page.locator("body > button").click(); + await new Promise((resolve) => setTimeout(resolve, 1000)); + await page.waitForURL("**/page2.html", { waitUntil: "commit" }); + // await new Promise(resolve => setTimeout(resolve, 1000)); + const currentURL = page.url(); + const expectedURL = + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/page2.html"; + + expect(currentURL).toBe(expectedURL); + + await stagehand.close(); + }); + + test("tests that opening a new tab does not close the old tab", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/", + ); + await page.locator("body > button").click(); + await new Promise((resolve) => setTimeout(resolve, 1000)); + + const expectedNumPages = 2; + const actualNumPages = stagehand.context.pages().length; + + expect(actualNumPages).toBe(expectedNumPages); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/navigation.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/navigation.test.ts new file mode 100644 index 0000000..f00f8b6 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/navigation.test.ts @@ -0,0 +1,32 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - Navigation", () => { + test("should navigate back and forward between pages", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + expect(page.url()).toBe( + "https://browserbase.github.io/stagehand-eval-sites/sites/example/", + ); + + await page.goto("https://docs.browserbase.com/introduction"); + expect(page.url()).toBe("https://docs.browserbase.com/introduction"); + + await page.goBack(); + expect(page.url()).toBe( + "https://browserbase.github.io/stagehand-eval-sites/sites/example/", + ); + + await page.goForward(); + expect(page.url()).toBe("https://docs.browserbase.com/introduction"); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/on.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/on.test.ts new file mode 100644 index 0000000..cc2f0f9 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/on.test.ts @@ -0,0 +1,82 @@ +import { expect, test } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - page.on()", () => { + test("should handle console events", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + const messages: string[] = []; + page.on("console", (msg) => { + messages.push(msg.text()); + }); + + await page.evaluate(() => console.log("Test console log")); + + expect(messages).toContain("Test console log"); + + await stagehand.close(); + }); + + test("should handle dialog events", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + { waitUntil: "commit" }, + ); + + page.on("dialog", async (dialog) => { + expect(dialog.message()).toBe("Test alert"); + await dialog.dismiss(); + }); + + await page.evaluate(() => alert("Test alert")); + + await stagehand.close(); + }); + + test("should handle request and response events", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + { waitUntil: "commit" }, + ); + + const requests: string[] = []; + const responses: string[] = []; + + page.on("request", (request) => { + requests.push(request.url()); + }); + + page.on("response", (response) => { + responses.push(response.url()); + }); + + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + { waitUntil: "commit" }, + ); + + expect(requests).toContain( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + expect(responses).toContain( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + ); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/pageContext.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/pageContext.test.ts new file mode 100644 index 0000000..4495438 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/pageContext.test.ts @@ -0,0 +1,66 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - page.context()", () => { + let stagehand: Stagehand; + + test.beforeEach(async () => { + stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + }); + + test.afterEach(async () => { + if (stagehand) { + try { + await stagehand.close(); + } catch (error) { + console.error("[afterEach] Error during stagehand.close():", error); + } + } else { + console.log("[afterEach] Stagehand was not defined, skipping close()."); + } + }); + + test("should confirm page.context() and stagehand.context share state", async () => { + const page = stagehand.page; + const stagehandContext = stagehand.context; + const pageContext = page.context(); + + await pageContext.addCookies([ + { + name: "stagehandTestCookie", + value: "hello-stagehand", + domain: "browserbase.github.io", + path: "/", + expires: Math.floor(Date.now() / 1000) + 3600, // 1 hour + httpOnly: false, + secure: false, + sameSite: "Lax", + }, + ]); + + const cookies = await stagehandContext.cookies( + "https://browserbase.github.io/stagehand-eval-sites/sites/example/", + ); + + const testCookie = cookies.find((c) => c.name === "stagehandTestCookie"); + expect(testCookie).toBeDefined(); + expect(testCookie?.value).toBe("hello-stagehand"); + + const extraPage = await pageContext.newPage(); + await extraPage.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/example", + { waitUntil: "networkidle" }, + ); + const contextPages = stagehandContext.pages(); + + // The newly created page should be recognized by stagehandContext as well. + const foundExtraPage = contextPages.find( + (p) => + p.url() === + "https://browserbase.github.io/stagehand-eval-sites/sites/example/", + ); + expect(foundExtraPage).toBeDefined(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/reload.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/reload.test.ts new file mode 100644 index 0000000..66caacd --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/reload.test.ts @@ -0,0 +1,40 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - Reload", () => { + test("should reload the page and reset page state", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/"); + + await page.evaluate(() => { + const w = window as typeof window & { + __testReloadMarker?: string; + }; + w.__testReloadMarker = "Hello Reload!"; + }); + + const markerBeforeReload = await page.evaluate(() => { + const w = window as typeof window & { + __testReloadMarker?: string; + }; + return w.__testReloadMarker; + }); + expect(markerBeforeReload).toBe("Hello Reload!"); + + await page.reload(); + + const markerAfterReload = await page.evaluate(() => { + const w = window as typeof window & { + __testReloadMarker?: string; + }; + return w.__testReloadMarker; + }); + expect(markerAfterReload).toBeUndefined(); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/deterministic/tests/page/waitFor.test.ts b/sdk/stagehand-ts/evals/deterministic/tests/page/waitFor.test.ts new file mode 100644 index 0000000..a809a25 --- /dev/null +++ b/sdk/stagehand-ts/evals/deterministic/tests/page/waitFor.test.ts @@ -0,0 +1,165 @@ +import { test, expect } from "@playwright/test"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/evals/deterministic/stagehand.config"; + +test.describe("StagehandPage - waitFor", () => { + test("should wait for an element to become visible", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/introduction"); + const dynamicElement = page.locator( + "div.grid:nth-child(1) > a:nth-child(1) > div:nth-child(1)", + ); + + const isVisibleBefore = await dynamicElement.isVisible(); + expect(isVisibleBefore).toBe(false); + + const clickableElement = page.locator( + "div.not-prose:nth-child(2) > a:nth-child(1) > div:nth-child(1)", + ); + await clickableElement.click(); + + await dynamicElement.waitFor({ state: "visible" }); + + const isVisibleAfter = await dynamicElement.isVisible(); + expect(isVisibleAfter).toBe(true); + + await stagehand.close(); + }); + + test("should wait for an element to be detached", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/introduction"); + + const disappearingElement = page.locator( + "div.not-prose:nth-child(2) > a:nth-child(1) > div:nth-child(1)", + ); + + await disappearingElement.click(); + await disappearingElement.waitFor({ state: "detached" }); + + const isAttachedAfter = await disappearingElement.isVisible(); + expect(isAttachedAfter).toBe(false); + + await stagehand.close(); + }); + + test("should wait for a specific event (waitForEvent)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/introduction"); + + const consolePromise = page.waitForEvent("console"); + await page.evaluate(() => { + console.log("Hello from the browser console!"); + }); + const consoleMessage = await consolePromise; + expect(consoleMessage.text()).toBe("Hello from the browser console!"); + + await stagehand.close(); + }); + + test("should wait for a function to return true (waitForFunction)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/introduction"); + + await page.evaluate(() => { + setTimeout(() => { + const w = window as typeof window & { + __stagehandFlag?: boolean; + }; + w.__stagehandFlag = true; + }, 1000); + }); + + await page.waitForFunction(() => { + const w = window as typeof window & { + __stagehandFlag?: boolean; + }; + return w.__stagehandFlag === true; + }); + + const value = await page.evaluate(() => { + const w = window as typeof window & { + __stagehandFlag?: boolean; + }; + return w.__stagehandFlag; + }); + expect(value).toBe(true); + + await stagehand.close(); + }); + + test("should wait for the load state (waitForLoadState)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/introduction"); + await page.waitForLoadState("networkidle"); + const heroTitle = page.locator("h1"); + await expect(heroTitle).toHaveText(/Documentation/i); + + await stagehand.close(); + }); + + test("should wait for a specific request (waitForRequest)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + const requestPromise = page.waitForRequest((req) => + req.url().includes("mintlify"), + ); + + await page.goto("https://docs.browserbase.com/introduction"); + const matchingRequest = await requestPromise; + expect(matchingRequest.url()).toContain("mintlify"); + + await stagehand.close(); + }); + + test("should wait for a specific response (waitForResponse)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + const responsePromise = page.waitForResponse( + (res) => res.url().includes("introduction") && res.status() === 200, + ); + + await page.goto("https://docs.browserbase.com/introduction"); + const matchingResponse = await responsePromise; + expect(await matchingResponse.text()).toContain("Browserbase"); + + await stagehand.close(); + }); + + test("should wait for a URL (waitForURL)", async () => { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com"); + + const getStartedLink = page.locator( + "div.not-prose:nth-child(3) > a:nth-child(1) > div:nth-child(1)", + ); + await getStartedLink.click(); + + await page.waitForURL(/.*getting-started.*/); + expect(page.url()).toContain("/getting-started"); + + await stagehand.close(); + }); +}); diff --git a/sdk/stagehand-ts/evals/env.ts b/sdk/stagehand-ts/evals/env.ts new file mode 100644 index 0000000..45f877b --- /dev/null +++ b/sdk/stagehand-ts/evals/env.ts @@ -0,0 +1,18 @@ +/** + * Determine the current environment in which the evaluations are running: + * - BROWSERBASE or LOCAL + * + * The environment is read from the EVAL_ENV environment variable. + */ +export const env: "BROWSERBASE" | "LOCAL" = + process.env.EVAL_ENV?.toLowerCase() === "browserbase" + ? "BROWSERBASE" + : "LOCAL"; + +/** + * Enable or disable caching based on the EVAL_ENABLE_CACHING environment variable. + * Caching may improve performance by not re-fetching or re-computing certain results. + * By default, caching is disabled unless explicitly enabled. + */ +export const enableCaching = + process.env.EVAL_ENABLE_CACHING?.toLowerCase() === "true"; diff --git a/sdk/stagehand-ts/evals/evals.config.json b/sdk/stagehand-ts/evals/evals.config.json new file mode 100644 index 0000000..5c76f88 --- /dev/null +++ b/sdk/stagehand-ts/evals/evals.config.json @@ -0,0 +1,556 @@ +{ + "defaults": { + "env": "browserbase", + "trials": 1, + "concurrency": 20, + "provider": null, + "model": null, + "api": false + }, + "benchmarks": { + "webbench": { + "limit": 25, + "filters": ["difficulty", "category", "use_hitl"] + }, + "gaia": { + "limit": 25, + "filters": ["level"] + }, + "webvoyager": { + "limit": 25 + }, + "osworld": { + "limit": 25, + "filters": ["source", "evaluation_type"], + "timeout": 60000 + }, + "onlineMind2Web": { + "limit": 25 + } + }, + "tasks": [ + { + "name": "history", + "categories": ["combination"] + }, + { + "name": "expect_act_timeout", + "categories": ["regression"] + }, + { + "name": "extract_repo_name", + "categories": ["extract"] + }, + { + "name": "amazon_add_to_cart", + "categories": ["act"] + }, + { + "name": "instructions", + "categories": ["regression", "combination"] + }, + { + "name": "bidnet", + "categories": ["act"] + }, + { + "name": "ionwave", + "categories": ["act", "regression"] + }, + { + "name": "nonsense_action", + "categories": ["act"] + }, + { + "name": "peeler_simple", + "categories": ["act"] + }, + { + "name": "simple_google_search", + "categories": ["act"] + }, + { + "name": "vantechjournal", + "categories": ["act"] + }, + { + "name": "wikipedia", + "categories": ["act"] + }, + + { + "name": "allrecipes", + "categories": ["combination"] + }, + { + "name": "arxiv", + "categories": ["combination"] + }, + { + "name": "extract_collaborators", + "categories": ["combination"] + }, + { + "name": "extract_github_commits", + "categories": ["combination"] + }, + { + "name": "imdb_movie_details", + "categories": ["combination"] + }, + { + "name": "peeler_complex", + "categories": ["combination"] + }, + { + "name": "sciquest", + "categories": ["combination"] + }, + { + "name": "wichita", + "categories": ["combination", "regression"] + }, + { + "name": "hn_aisdk", + "categories": ["llm_clients"] + }, + { + "name": "hn_langchain", + "categories": ["llm_clients"] + }, + { + "name": "hn_customOpenAI", + "categories": ["llm_clients"] + }, + { + "name": "apple", + "categories": ["experimental"] + }, + { + "name": "combination_sauce", + "categories": ["experimental"] + }, + { + "name": "costar", + "categories": ["experimental"] + }, + { + "name": "extract_aigrant_companies", + "categories": ["regression"] + }, + { + "name": "extract_capacitor_info", + "categories": ["experimental"] + }, + { + "name": "extract_partners", + "categories": ["experimental"] + }, + { + "name": "extract_press_releases", + "categories": ["experimental"] + }, + { + "name": "extract_snowshoeing_destinations", + "categories": ["experimental"] + }, + { + "name": "homedepot", + "categories": ["experimental"] + }, + { + "name": "rakuten_jp", + "categories": ["experimental"] + }, + { + "name": "stock_x", + "categories": ["experimental"] + }, + { + "name": "ted_talk", + "categories": ["experimental"] + }, + + { + "name": "extract_baptist_health", + "categories": ["extract"] + }, + { + "name": "extract_github_stars", + "categories": ["extract"] + }, + { + "name": "extract_memorial_healthcare", + "categories": ["extract", "regression"] + }, + { + "name": "extract_nhl_stats", + "categories": ["extract"] + }, + { + "name": "extract_professional_info", + "categories": ["extract"] + }, + { + "name": "extract_csa", + "categories": ["extract"] + }, + { + "name": "extract_resistor_info", + "categories": ["extract"] + }, + { + "name": "extract_rockauto", + "categories": ["extract"] + }, + { + "name": "extract_staff_members", + "categories": ["extract"] + }, + + { + "name": "ionwave_observe", + "categories": ["observe"] + }, + { + "name": "panamcs", + "categories": ["observe"] + }, + { + "name": "vanta_h", + "categories": ["experimental"] + }, + { + "name": "extract_area_codes", + "categories": ["extract"] + }, + { + "name": "extract_public_notices", + "categories": ["extract"] + }, + { + "name": "extract_jstor_news", + "categories": ["extract"] + }, + { + "name": "extract_apartments", + "categories": ["extract"] + }, + { + "name": "extract_zillow", + "categories": ["extract"] + }, + { + "name": "observe_github", + "categories": ["observe", "regression"] + }, + { + "name": "observe_vantechjournal", + "categories": ["observe", "regression"] + }, + { + "name": "observe_amazon_add_to_cart", + "categories": ["observe"] + }, + { + "name": "observe_simple_google_search", + "categories": ["observe"] + }, + { + "name": "observe_yc_startup", + "categories": ["observe"] + }, + { + "name": "observe_taxes", + "categories": ["observe"] + }, + { + "name": "observe_iframes1", + "categories": ["regression", "observe"] + }, + { + "name": "observe_iframes2", + "categories": ["regression", "observe"] + }, + { + "name": "extract_hamilton_weather", + "categories": ["targeted_extract", "regression"] + }, + { + "name": "extract_regulations_table", + "categories": ["targeted_extract"] + }, + { + "name": "extract_recipe", + "categories": ["targeted_extract"] + }, + { + "name": "extract_aigrant_targeted", + "categories": ["targeted_extract"] + }, + { + "name": "extract_aigrant_targeted_2", + "categories": ["targeted_extract"] + }, + { + "name": "extract_geniusee", + "categories": ["targeted_extract"] + }, + { + "name": "extract_geniusee_2", + "categories": ["targeted_extract"] + }, + { + "name": "scroll_50", + "categories": ["regression", "act"] + }, + { + "name": "scroll_75", + "categories": ["regression", "act"] + }, + { + "name": "nextChunk", + "categories": ["regression", "act"] + }, + { + "name": "prevChunk", + "categories": ["regression", "act"] + }, + { + "name": "google_flights", + "categories": ["act"] + }, + { + "name": "extract_jfk_links", + "categories": ["extract"] + }, + { + "name": "extract_single_link", + "categories": ["extract"] + }, + { + "name": "dropdown", + "categories": ["act"] + }, + { + "name": "radio_btn", + "categories": ["act"] + }, + { + "name": "checkboxes", + "categories": ["act"] + }, + { + "name": "agent/iframe_form", + "categories": ["agent"] + }, + { + "name": "agent/iframe_form_multiple", + "categories": ["agent"] + }, + { + "name": "agent/google_flights", + "categories": ["agent"] + }, + { + "name": "agent/github_react_version", + "categories": ["agent"] + }, + { + "name": "agent/steam_games", + "categories": ["agent"] + }, + { + "name": "agent/ubereats", + "categories": ["agent"] + }, + { + "name": "agent/kith", + "categories": ["agent"] + }, + { + "name": "agent/apple_tv", + "categories": ["agent"] + }, + { + "name": "agent/apple_trade_in", + "categories": ["agent"] + }, + { + "name": "agent/arxiv_gpt_report", + "categories": ["agent"] + }, + { + "name": "agent/sf_library_card", + "categories": ["agent"] + }, + { + "name": "agent/sf_library_card_multiple", + "categories": ["agent"] + }, + { + "name": "agent/hugging_face", + "categories": ["agent"] + }, + { + "name": "agent/google_maps_3", + "categories": ["agent"] + }, + { + "name": "login", + "categories": ["act", "regression"] + }, + { + "name": "iframe_hn", + "categories": ["extract"] + }, + { + "name": "iframe_same_proc", + "categories": ["act"] + }, + { + "name": "iframe_form_filling", + "categories": ["act"] + }, + { + "name": "iframes_nested", + "categories": ["act"] + }, + { + "name": "no_js_click", + "categories": ["act", "regression"] + }, + { + "name": "tab_handling", + "categories": ["act"] + }, + { + "name": "agent/kayak", + "categories": ["agent"] + }, + { + "name": "multi_tab", + "categories": ["act"] + }, + { + "name": "shadow_dom", + "categories": ["act"] + }, + { + "name": "os_dropdown", + "categories": ["act"] + }, + { + "name": "custom_dropdown", + "categories": ["act"] + }, + { + "name": "hidden_input_dropdown", + "categories": ["act"] + }, + { + "name": "nested_iframes_2", + "categories": ["act"] + }, + { + "name": "heal_scroll_50", + "categories": ["act"] + }, + { + "name": "heal_simple_google_search", + "categories": ["regression", "act"] + }, + { + "name": "heal_custom_dropdown", + "categories": ["act"] + }, + { + "name": "agent/trivago", + "categories": ["agent"] + }, + { + "name": "agent/google_maps", + "categories": ["agent"] + }, + { + "name": "agent/google_maps_2", + "categories": ["agent"] + }, + { + "name": "agent/youtube", + "categories": ["agent"] + }, + { + "name": "agent/sign_in", + "categories": ["agent"] + }, + { + "name": "osr_in_oopif", + "categories": ["act"] + }, + { + "name": "csr_in_oopif", + "categories": ["act"] + }, + { + "name": "csr_in_spif", + "categories": ["act"] + }, + { + "name": "csr_in_spif", + "categories": ["act"] + }, + { + "name": "spif_in_osr", + "categories": ["act"] + }, + { + "name": "oopif_in_osr", + "categories": ["act"] + }, + { + "name": "spif_in_csr", + "categories": ["act"] + }, + { + "name": "oopif_in_csr", + "categories": ["act"] + }, + { + "name": "osr_in_spif", + "categories": ["act"] + }, + { + "name": "namespace_xpath", + "categories": ["act"] + }, + { + "name": "iframe_scroll", + "categories": ["act"] + }, + { + "name": "agent/gaia", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/webvoyager", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/onlineMind2Web", + "categories": ["external_agent_benchmarks"] + }, + { + "name": "agent/nba_trades", + "categories": ["agent"] + }, + { + "name": "agent/github", + "categories": ["agent"] + }, + { + "name": "agent/all_recipes", + "categories": ["agent"] + } + ] +} diff --git a/sdk/stagehand-ts/evals/evaluator.ts b/sdk/stagehand-ts/evals/evaluator.ts new file mode 100644 index 0000000..2027831 --- /dev/null +++ b/sdk/stagehand-ts/evals/evaluator.ts @@ -0,0 +1,357 @@ +/** + * This class is responsible for evaluating the result of an agentic task. + * The first version includes a VLM evaluator specifically prompted to evaluate the state of a task + * usually represented as a screenshot. + * The evaluator will reply with YES or NO given the state of the provided task. + */ + +import { + AvailableModel, + ClientOptions, + Stagehand, +} from "@browserbasehq/stagehand"; +import dotenv from "dotenv"; +import { + EvaluateOptions, + BatchAskOptions, + EvaluationResult, +} from "@/types/evaluator"; +import { LLMParsedResponse } from "@/lib/inference"; +import { LLMResponse } from "@/lib/llm/LLMClient"; +import { LogLine } from "@/types/log"; +import { z } from "zod"; +import { imageResize } from "./utils/imageUtils"; + +dotenv.config(); + +const EvaluationSchema = z.object({ + evaluation: z.enum(["YES", "NO"]), + reasoning: z.string(), +}); + +const BatchEvaluationSchema = z.array(EvaluationSchema); + +export class Evaluator { + private stagehand: Stagehand; + private modelName: AvailableModel; + private modelClientOptions: ClientOptions | { apiKey: string }; + private silentLogger: (message: LogLine) => void; + + constructor( + stagehand: Stagehand, + modelName?: AvailableModel, + modelClientOptions?: ClientOptions, + ) { + this.stagehand = stagehand; + this.modelName = modelName || "google/gemini-2.5-flash"; + this.modelClientOptions = modelClientOptions || { + apiKey: process.env.GEMINI_API_KEY || "", + }; + } + + async ask(options: EvaluateOptions): Promise { + const { + question, + answer, + screenshot = true, + systemPrompt, + screenshotDelayMs = 250, + agentReasoning, + } = options; + if (!question) { + throw new Error("Question cannot be an empty string"); + } + if (!answer && !screenshot) { + throw new Error("Either answer (text) or screenshot must be provided"); + } + + // Handle multiple screenshots case + if (Array.isArray(screenshot)) { + return this._evaluateWithMultipleScreenshots({ + question, + screenshots: screenshot, + systemPrompt, + agentReasoning, + }); + } + + // Single screenshot case (existing logic) + const defaultSystemPrompt = `You are an expert evaluator that confidently returns YES or NO based on if the original goal was achieved. You have access to ${screenshot ? "a screenshot" : "the agents reasoning and actions throughout the task"} that you can use to evaluate the tasks completion. Provide detailed reasoning for your answer. + Today's date is ${new Date().toLocaleDateString()}`; + + await new Promise((resolve) => setTimeout(resolve, screenshotDelayMs)); + let imageBuffer: Buffer; + if (screenshot) { + imageBuffer = await this.stagehand.page.screenshot(); + } + const llmClient = this.stagehand.llmProvider.getClient( + this.modelName, + this.modelClientOptions, + ); + + const response = await llmClient.createChatCompletion< + LLMParsedResponse + >({ + logger: this.silentLogger, + options: { + messages: [ + { role: "system", content: systemPrompt || defaultSystemPrompt }, + { + role: "user", + content: [ + { + type: "text", + text: agentReasoning + ? `Question: ${question}\n\nAgent's reasoning and actions taken:\n${agentReasoning}` + : question, + }, + ...(screenshot + ? [ + { + type: "image_url", + image_url: { + url: `data:image/jpeg;base64,${imageBuffer.toString("base64")}`, + }, + }, + ] + : []), + ...(answer + ? [ + { + type: "text", + text: `the answer is ${answer}`, + }, + ] + : []), + ], + }, + ], + response_model: { + name: "EvaluationResult", + schema: EvaluationSchema, + }, + // temperature: 1, + }, + }); + + try { + const result = response.data as unknown as z.infer< + typeof EvaluationSchema + >; + return { evaluation: result.evaluation, reasoning: result.reasoning }; + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : String(error); + return { + evaluation: "INVALID" as const, + reasoning: `Failed to get structured response: ${errorMessage}`, + }; + } + } + + /** + * Evaluates multiple questions with optional answers and/or screenshot. + * Similar to ask() but processes multiple questions in a single call. + * Returns an array of evaluation results. + * + * @param options - The options for batch evaluation + * @returns A promise that resolves to an array of EvaluationResults + */ + async batchAsk(options: BatchAskOptions): Promise { + const { + questions, + screenshot = true, + systemPrompt = `You are an expert evaluator that confidently returns YES or NO for each question given the state of a task based on the original goal. You have access to ${screenshot ? "a screenshot" : "the agents reasoning and actions throughout the task"} that you can use to evaluate the tasks completion. Provide detailed reasoning for your answer. + Today's date is ${new Date().toLocaleDateString()}`, + screenshotDelayMs = 1000, + } = options; + + // Validate inputs + if (!questions || questions.length === 0) { + throw new Error("Questions array cannot be empty"); + } + + for (const item of questions) { + if (!item.question) { + throw new Error("Question cannot be an empty string"); + } + if (!item.answer && !screenshot) { + throw new Error( + "Either answer (text) or screenshot must be provided for each question", + ); + } + } + + // Wait for the specified delay before taking screenshot + await new Promise((resolve) => setTimeout(resolve, screenshotDelayMs)); + + let imageBuffer: Buffer; + if (screenshot) { + imageBuffer = await this.stagehand.page.screenshot(); + } + + // Get the LLM client with our preferred model + const llmClient = this.stagehand.llmProvider.getClient( + this.modelName, + this.modelClientOptions, + ); + + // Format all questions with their optional answers + const formattedQuestions = questions + .map((item, i) => { + let text = `${i + 1}. ${item.question}`; + if (item.answer) { + text += `\n Answer: ${item.answer}`; + } + return text; + }) + .join("\n\n"); + + // Use the model-specific LLM client to evaluate + const response = await llmClient.createChatCompletion< + LLMParsedResponse + >({ + logger: this.silentLogger, + options: { + messages: [ + { + role: "system", + content: `${systemPrompt}\n\nYou will be given multiple questions${screenshot ? " with a screenshot" : ""}. ${questions.some((q) => q.answer) ? "Some questions include answers to evaluate." : ""} Answer each question by returning an object in the specified JSON format. Return a single JSON array containing one object for each question in the order they were asked.`, + }, + { + role: "user", + content: [ + { type: "text", text: formattedQuestions }, + ...(screenshot + ? [ + { + type: "image_url", + image_url: { + url: `data:image/jpeg;base64,${imageBuffer.toString("base64")}`, + }, + }, + ] + : []), + ], + }, + ], + response_model: { + name: "BatchEvaluationResult", + schema: BatchEvaluationSchema, + }, + // temperature: 1, + }, + }); + + try { + const results = response.data as unknown as z.infer< + typeof BatchEvaluationSchema + >; + return results.map((r) => ({ + evaluation: r.evaluation, + reasoning: r.reasoning, + })); + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : String(error); + return questions.map(() => ({ + evaluation: "INVALID" as const, + reasoning: `Failed to get structured response: ${errorMessage}`, + })); + } + } + + /** + * Private method to evaluate with multiple screenshots + */ + private async _evaluateWithMultipleScreenshots(options: { + question: string; + screenshots: Buffer[]; + systemPrompt?: string; + agentReasoning?: string; + }): Promise { + const { + question, + screenshots, + agentReasoning, + systemPrompt = `You are an expert evaluator that confidently returns YES or NO given a question and multiple screenshots showing the progression of a task. + ${agentReasoning ? "You also have access to the agent's detailed reasoning and thought process throughout the task." : ""} + Analyze ALL screenshots to understand the complete journey. Look for evidence of task completion across all screenshots, not just the last one. + Success criteria may appear at different points in the sequence (confirmation messages, intermediate states, etc). + ${agentReasoning ? "The agent's reasoning provides crucial context about what actions were attempted, what was observed, and the decision-making process. Use this alongside the visual evidence to make a comprehensive evaluation." : ""} + Today's date is ${new Date().toLocaleDateString()}`, + } = options; + + if (!question) { + throw new Error("Question cannot be an empty string"); + } + + if (!screenshots || screenshots.length === 0) { + throw new Error("At least one screenshot must be provided"); + } + + const llmClient = this.stagehand.llmProvider.getClient( + this.modelName, + this.modelClientOptions, + ); + + const lastScreenshot = await this.stagehand.page.screenshot(); + + const allScreenshots = [...screenshots, lastScreenshot]; + //Downsize screenshots: + const downsizedScreenshots = await Promise.all( + allScreenshots.map(async (screenshot) => { + return await imageResize(screenshot, 0.7); + }), + ); + + const imageContents = downsizedScreenshots.map((screenshot) => ({ + type: "image_url" as const, + image_url: { + url: `data:image/png;base64,${screenshot.toString("base64")}`, + }, + })); + + const response = await llmClient.createChatCompletion< + LLMParsedResponse + >({ + logger: this.stagehand.logger, + options: { + messages: [ + { role: "system", content: systemPrompt }, + { + role: "user", + content: [ + { + type: "text", + text: agentReasoning + ? `Question: ${question}\n\nAgent's reasoning and actions throughout the task:\n${agentReasoning}\n\nI'm providing ${screenshots.length} screenshots showing the progression of the task. Please analyze both the agent's reasoning and all screenshots to determine if the task was completed successfully.` + : `${question}\n\nI'm providing ${screenshots.length} screenshots showing the progression of the task. Please analyze all of them to determine if the task was completed successfully.`, + }, + ...imageContents, + ], + }, + ], + response_model: { + name: "EvaluationResult", + schema: EvaluationSchema, + }, + // temperature: 1, + }, + }); + + try { + const result = response.data as unknown as z.infer< + typeof EvaluationSchema + >; + return { evaluation: result.evaluation, reasoning: result.reasoning }; + } catch (error) { + const errorMessage = + error instanceof Error ? error.message : String(error); + return { + evaluation: "INVALID" as const, + reasoning: `Failed to get structured response: ${errorMessage}`, + }; + } + } +} diff --git a/sdk/stagehand-ts/evals/index-parallel.eval.ts b/sdk/stagehand-ts/evals/index-parallel.eval.ts new file mode 100644 index 0000000..31bb956 --- /dev/null +++ b/sdk/stagehand-ts/evals/index-parallel.eval.ts @@ -0,0 +1,277 @@ +// /** +// * Multi-process version of the evaluation runner using Worker Threads +// * This provides true parallelism by running tasks in separate V8 isolates +// */ +// import { Worker } from "worker_threads"; +// import path from "path"; +// import process from "process"; +// import os from "os"; +// import { +// DEFAULT_EVAL_CATEGORIES, +// filterByCategory, +// filterByEvalName, +// } from "./args"; +// import { generateExperimentName } from "./utils"; +// import { tasksByName, tasksConfig, getModelList } from "./taskConfig"; +// import { Testcase } from "@/types/evals"; +// import { env } from "./env"; +// import dotenv from "dotenv"; +// import { generateSummary } from "./core/summary"; +// import { buildGAIATestcases } from "./suites/gaia"; +// import { buildWebVoyagerTestcases } from "./suites/webvoyager"; +// import { buildOnlineMind2WebTestcases } from "./suites/onlineMind2Web"; + +// dotenv.config(); + +// // Use CPU count for max workers, with override from env +// const MAX_WORKERS = process.env.EVAL_MAX_WORKERS +// ? parseInt(process.env.EVAL_MAX_WORKERS, 10) +// : os.cpus().length; + +// const TRIAL_COUNT = process.env.EVAL_TRIAL_COUNT +// ? parseInt(process.env.EVAL_TRIAL_COUNT, 10) +// : 3; + +// const USE_API: boolean = (process.env.USE_API ?? "").toLowerCase() === "true"; + +// console.log(`Running with ${MAX_WORKERS} worker processes`); + +// function runTaskInWorker(testcase: Testcase): Promise { +// return new Promise((resolve, reject) => { +// const worker = new Worker(path.join(__dirname, "worker.ts"), { +// workerData: { +// input: testcase.input, +// USE_API, +// }, +// // Use ts-node to run TypeScript directly in worker +// execArgv: [...process.execArgv, "-r", "ts-node/register"], +// }); + +// worker.on("message", (msg) => { +// if (msg.success) { +// console.log(`✅ ${testcase.input.name}: Passed`); +// resolve(msg.result); +// } else { +// console.log(`❌ ${testcase.input.name}: Failed`); +// resolve({ +// _success: false, +// error: msg.error, +// logs: msg.error.logs || [], +// }); +// } +// }); + +// worker.on("error", (error) => { +// console.error(`❌ ${testcase.input.name}: Worker error - ${error}`); +// reject(error); +// }); + +// worker.on("exit", (code) => { +// if (code !== 0) { +// reject(new Error(`Worker stopped with exit code ${code}`)); +// } +// }); +// }); +// } + +// async function runWithWorkerPool(testcases: Testcase[]) { +// const results: any[] = []; +// const queue = [...testcases]; +// const activeWorkers = new Map>(); + +// // Process queue with limited concurrency +// while (queue.length > 0 || activeWorkers.size > 0) { +// // Start new workers up to the limit +// while (activeWorkers.size < MAX_WORKERS && queue.length > 0) { +// const testcase = queue.shift()!; +// const workerId = Date.now() + Math.random(); + +// const workerPromise = runTaskInWorker(testcase) +// .then((result) => { +// results.push({ +// input: testcase.input, +// output: result, +// name: testcase.input.name, +// score: result._success ? 1 : 0, +// }); +// }) +// .catch((error) => { +// console.error(`Worker error for ${testcase.input.name}:`, error); +// results.push({ +// input: testcase.input, +// output: { _success: false, error: error.message }, +// name: testcase.input.name, +// score: 0, +// }); +// }) +// .finally(() => { +// activeWorkers.delete(workerId); +// }); + +// activeWorkers.set(workerId, workerPromise); +// } + +// // Wait for at least one worker to complete +// if (activeWorkers.size > 0) { +// await Promise.race(activeWorkers.values()); +// } +// } + +// return results; +// } + +// const generateFilteredTestcases = (): Testcase[] => { +// let taskNamesToRun: string[]; +// let effectiveCategory: string | null = filterByCategory; + +// if (filterByEvalName) { +// taskNamesToRun = [filterByEvalName]; +// const taskCategories = tasksByName[filterByEvalName]?.categories || []; +// if ( +// taskCategories.length === 1 && +// (taskCategories[0] === "agent" || +// taskCategories[0] === "external_agent_benchmarks") +// ) { +// effectiveCategory = taskCategories[0]; +// console.log( +// `Task ${filterByEvalName} is in ${taskCategories[0]} category, using agent models.`, +// ); +// } +// } else if (filterByCategory) { +// taskNamesToRun = Object.keys(tasksByName).filter((name) => +// tasksByName[name].categories.includes(filterByCategory!), +// ); +// } else { +// taskNamesToRun = Object.keys(tasksByName).filter((name) => +// DEFAULT_EVAL_CATEGORIES.some((category) => +// tasksByName[name].categories.includes(category), +// ), +// ); +// } + +// const currentModels = getModelList(effectiveCategory); +// console.log( +// `Using models for this run (${effectiveCategory || "default"}):`, +// currentModels, +// ); + +// const datasetFilter = process.env.EVAL_DATASET; +// const isGAIATaskIncluded = taskNamesToRun.includes("agent/gaia"); +// const isWebVoyagerTaskIncluded = taskNamesToRun.includes("agent/webvoyager"); +// const isOnlineMind2WebTaskIncluded = taskNamesToRun.includes( +// "agent/onlineMind2Web", +// ); + +// let allTestcases: Testcase[] = []; + +// if (isGAIATaskIncluded && (!datasetFilter || datasetFilter === "gaia")) { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/gaia"); +// allTestcases.push(...buildGAIATestcases(currentModels)); +// } else if (isGAIATaskIncluded && datasetFilter && datasetFilter !== "gaia") { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/gaia"); +// } + +// if ( +// isWebVoyagerTaskIncluded && +// (!datasetFilter || datasetFilter === "webvoyager") +// ) { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/webvoyager"); +// allTestcases.push(...buildWebVoyagerTestcases(currentModels)); +// } else if ( +// isWebVoyagerTaskIncluded && +// datasetFilter && +// datasetFilter !== "webvoyager" +// ) { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/webvoyager"); +// } + +// if ( +// isOnlineMind2WebTaskIncluded && +// (!datasetFilter || datasetFilter === "onlinemind2web") +// ) { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/onlineMind2Web"); +// allTestcases.push(...buildOnlineMind2WebTestcases(currentModels)); +// } else if ( +// isOnlineMind2WebTaskIncluded && +// datasetFilter && +// datasetFilter !== "onlinemind2web" +// ) { +// taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/onlineMind2Web"); +// } + +// const regularTestcases = currentModels.flatMap((model) => +// taskNamesToRun.map((testName) => ({ +// input: { name: testName, modelName: model }, +// name: testName, +// tags: [ +// model, +// testName, +// ...(tasksConfig.find((t) => t.name === testName)?.categories || []).map( +// (x) => `category/${x}`, +// ), +// ], +// metadata: { +// model: model, +// test: testName, +// }, +// expected: true, +// })), +// ); + +// allTestcases = [...allTestcases, ...regularTestcases]; + +// if (filterByCategory) { +// allTestcases = allTestcases.filter((testcase) => +// tasksByName[testcase.name].categories.includes(filterByCategory!), +// ); +// } + +// if (env === "BROWSERBASE") { +// allTestcases = allTestcases.filter( +// (testcase) => !["peeler_simple", "stock_x"].includes(testcase.name), +// ); +// } + +// console.log( +// "Final test cases to run:", +// allTestcases +// .map( +// (t, i) => +// `${i}: ${t.name} (${t.input.modelName}): ${tasksByName[t.name].categories}`, +// ) +// .join("\n"), +// ); + +// return allTestcases; +// }; + +// (async () => { +// const experimentName: string = generateExperimentName({ +// evalName: filterByEvalName || undefined, +// category: filterByCategory || undefined, +// environment: env, +// }); + +// try { +// const testcases = generateFilteredTestcases(); + +// // Handle trials by duplicating testcases +// const testcasesWithTrials = []; +// for (let trial = 0; trial < TRIAL_COUNT; trial++) { +// testcasesWithTrials.push(...testcases); +// } + +// console.log( +// `Running ${testcasesWithTrials.length} total test cases (${testcases.length} unique × ${TRIAL_COUNT} trials)`, +// ); + +// const results = await runWithWorkerPool(testcasesWithTrials); + +// await generateSummary(results, experimentName); + +// console.log("Evaluation complete!"); +// } catch (error) { +// console.error("Error during evaluation run:", error); +// process.exit(1); +// } +// })(); diff --git a/sdk/stagehand-ts/evals/index.eval.ts b/sdk/stagehand-ts/evals/index.eval.ts new file mode 100644 index 0000000..f9c1bfc --- /dev/null +++ b/sdk/stagehand-ts/evals/index.eval.ts @@ -0,0 +1,492 @@ +/** + * This script orchestrates the running of evaluations against a set of tasks. + * It uses Braintrust to run multiple testcases (each testcase representing a + * given task-model combination) and then aggregates the results, producing + * a summary of passes, failures, and categorized success rates. + * + * Overview: + * - Reads a configuration file `evals.config.json` to determine what tasks (evaluations) + * are available and which categories they belong to. + * - Supports filtering which tasks to run either by evaluation category or by specific task name. + * - Supports multiple models, defaulting to certain sets of models depending on the category. + * - Runs each selected task against each selected model in parallel, collecting results. + * - Saves a summary of the evaluation results to `eval-summary.json`. + */ +import path from "path"; +import process from "process"; +import { + DEFAULT_EVAL_CATEGORIES, + filterByCategory, + filterByEvalName, +} from "./args"; +import { generateExperimentName } from "./utils"; +import { exactMatch, errorMatch } from "./scoring"; +import { tasksByName, tasksConfig, getModelList } from "./taskConfig"; +import { Eval, wrapAISDKModel, wrapOpenAI } from "braintrust"; +import { + SummaryResult, + Testcase, + EvalInput, + ErrorType, + EvalOutput, +} from "@/types/evals"; +import { EvalLogger } from "./logger"; +import { AvailableModel, LLMClient } from "@browserbasehq/stagehand"; +import { env } from "./env"; +import dotenv from "dotenv"; +import { StagehandEvalError } from "@/types/stagehandErrors"; +import { CustomOpenAIClient } from "@/examples/external_clients/customOpenAI"; +import OpenAI from "openai"; +import { initStagehand } from "./initStagehand"; +import { AgentProvider } from "@/lib/agent/AgentProvider"; +import { AISdkClient } from "@/examples/external_clients/aisdk"; +import { getAISDKLanguageModel } from "@/lib/llm/LLMProvider"; +import { loadApiKeyFromEnv } from "@/lib/utils"; +import { LogLine } from "@/types/log"; +import { generateSummary } from "./core/summary"; +import { buildGAIATestcases } from "./suites/gaia"; +import { buildWebVoyagerTestcases } from "./suites/webvoyager"; +import { buildOnlineMind2WebTestcases } from "./suites/onlineMind2Web"; + +dotenv.config(); + +process.on("uncaughtException", (err) => { + console.error("[eval-runner] Uncaught exception:", err); +}); + +process.on("unhandledRejection", (reason) => { + console.error("[eval-runner] Unhandled rejection:", reason); +}); + +/** + * Read max concurrency and trial count from environment variables set in args.ts. + * Fallback to defaults (20 and 5) if they're not provided. + */ +const MAX_CONCURRENCY = process.env.EVAL_MAX_CONCURRENCY + ? parseInt(process.env.EVAL_MAX_CONCURRENCY, 10) + : 3; + +const TRIAL_COUNT = process.env.EVAL_TRIAL_COUNT + ? parseInt(process.env.EVAL_TRIAL_COUNT, 10) + : 3; + +const USE_API: boolean = (process.env.USE_API ?? "").toLowerCase() === "true"; + +/** + * generateFilteredTestcases: + * Based on the chosen filters (category or specific eval name) and environment, + * this function generates the set of testcases to run. Each testcase is a combination + * of a task and a model. + * + * Steps: + * - Dynamically determine the list of models based on filters. + * - Start with all combinations of tasks (from `tasksByName`) and the determined models. + * - Filter by category if a category filter was specified. + * - Filter by evaluation name if specified. + * - In the BROWSERBASE environment, exclude certain tasks that are not suitable. + */ +const generateFilteredTestcases = (): Testcase[] => { + let taskNamesToRun: string[]; + let effectiveCategory: string | null = filterByCategory; // Start with the command-line filter + + if (filterByEvalName) { + // If a specific task name is given, that's the only one we run + taskNamesToRun = [filterByEvalName]; + // Check if this single task belongs to agent-related categories to override models + const taskCategories = tasksByName[filterByEvalName]?.categories || []; + if ( + taskCategories.length === 1 && + (taskCategories[0] === "agent" || + taskCategories[0] === "external_agent_benchmarks") + ) { + // Treat this run as an agent category run for model selection + effectiveCategory = taskCategories[0]; + console.log( + `Task ${filterByEvalName} is in ${taskCategories[0]} category, using agent models.`, + ); + } + } else if (filterByCategory) { + // If filtering by category, get all tasks in that category + taskNamesToRun = Object.keys(tasksByName).filter((name) => + tasksByName[name].categories.includes(filterByCategory!), + ); + } else { + // If no specific task or category filter, run tasks from default categories + taskNamesToRun = Object.keys(tasksByName).filter((name) => + DEFAULT_EVAL_CATEGORIES.some((category) => + tasksByName[name].categories.includes(category), + ), + ); + } + + // Dynamically determine the MODELS based on the effective category + const currentModels = getModelList(effectiveCategory); + + console.log( + `Using models for this run (${effectiveCategory || "default"}):`, + currentModels, + ); + + // Check for dataset filter from environment + const datasetFilter = process.env.EVAL_DATASET; + + // Special handling: fan out GAIA dataset for agent/gaia + const isGAIATaskIncluded = taskNamesToRun.includes("agent/gaia"); + // Special handling: fan out WebVoyager dataset for agent/webvoyager + const isWebVoyagerTaskIncluded = taskNamesToRun.includes("agent/webvoyager"); + // Special handling: fan out Mind2Web dataset for agent/onlineMind2Web + const isMind2WebTaskIncluded = taskNamesToRun.includes( + "agent/onlineMind2Web", + ); + + let allTestcases: Testcase[] = []; + + // Only include GAIA if no dataset filter or if gaia is selected + if (isGAIATaskIncluded && (!datasetFilter || datasetFilter === "gaia")) { + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/gaia"); + allTestcases.push(...buildGAIATestcases(currentModels)); + } else if (isGAIATaskIncluded && datasetFilter && datasetFilter !== "gaia") { + // Remove GAIA from tasks to run if dataset filter excludes it + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/gaia"); + } + + // Only include WebVoyager if no dataset filter or if webvoyager is selected + if ( + isWebVoyagerTaskIncluded && + (!datasetFilter || datasetFilter === "webvoyager") + ) { + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/webvoyager"); + allTestcases.push(...buildWebVoyagerTestcases(currentModels)); + } else if ( + isWebVoyagerTaskIncluded && + datasetFilter && + datasetFilter !== "webvoyager" + ) { + // Remove WebVoyager from tasks to run if dataset filter excludes it + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/webvoyager"); + } + + // Only include Mind2Web if no dataset filter or if onlineMind2Web is selected + if ( + isMind2WebTaskIncluded && + (!datasetFilter || datasetFilter === "onlineMind2Web") + ) { + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/onlineMind2Web"); + allTestcases.push(...buildOnlineMind2WebTestcases(currentModels)); + } else if ( + isMind2WebTaskIncluded && + datasetFilter && + datasetFilter !== "onlineMind2Web" + ) { + // Remove Mind2Web from tasks to run if dataset filter excludes it + taskNamesToRun = taskNamesToRun.filter((t) => t !== "agent/onlineMind2Web"); + } + + // Create a list of all remaining testcases using the determined task names and models + const regularTestcases = currentModels.flatMap((model) => + taskNamesToRun.map((testName) => { + const taskCategories = + tasksConfig.find((t) => t.name === testName)?.categories || []; + return { + input: { name: testName, modelName: model as AvailableModel }, + name: testName, + tags: [ + model, + // Only include primary category as tag + taskCategories.length > 0 ? taskCategories[0] : "uncategorized", + ], + metadata: { + model: model as AvailableModel, + test: testName, + category: taskCategories[0], + categories: taskCategories, // Keep all categories in metadata for filtering + }, + expected: true, + }; + }), + ); + + allTestcases = [...allTestcases, ...regularTestcases]; + + // This filtering step might now be redundant if taskNamesToRun is already filtered + if (filterByCategory) { + allTestcases = allTestcases.filter((testcase) => + tasksByName[testcase.name].categories.includes(filterByCategory!), + ); + } + + // If running in BROWSERBASE environment, exclude tasks that are not applicable. + if (env === "BROWSERBASE") { + allTestcases = allTestcases.filter( + (testcase) => !["peeler_simple", "stock_x"].includes(testcase.name), + ); + } + + console.log( + "Final test cases to run:", + allTestcases + .map( + (t, i) => + `${i}: ${t.name} (${t.input.modelName}): ${tasksByName[t.name].categories}`, + ) + .join("\n"), + ); + + return allTestcases; +}; + +/** + * Main execution block: + * - Determine experiment name + * - Determine the project name (braintrustProjectName) based on CI or dev environment + * - Run the Eval function with the given configuration: + * * experimentName: A label for this run + * * data: A function that returns the testcases to run + * * task: A function that executes each task, given input specifying model and task name + * * scores: An array of scoring functions + * * maxConcurrency: Limit on parallel tasks + * * trialCount: Number of trials (retries) per task + * - Collect and summarize results using `generateSummary`. + */ +(async () => { + // Generate a unique name for the experiment + const experimentName: string = generateExperimentName({ + evalName: filterByEvalName || undefined, + category: filterByCategory || undefined, + environment: env, + }); + + // Determine braintrust project name to use (stagehand in CI, stagehand-dev otherwise) + const braintrustProjectName = + process.env.CI === "true" ? "stagehand" : "stagehand-dev"; + + const startTime = Date.now(); + + try { + // Run the evaluations with the braintrust Eval function + const evalResult = await Eval(braintrustProjectName, { + experimentName, + data: generateFilteredTestcases, + // Each test is a function that runs the corresponding task module + task: async (input: EvalInput) => { + const logger = new EvalLogger(); + try { + // Dynamically import the task based on its name + const basePath = path.join(__dirname, "tasks", `${input.name}`); + const candidatePaths = [`${basePath}.js`, `${basePath}.ts`]; + + let taskModule; + let lastError: unknown; + for (const candidate of candidatePaths) { + try { + taskModule = await import(candidate); + break; + } catch (err) { + lastError = err; + } + } + + if (!taskModule) { + const tried = candidatePaths.join("\n- "); + throw new StagehandEvalError( + `Failed to import task module for ${input.name}. Tried paths:\n- ${tried}\nError: ${(lastError as Error)?.message}`, + ); + } + + // Extract the task function + const taskName = input.name.includes("/") + ? input.name.split("/").pop() // Get the last part of the path for nested tasks + : input.name; + + const taskFunction = taskModule[taskName]; + + if (typeof taskFunction !== "function") { + throw new StagehandEvalError( + `No Eval function found for task name: ${taskName} in module ${input.name}`, + ); + } + + // Execute the task + let taskInput: Awaited>; + + if (USE_API) { + // Derive provider from model. Prefer explicit "provider/model"; otherwise infer for agent models + let provider: string; + if (input.modelName.includes("/")) { + provider = input.modelName.split("/")[0]; + } else { + // Fall back to agent provider inference for bare agent model names (e.g., "computer-use-preview") + try { + provider = AgentProvider.getAgentProvider(input.modelName); + } catch { + // If not an agent model, leave provider undefined to trigger helpful error below + provider = undefined as unknown as string; + } + } + + const logFn = (line: LogLine): void => logger.log(line); + const apiKey = loadApiKeyFromEnv(provider, logFn); + + if (!apiKey) { + throw new StagehandEvalError( + `USE_API=true but no API key found for provider “${provider}”.`, + ); + } + + taskInput = await initStagehand({ + logger, + modelName: input.modelName, + modelClientOptions: { apiKey: apiKey }, + }); + } else { + let llmClient: LLMClient; + if (input.modelName.includes("/")) { + llmClient = new AISdkClient({ + model: wrapAISDKModel( + getAISDKLanguageModel( + input.modelName.split("/")[0], + input.modelName.split("/")[1], + ), + ), + }); + } else { + llmClient = new CustomOpenAIClient({ + modelName: input.modelName as AvailableModel, + client: wrapOpenAI( + new OpenAI({ + apiKey: process.env.TOGETHER_AI_API_KEY, + baseURL: "https://api.together.xyz/v1", + }), + ), + }); + } + taskInput = await initStagehand({ + logger, + llmClient, + modelName: input.modelName, + }); + } + // Pass full EvalInput to the task (data-driven params available via input.params) + let result; + let isStagehandClosed = false; + try { + result = await taskFunction({ ...taskInput, input }); + // Log result to console + if (result && result._success) { + console.log(`✅ ${input.name}: Passed`); + } else { + console.log(`❌ ${input.name}: Failed`); + } + } finally { + // Only close if not already closed + if (taskInput.stagehand && !isStagehandClosed) { + try { + await taskInput.stagehand.close(); + isStagehandClosed = true; + } catch (closeError) { + console.warn("Error closing stagehand:", closeError); + } + } + } + return result; + } catch (error) { + // Categorize the error + let errorType = ErrorType.UNKNOWN; + const errorMessage = + error instanceof Error ? error.message : String(error); + + const errorMessageLower = errorMessage.toLowerCase(); + + if (error instanceof Error) { + if (errorMessageLower.includes("access denied")) { + errorType = ErrorType.ANTIBOT; + } else if (errorMessageLower.includes("proxy.goto")) { + errorType = ErrorType.PROXY_ERROR; + } else if (errorMessageLower.includes("timeout")) { + errorType = ErrorType.TIMEOUT; + } else if ( + errorMessageLower.includes("network") || + errorMessageLower.includes("fetch") + ) { + errorType = ErrorType.NETWORK; + } else if ( + errorMessageLower.includes("parse") || + errorMessageLower.includes("json") + ) { + errorType = ErrorType.PARSING_ERROR; + } else if ( + errorMessageLower.includes("init") || + errorMessageLower.includes("setup") + ) { + errorType = ErrorType.SETUP_ERROR; + } + } + + // Log any errors that occur during task execution + console.error(`❌ ${input.name}: ${errorType} - ${errorMessage}`); + logger.error({ + message: `Error in task ${input.name}`, + level: 0, + auxiliary: { + error: { + value: errorMessage, + type: "string", + }, + error_type: { + value: errorType, + type: "string", + }, + trace: { + value: error instanceof Error ? error.stack : "", + type: "string", + }, + }, + }); + + const output: EvalOutput = { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + error_type: errorType, + error_message: errorMessage, + error_stack: error instanceof Error ? error.stack : undefined, + logs: logger.getLogs(), + debugUrl: "", + sessionUrl: "", + }; + + return output; + } + }, + // Use the scoring functions defined above + scores: [exactMatch, errorMatch], + maxConcurrency: MAX_CONCURRENCY, + trialCount: TRIAL_COUNT, + }); + + // Map results to the SummaryResult format + const summaryResults: SummaryResult[] = evalResult.results.map((result) => { + const output = + typeof result.output === "boolean" + ? { _success: result.output } + : (result.output as EvalOutput); + + // The full output object (including error_type, error_message, etc.) + // is already captured in result.output and will be visible in Braintrust + // We don't need to duplicate it in metadata + + return { + input: result.input, + output, + name: result.input.name, + score: output._success ? 1 : 0, + }; + }); + + console.log(`\n⌛️ Total run time: ${(Date.now() - startTime) / 1000}s\n`); + // Generate and write the summary + await generateSummary(summaryResults, experimentName); + } catch (error) { + console.error("Error during evaluation run:", error); + // process.exit(1); + } +})(); diff --git a/sdk/stagehand-ts/evals/initStagehand.ts b/sdk/stagehand-ts/evals/initStagehand.ts new file mode 100644 index 0000000..5217362 --- /dev/null +++ b/sdk/stagehand-ts/evals/initStagehand.ts @@ -0,0 +1,266 @@ +/** + * This file provides a function to initialize a Stagehand instance for use in evaluations. + * It configures the Stagehand environment and sets default options based on the current environment + * (e.g., local or BROWSERBASE), caching preferences, and verbosity. It also establishes a logger for + * capturing logs emitted by Stagehand. + * + * We create a central config object (`StagehandConfig`) that defines all parameters for Stagehand. + * + * The `initStagehand` function takes the model name, an optional DOM settling timeout, and an EvalLogger, + * then uses these to override some default values before creating and initializing the Stagehand instance. + */ + +import { enableCaching, env } from "./env"; +import { + ConstructorParams, + LLMClient, + Stagehand, +} from "@browserbasehq/stagehand"; +import { EvalLogger } from "./logger"; +import type { StagehandInitResult } from "@/types/evals"; +import type { AgentConfig } from "@/dist"; +import { AvailableModel } from "@browserbasehq/stagehand"; +import { + // AgentProvider, + modelToAgentProviderMap, +} from "@/lib/agent/AgentProvider"; +// import fetch from "node-fetch"; +// import { HttpsProxyAgent } from "https-proxy-agent"; + +// /** +// * Generates a random 8-character alphanumeric string for session ID +// */ +// function generateSessionId(): string { +// const chars = "abcdefghijklmnopqrstuvwxyz0123456789"; +// let result = ""; +// for (let i = 0; i < 8; i++) { +// result += chars.charAt(Math.floor(Math.random() * chars.length)); +// } +// return result; +// } + +// /** +// * Validates that a proxy is working by making a test request +// */ +// async function validateProxy( +// server: string, +// username: string, +// password: string, +// ): Promise { +// const proxyUrl = `${server.replace("://", `://${username}:${password}@`)}`; +// const targetUrl = "https://httpbin.org/ip"; + +// try { +// const agent = new HttpsProxyAgent(proxyUrl); +// const res = await fetch(targetUrl, { agent }); + +// if (res.status === 200) { +// const body = await res.text(); +// console.log( +// `Proxy validation successful. Response: ${body.substring(0, 100)}`, +// ); +// return true; +// } else { +// console.error(`Proxy validation failed with status: ${res.status}`); +// return false; +// } +// } catch (err) { +// console.error("Proxy test failed:", err.message); +// return false; +// } +// } + +// /** +// * Returns a proxy configuration using NimbleWay format +// * Uses a fixed configuration with a random session ID per eval +// * Validates the proxy before returning it +// */ +// async function getNimbleProxies(): Promise< +// { +// type: "external"; +// server: string; +// username: string; +// password: string; +// }[] +// > { +// // Generate random session ID for this eval +// const sessionId = generateSessionId(); + +// // NimbleWay proxy configuration +// const username = `account-browserbase_1zxs2i-pipeline-nimbleip-country-US-session-${sessionId}`; +// const password = "Kd0Cz0O709g8"; +// const server = "http://ip.nimbleway.com:7000"; + +// // Validate the proxy is working +// const isValid = await validateProxy(server, username, password); + +// if (!isValid) { +// console.warn("Proxy validation failed, but continuing anyway"); +// } + +// return [ +// { +// type: "external", +// server, +// username, +// password, +// }, +// ]; +// } + +// async function getBDMobileProxies(): Promise< +// { +// type: "external"; +// server: string; +// username: string; +// password: string; +// }[] +// > { +// // const sessionId = generateSessionId(); + +// // BD Mobile proxy configuration +// const username = `brd-customer-hl_66010a9c-zone-mobile_proxy_stagehand_evals`; +// const password = "yn6nmnr8g9m4"; +// const server = "https://brd.superproxy.io:33335"; + +// // Validate the proxy is working +// const isValid = await validateProxy(server, username, password); + +// if (!isValid) { +// console.warn("Proxy validation failed, but continuing anyway"); +// } + +// return [ +// { +// type: "external", +// server, +// username, +// password, +// }, +// ]; +// } + +/** + * StagehandConfig: + * This configuration object follows a similar pattern to `examples/stagehand.config.ts`. + * It sets the environment, verbosity, caching preferences, and other defaults. Some values, + * like `apiKey` and `projectId`, can be defined via environment variables if needed. + * + * Adjust or remove fields as appropriate for your environment. + */ +// Base configuration without async values +const BaseStagehandConfig = { + env: env, + apiKey: process.env.BROWSERBASE_API_KEY, + projectId: process.env.BROWSERBASE_PROJECT_ID, + useAPI: process.env.USE_API === "true", + verbose: 2 as const, + debugDom: true, + headless: false, + enableCaching, + domSettleTimeoutMs: 60_000, + disablePino: true, + selfHeal: true, + modelName: "google/gemini-2.5-flash", + modelClientOptions: { + apiKey: process.env.GEMINI_API_KEY, + }, +}; + +/** + * Initializes a Stagehand instance for a given model: + * - modelName: The model to use (overrides default in StagehandConfig) + * - domSettleTimeoutMs: Optional timeout for DOM settling operations + * - logger: An EvalLogger instance for capturing logs + * + * Returns: + * - stagehand: The initialized Stagehand instance + * - logger: The provided logger, associated with the Stagehand instance + * - initResponse: Any response data returned by Stagehand initialization + */ +export const initStagehand = async ({ + llmClient, + modelClientOptions, + domSettleTimeoutMs, + logger, + configOverrides, + actTimeoutMs, + modelName, +}: { + llmClient?: LLMClient; + modelClientOptions?: { apiKey: string }; + domSettleTimeoutMs?: number; + logger: EvalLogger; + configOverrides?: Partial; + actTimeoutMs?: number; + modelName: AvailableModel; +}): Promise => { + // Get proxies with validation + // const proxyType = await getNimbleProxies(); + // const proxies = await getBDMobileProxies(); + + const config = { + ...BaseStagehandConfig, + modelClientOptions, + llmClient, + ...(domSettleTimeoutMs && { domSettleTimeoutMs }), + actTimeoutMs, + modelName, + experimental: + typeof configOverrides?.experimental === "boolean" + ? configOverrides.experimental + : !BaseStagehandConfig.useAPI, + browserbaseSessionCreateParams: { + projectId: process.env.BROWSERBASE_PROJECT_ID!, + proxies: true, + // proxies, + browserSettings: { + enablePdfViewer: true, + advancedStealth: true, + os: "windows", + viewport: { + width: 2560, + height: 1440, + }, + }, + }, + ...configOverrides, + logger: logger.log.bind(logger), + }; + + try { + const stagehand = new Stagehand(config); + + // Associate the logger with the Stagehand instance + logger.init(stagehand); + + const { debugUrl, sessionUrl } = await stagehand.init(); + + // Set navigation timeout to 60 seconds for evaluations + stagehand.context.setDefaultNavigationTimeout(60_000); + + let agentConfig: AgentConfig | undefined; + if (modelName in modelToAgentProviderMap) { + agentConfig = { + model: modelName, + provider: modelToAgentProviderMap[modelName], + instructions: `You are a helpful assistant that must solve the task by browsing. At the end, produce a single line: "Final Answer: " summarizing the requested result (e.g., score, list, or text). Current page: ${await stagehand.page.title()}. ALWAYS OPERATE WITHIN THE PAGE OPENED BY THE USER, WHICHEVER TASK YOU ARE ATTEMPTING TO COMPLETE CAN BE ACCOMPLISHED WITHIN THE PAGE. Simple perform the task provided, do not overthink or overdo it. The user trusts you to complete the task without any additional instructions, or answering any questions.`, + } as AgentConfig; + } + + const agent = stagehand.agent(agentConfig); + + return { + stagehand, + stagehandConfig: config, + logger, + debugUrl, + sessionUrl, + modelName, + agent, + }; + } catch (error) { + console.error("Error initializing stagehand:", error); + throw error; + } +}; diff --git a/sdk/stagehand-ts/evals/llm_clients/hn_aisdk.ts b/sdk/stagehand-ts/evals/llm_clients/hn_aisdk.ts new file mode 100644 index 0000000..1c5f8da --- /dev/null +++ b/sdk/stagehand-ts/evals/llm_clients/hn_aisdk.ts @@ -0,0 +1,115 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const hn_aisdk: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehandConfig, + logger, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + modelName: "openai/gpt-4o-mini", + }); + await stagehand.init(); + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/hackernews/", + ); + + let { story } = await stagehand.page.extract({ + instruction: "extract the title of the top story on the page", + schema: z.object({ + story: z.string().describe("the title of the top story on the page"), + }), + }); + // remove the (url) part of the story title + story = story.split(" (")[0]; + + const expectedStoryElement = await stagehand.page.$( + "xpath=/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]/span/a", + ); + // remove the (url) part of the story title + const expectedStory = (await expectedStoryElement?.textContent())?.split( + " (", + )?.[0]; + + if (!expectedStory) { + logger.error({ + message: "Could not find expected story element", + level: 0, + }); + return { + _success: false, + error: "Could not find expected story element", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (story !== expectedStory) { + logger.error({ + message: "Extracted story does not match expected story", + level: 0, + auxiliary: { + expected: { + value: expectedStory, + type: "string", + }, + actual: { + value: story, + type: "string", + }, + }, + }); + return { + _success: false, + error: "Extracted story does not match expected story", + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.page.act("Click on the 'new' tab"); + + if (stagehand.page.url() !== "https://news.ycombinator.com/newest") { + logger.error({ + message: "Page did not navigate to the 'new' tab", + level: 0, + auxiliary: { + expected: { + value: "https://news.ycombinator.com/newest", + type: "string", + }, + actual: { + value: stagehand.page.url(), + type: "string", + }, + }, + }); + return { + _success: false, + error: "Page did not navigate to the 'new' tab", + expectedUrl: "https://news.ycombinator.com/newest", + actualUrl: stagehand.page.url(), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.close(); + + return { + _success: true, + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; +}; diff --git a/sdk/stagehand-ts/evals/llm_clients/hn_customOpenAI.ts b/sdk/stagehand-ts/evals/llm_clients/hn_customOpenAI.ts new file mode 100644 index 0000000..9a42e1a --- /dev/null +++ b/sdk/stagehand-ts/evals/llm_clients/hn_customOpenAI.ts @@ -0,0 +1,124 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; +import { CustomOpenAIClient } from "@/examples/external_clients/customOpenAI"; +import OpenAI from "openai"; +import { Stagehand } from "@browserbasehq/stagehand"; + +export const hn_customOpenAI: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + llmClient: new CustomOpenAIClient({ + modelName: "gpt-4o-mini", + client: new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, + }), + }), + }); + + await stagehand.init(); + + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/hackernews/", + ); + + let { story } = await stagehand.page.extract({ + instruction: "extract the title of the top story on the page", + schema: z.object({ + story: z.string().describe("the title of the top story on the page"), + }), + }); + // remove the (url) part of the story title + story = story.split(" (")[0]; + + const expectedStoryElement = await stagehand.page.$( + "xpath=/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]/span/a", + ); + // remove the (url) part of the story title + const expectedStory = (await expectedStoryElement?.textContent())?.split( + " (", + )?.[0]; + + if (!expectedStory) { + logger.error({ + message: "Could not find expected story element", + level: 0, + }); + return { + _success: false, + error: "Could not find expected story element", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (story !== expectedStory) { + logger.error({ + message: "Extracted story does not match expected story", + level: 0, + auxiliary: { + expected: { + value: expectedStory, + type: "string", + }, + actual: { + value: story, + type: "string", + }, + }, + }); + return { + _success: false, + error: "Extracted story does not match expected story", + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.page.act("Click on the 'new' tab"); + + if (stagehand.page.url() !== "https://news.ycombinator.com/newest") { + logger.error({ + message: "Page did not navigate to the 'new' tab", + level: 0, + auxiliary: { + expected: { + value: "https://news.ycombinator.com/newest", + type: "string", + }, + actual: { + value: stagehand.page.url(), + type: "string", + }, + }, + }); + return { + _success: false, + error: "Page did not navigate to the 'new' tab", + expectedUrl: "https://news.ycombinator.com/newest", + actualUrl: stagehand.page.url(), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.close(); + + return { + _success: true, + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; +}; diff --git a/sdk/stagehand-ts/evals/llm_clients/hn_langchain.ts b/sdk/stagehand-ts/evals/llm_clients/hn_langchain.ts new file mode 100644 index 0000000..132e00c --- /dev/null +++ b/sdk/stagehand-ts/evals/llm_clients/hn_langchain.ts @@ -0,0 +1,122 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; +import { LangchainClient } from "@/examples/external_clients/langchain"; +import { ChatOpenAI } from "@langchain/openai"; +import { Stagehand } from "@browserbasehq/stagehand"; + +export const hn_langchain: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + llmClient: new LangchainClient( + new ChatOpenAI({ + model: "gpt-4o-mini", + }), + ), + }); + await stagehand.init(); + + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/hackernews/", + ); + + let { story } = await stagehand.page.extract({ + instruction: "extract the title of the top story on the page", + schema: z.object({ + story: z.string().describe("the title of the top story on the page"), + }), + }); + // remove the (url) part of the story title + story = story.split(" (")[0]; + + const expectedStoryElement = await stagehand.page.$( + "xpath=/html/body/center/table/tbody/tr[3]/td/table/tbody/tr[1]/td[3]/span/a", + ); + // remove the (url) part of the story title + const expectedStory = (await expectedStoryElement?.textContent())?.split( + " (", + )?.[0]; + + if (!expectedStory) { + logger.error({ + message: "Could not find expected story element", + level: 0, + }); + return { + _success: false, + error: "Could not find expected story element", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (story !== expectedStory) { + logger.error({ + message: "Extracted story does not match expected story", + level: 0, + auxiliary: { + expected: { + value: expectedStory, + type: "string", + }, + actual: { + value: story, + type: "string", + }, + }, + }); + return { + _success: false, + error: "Extracted story does not match expected story", + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.page.act("Click on the 'new' tab"); + + if (stagehand.page.url() !== "https://news.ycombinator.com/newest") { + logger.error({ + message: "Page did not navigate to the 'new' tab", + level: 0, + auxiliary: { + expected: { + value: "https://news.ycombinator.com/newest", + type: "string", + }, + actual: { + value: stagehand.page.url(), + type: "string", + }, + }, + }); + return { + _success: false, + error: "Page did not navigate to the 'new' tab", + expectedUrl: "https://news.ycombinator.com/newest", + actualUrl: stagehand.page.url(), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.close(); + + return { + _success: true, + expectedStory, + actualStory: story, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; +}; diff --git a/sdk/stagehand-ts/evals/logger.ts b/sdk/stagehand-ts/evals/logger.ts new file mode 100644 index 0000000..c0bfd60 --- /dev/null +++ b/sdk/stagehand-ts/evals/logger.ts @@ -0,0 +1,123 @@ +/** + * This file defines the `EvalLogger` class, which is used to capture and manage + * log lines during the evaluation process. The logger supports different log + * levels (info, error, warn), stores logs in memory for later retrieval, and + * also prints them to the console for immediate feedback. + * + * The `parseLogLine` function helps transform raw `LogLine` objects into a more + * structured format (`LogLineEval`), making auxiliary data easier to understand + * and analyze. By associating an `EvalLogger` instance with a `Stagehand` object, + * all logs emitted during the evaluation process can be captured, persisted, and + * reviewed after the tasks complete. + */ +import { logLineToString } from "./utils"; +import { LogLineEval } from "@/types/evals"; +import { Stagehand, LogLine } from "@browserbasehq/stagehand"; + +/** + * parseLogLine: + * Given a LogLine, attempts to parse its `auxiliary` field into a structured object. + * If parsing fails, logs an error and returns the original line. + * + * The `auxiliary` field in the log line typically contains additional metadata about the log event. + */ +function parseLogLine(logLine: LogLine): LogLineEval { + try { + let parsedAuxiliary: Record | undefined; + + if (logLine.auxiliary) { + parsedAuxiliary = {}; + + for (const [key, entry] of Object.entries(logLine.auxiliary)) { + try { + parsedAuxiliary[key] = + entry.type === "object" ? JSON.parse(entry.value) : entry.value; + } catch (parseError) { + console.warn(`Failed to parse auxiliary entry ${key}:`, parseError); + // If parsing fails, use the raw value + parsedAuxiliary[key] = entry.value; + } + } + } + + return { + ...logLine, + auxiliary: undefined, + parsedAuxiliary, + } as LogLineEval; + } catch (e) { + console.log("Error parsing log line", logLine); + console.error(e); + return logLine; + } +} + +/** + * EvalLogger: + * A logger class used during evaluations to capture and print log lines. + * + * Capabilities: + * - Maintains an internal array of log lines (EvalLogger.logs) for later retrieval. + * - Can be initialized with a Stagehand instance to provide consistent logging. + * - Supports logging at different levels (info, error, warn). + * - Each log line is converted to a string and printed to console for immediate feedback. + * - Also keeps a structured version of the logs that can be returned for analysis or + * included in evaluation output. + */ +export class EvalLogger { + private logs: LogLineEval[] = []; + stagehand?: Stagehand; + + constructor() { + this.logs = []; + } + + /** + * init: + * Associates this logger with a given Stagehand instance. + * This allows the logger to provide additional context if needed. + */ + init(stagehand: Stagehand) { + this.stagehand = stagehand; + } + + /** + * log: + * Logs a message at the default (info) level. + * Uses `logLineToString` to produce a readable output on the console, + * and then stores the parsed log line in `this.logs`. + */ + log(logLine: LogLine) { + console.log(logLineToString(logLine)); + this.logs.push(parseLogLine(logLine)); + } + + /** + * error: + * Logs an error message with `console.error` and stores it. + * Useful for capturing and differentiating error-level logs. + */ + error(logLine: LogLine) { + console.error(logLineToString(logLine)); + this.logs.push(parseLogLine(logLine)); + } + + /** + * warn: + * Logs a warning message with `console.warn` and stores it. + * Helps differentiate warnings from regular info logs. + */ + warn(logLine: LogLine) { + console.warn(logLineToString(logLine)); + this.logs.push(parseLogLine(logLine)); + } + + /** + * getLogs: + * Retrieves the array of stored log lines. + * Useful for returning logs after a task completes, for analysis or debugging. + */ + getLogs(): LogLineEval[] { + return this.logs || []; + } +} diff --git a/sdk/stagehand-ts/evals/package.json b/sdk/stagehand-ts/evals/package.json new file mode 100644 index 0000000..81eaf65 --- /dev/null +++ b/sdk/stagehand-ts/evals/package.json @@ -0,0 +1,21 @@ +{ + "name": "@browserbasehq/stagehand-evals", + "version": "1.0.9", + "private": true, + "description": "Evaluation suite for Stagehand", + "main": "./", + "scripts": { + "build": "pnpm --filter @browserbasehq/stagehand run build", + "evals": "pnpm run build && tsx index.eval.ts", + "e2e": "pnpm run build && playwright test --config deterministic/e2e.playwright.config.ts", + "e2e:bb": "pnpm run build && playwright test --config deterministic/bb.playwright.config.ts", + "e2e:local": "pnpm run build && playwright test --config deterministic/local.playwright.config.ts" + }, + "dependencies": { + "@browserbasehq/stagehand": "workspace:*", + "sharp": "^0.33.5" + }, + "devDependencies": { + "tsx": "^4.10.5" + } +} diff --git a/sdk/stagehand-ts/evals/proxies.txt b/sdk/stagehand-ts/evals/proxies.txt new file mode 100644 index 0000000..577c8a8 --- /dev/null +++ b/sdk/stagehand-ts/evals/proxies.txt @@ -0,0 +1 @@ +http://account-browserbase_1zxs2i-pipeline-nimbleip-country-US-session-TODO:Kd0Cz0O709g8@ip.nimbleway.com:7000 \ No newline at end of file diff --git a/sdk/stagehand-ts/evals/scoring.ts b/sdk/stagehand-ts/evals/scoring.ts new file mode 100644 index 0000000..42552e5 --- /dev/null +++ b/sdk/stagehand-ts/evals/scoring.ts @@ -0,0 +1,65 @@ +/** + * This file implements scoring functions needed by braintrust. + */ + +import { EvalArgs, EvalInput, EvalResult } from "@/types/evals"; + +/** + * Scoring function: exactMatch + * Given the arguments (including input, output, and expected result), + * this returns a score of 1 if the result matches the expectation, and 0 otherwise. + * + * If "expected" is true, it checks if the output indicates success. + * If "expected" is a boolean or an object with _success flag, + * it checks if output is exactly that success condition. + */ +export function exactMatch( + args: EvalArgs, +): EvalResult { + console.log(`Task "${args.input.name}" returned: ${args.output}`); + + const expected = args.expected ?? true; + if (expected === true) { + // If we expect a success (true), then we check the output's _success flag. + return { + name: "Exact match", + score: + typeof args.output === "boolean" + ? args.output + ? 1 + : 0 + : args.output._success + ? 1 + : 0, + }; + } + + // If expected is not true, just directly compare the output to expected. + return { + name: "Exact match", + score: args.output === expected ? 1 : 0, + }; +} + +/** + * Scoring function: errorMatch + * Determines if an error occurred in the task. + * Scores 1 if an error is found, otherwise 0. + */ +export function errorMatch( + args: EvalArgs< + EvalInput, + boolean | { _success: boolean; error?: unknown }, + unknown + >, +): EvalResult { + console.log(`Task "${args.input.name}" returned: ${args.output}`); + + return { + name: "Error rate", + score: + typeof args.output === "object" && args.output.error !== undefined + ? 1 + : 0, + }; +} diff --git a/sdk/stagehand-ts/evals/suites/gaia.ts b/sdk/stagehand-ts/evals/suites/gaia.ts new file mode 100644 index 0000000..7f50d24 --- /dev/null +++ b/sdk/stagehand-ts/evals/suites/gaia.ts @@ -0,0 +1,95 @@ +import path from "path"; +import type { Testcase, EvalInput } from "@/types/evals"; +import type { AvailableModel } from "@/types/model"; +import { tasksConfig } from "../taskConfig"; +import { readJsonlFile, parseJsonlRows, applySampling } from "../utils"; + +export const buildGAIATestcases = (models: string[]): Testcase[] => { + const gaiaFilePath = + process.env.EVAL_GAIA_FILE || + path.join(__dirname, "..", "datasets", "gaia", "GAIA_web.jsonl"); + + const gaiaLines = readJsonlFile(gaiaFilePath); + + const levelFilter = process.env.EVAL_GAIA_LEVEL + ? Number(process.env.EVAL_GAIA_LEVEL) + : undefined; + // Use EVAL_MAX_K if set, otherwise fall back to EVAL_GAIA_LIMIT or default to 25 + const maxCases = process.env.EVAL_MAX_K + ? Number(process.env.EVAL_MAX_K) + : process.env.EVAL_GAIA_LIMIT + ? Number(process.env.EVAL_GAIA_LIMIT) + : 25; + const sampleCount = process.env.EVAL_GAIA_SAMPLE + ? Number(process.env.EVAL_GAIA_SAMPLE) + : undefined; + + type GaiaRow = { + id: string; + Level?: number; + web: string; + ques: string; + [key: string]: unknown; + }; + + function isGaiaRow(parsed: unknown): parsed is GaiaRow { + if (parsed === null || typeof parsed !== "object") return false; + const obj = parsed as Record; + return ( + typeof obj.id === "string" && + typeof obj.web === "string" && + typeof obj.ques === "string" + ); + } + + const candidates = parseJsonlRows(gaiaLines, isGaiaRow); + + // Filter by level if specified + const filteredCandidates = levelFilter + ? candidates.filter((row) => row.Level === levelFilter) + : candidates; + + const gaiaRows = applySampling(filteredCandidates, sampleCount, maxCases); + + const allTestcases: Testcase[] = []; + for (const model of models) { + for (const row of gaiaRows) { + const finalAnswer = (row as Record)[ + "Final answer" + ] as unknown; + const input: EvalInput = { + name: "agent/gaia", + modelName: model as AvailableModel, + params: { + id: row.id, + level: row.Level, + web: row.web, + ques: row.ques, + expected: typeof finalAnswer === "string" ? finalAnswer : undefined, + }, + }; + const taskCategories = + tasksConfig.find((t) => t.name === input.name)?.categories || []; + allTestcases.push({ + input, + name: input.name, + tags: [ + model, + "gaia", // Simple dataset tag + ], + metadata: { + model: model as AvailableModel, + test: `${input.name}:${row.id}`, + category: taskCategories[0] || "agent", + categories: taskCategories, + dataset: "gaia", + task_id: row.id, + dataset_level: row.Level || "unknown", + }, + expected: true, + }); + } + } + + return allTestcases; +}; diff --git a/sdk/stagehand-ts/evals/suites/onlineMind2Web.ts b/sdk/stagehand-ts/evals/suites/onlineMind2Web.ts new file mode 100644 index 0000000..71d0c73 --- /dev/null +++ b/sdk/stagehand-ts/evals/suites/onlineMind2Web.ts @@ -0,0 +1,89 @@ +import path from "path"; +import type { Testcase, EvalInput } from "@/types/evals"; +import type { AvailableModel } from "@/types/model"; +import { tasksConfig } from "../taskConfig"; +import { readJsonlFile, parseJsonlRows, applySampling } from "../utils"; + +export const buildOnlineMind2WebTestcases = (models: string[]): Testcase[] => { + const mind2webFilePath = path.join( + __dirname, + "..", + "datasets", + "onlineMind2Web", + "onlineMind2Web.jsonl", + ); + + const lines = readJsonlFile(mind2webFilePath); + + // Use EVAL_MAX_K if set, otherwise fall back to EVAL_ONLINEMIND2WEB_LIMIT or default to 25 + const maxCases = process.env.EVAL_MAX_K + ? Number(process.env.EVAL_MAX_K) + : process.env.EVAL_ONLINEMIND2WEB_LIMIT + ? Number(process.env.EVAL_ONLINEMIND2WEB_LIMIT) + : 25; + const sampleCount = process.env.EVAL_ONLINEMIND2WEB_SAMPLE + ? Number(process.env.EVAL_ONLINEMIND2WEB_SAMPLE) + : undefined; + + type Mind2WebRow = { + task_id: string; + confirmed_task: string; + website: string; + reference_length?: number; + level?: string; + [key: string]: unknown; + }; + + function isMind2WebRow(parsed: unknown): parsed is Mind2WebRow { + if (parsed === null || typeof parsed !== "object") return false; + const obj = parsed as Record; + return ( + typeof obj.task_id === "string" && + typeof obj.confirmed_task === "string" && + typeof obj.website === "string" + ); + } + + const candidates = parseJsonlRows(lines, isMind2WebRow); + const rows = applySampling(candidates, sampleCount, maxCases); + + const allTestcases: Testcase[] = []; + for (const model of models) { + for (const row of rows) { + const input: EvalInput = { + name: "agent/onlineMind2Web", + modelName: model as AvailableModel, + params: { + task_id: row.task_id, + confirmed_task: row.confirmed_task, + website: row.website, + reference_length: row.reference_length, + level: row.level, + }, + }; + const taskCategories = + tasksConfig.find((t) => t.name === input.name)?.categories || []; + allTestcases.push({ + input, + name: input.name, + tags: [ + model, + "mind2web", // Simple dataset tag + ], + metadata: { + model: model as AvailableModel, + test: `${input.name}:${row.task_id}`, + category: taskCategories[0] || "agent", + categories: taskCategories, + dataset: "onlineMind2Web", + task_id: row.task_id, + difficulty: row.level, + website: row.website, + }, + expected: true, + }); + } + } + + return allTestcases; +}; diff --git a/sdk/stagehand-ts/evals/suites/webvoyager.ts b/sdk/stagehand-ts/evals/suites/webvoyager.ts new file mode 100644 index 0000000..2fed757 --- /dev/null +++ b/sdk/stagehand-ts/evals/suites/webvoyager.ts @@ -0,0 +1,86 @@ +import path from "path"; +import type { Testcase, EvalInput } from "@/types/evals"; +import type { AvailableModel } from "@/types/model"; +import { tasksConfig } from "../taskConfig"; +import { readJsonlFile, parseJsonlRows, applySampling } from "../utils"; + +export const buildWebVoyagerTestcases = (models: string[]): Testcase[] => { + const voyagerFilePath = path.join( + __dirname, + "..", + "datasets", + "webvoyager", + "WebVoyager_data.jsonl", + ); + + const lines = readJsonlFile(voyagerFilePath); + + // Use EVAL_MAX_K if set, otherwise fall back to EVAL_WEBVOYAGER_LIMIT or default to 25 + const maxCases = process.env.EVAL_MAX_K + ? Number(process.env.EVAL_MAX_K) + : process.env.EVAL_WEBVOYAGER_LIMIT + ? Number(process.env.EVAL_WEBVOYAGER_LIMIT) + : 25; + const sampleCount = process.env.EVAL_WEBVOYAGER_SAMPLE + ? Number(process.env.EVAL_WEBVOYAGER_SAMPLE) + : undefined; + + type VoyagerRow = { + id: string; + web: string; + ques: string; + web_name?: string; + [key: string]: unknown; + }; + + function isVoyagerRow(parsed: unknown): parsed is VoyagerRow { + if (parsed === null || typeof parsed !== "object") return false; + const obj = parsed as Record; + return ( + typeof obj.id === "string" && + typeof obj.web === "string" && + typeof obj.ques === "string" + ); + } + + const candidates = parseJsonlRows(lines, isVoyagerRow); + const rows = applySampling(candidates, sampleCount, maxCases); + + const allTestcases: Testcase[] = []; + for (const model of models) { + for (const row of rows) { + const input: EvalInput = { + name: "agent/webvoyager", + modelName: model as AvailableModel, + params: { + id: row.id, + web: row.web, + ques: row.ques, + web_name: row.web_name, + }, + }; + const taskCategories = + tasksConfig.find((t) => t.name === input.name)?.categories || []; + allTestcases.push({ + input, + name: input.name, + tags: [ + model, + "webvoyager", // Simple dataset tag + ], + metadata: { + model: model as AvailableModel, + test: `${input.name}:${row.id}`, + category: taskCategories[0] || "agent", + categories: taskCategories, + dataset: "webvoyager", + task_id: row.id, + website: row.web_name, + }, + expected: true, + }); + } + } + + return allTestcases; +}; diff --git a/sdk/stagehand-ts/evals/taskConfig.ts b/sdk/stagehand-ts/evals/taskConfig.ts new file mode 100644 index 0000000..a02442c --- /dev/null +++ b/sdk/stagehand-ts/evals/taskConfig.ts @@ -0,0 +1,175 @@ +/** + * This file is responsible for: + * - Loading and parsing the `evals.config.json` file, which defines tasks (evaluations) and their associated categories. + * - Building a lookup structure (`tasksByName`) to map each task name to its categories. + * - Filtering tasks based on command-line arguments (e.g., `filterByEvalName`) and ensuring that requested tasks exist. + * - Determining which models to use for evaluations, depending on the category and environment variables. + * - Validating that the chosen models are supported. + * + * The exported objects (`tasksByName`, `MODELS`, `config`) are used by the main evaluation script and other modules + * to know which tasks and models are available, and to configure the evaluations accordingly. + */ + +import fs from "fs"; +import path from "path"; +import { AvailableModel } from "@browserbasehq/stagehand"; +import { filterByEvalName } from "./args"; +import dotenv from "dotenv"; + +dotenv.config(); + +const ALL_EVAL_MODELS = [ + // GOOGLE + "gemini-2.0-flash", + "gemini-2.0-flash-lite", + "gemini-1.5-flash", + "gemini-2.5-pro-exp-03-25", + "gemini-1.5-pro", + "gemini-1.5-flash-8b", + "gemini-2.5-flash-preview-04-17", + "gemini-2.5-pro-preview-03-25", + // ANTHROPIC + "claude-3-5-sonnet-latest", + "claude-3-7-sonnet-latest", + // OPENAI + "gpt-4o-mini", + "gpt-4o", + "gpt-4.5-preview", + "o3", + "o3-mini", + "o4-mini", + // TOGETHER - META + "meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo", + "meta-llama/Llama-3.3-70B-Instruct-Turbo", + "meta-llama/Llama-4-Scout-17B-16E-Instruct", + "meta-llama/Llama-4-Maverick-17B-128E-Instruct-FP8", + // TOGETHER - DEEPSEEK + "deepseek-ai/DeepSeek-V3", + "Qwen/Qwen2.5-7B-Instruct-Turbo", + // GROQ + "groq/meta-llama/llama-4-scout-17b-16e-instruct", + "groq/llama-3.3-70b-versatile", + "groq/llama3-70b-8192", + "groq/qwen-qwq-32b", + "groq/qwen-2.5-32b", + "groq/deepseek-r1-distill-qwen-32b", + "groq/deepseek-r1-distill-llama-70b", + // CEREBRAS + "cerebras/llama3.3-70b", +]; + +// The configuration file `evals.config.json` contains a list of tasks and their associated categories. +const configPath = path.join(__dirname, "evals.config.json"); +const config = JSON.parse(fs.readFileSync(configPath, "utf-8")) satisfies { + tasks: { + name: string; + categories: string[]; + }[]; +}; + +/** + * The `tasksConfig` defines all tasks from the config file. Each task has a name and categories. + * We create a mapping `tasksByName` from task name to its categories for quick lookup. + */ +type TaskConfig = { + name: string; + categories: string[]; +}; +const tasksConfig = config.tasks as TaskConfig[]; + +const tasksByName = tasksConfig.reduce< + Record +>((acc, task) => { + acc[task.name] = { + categories: task.categories, + }; + return acc; +}, {}); + +/** + * If filtering by a specific eval name (task), ensure that this task actually exists. + */ +if (filterByEvalName && !tasksByName[filterByEvalName]) { + console.error(`Error: Evaluation "${filterByEvalName}" does not exist.`); + process.exit(1); +} + +/** + * Determine which models to run the evaluations against. + * + * DEFAULT_EVAL_MODELS: The default set of models used for most categories. + */ +const DEFAULT_EVAL_MODELS = process.env.EVAL_MODELS + ? process.env.EVAL_MODELS.split(",") + : [ + "google/gemini-2.0-flash", + "openai/gpt-4.1-mini", + "anthropic/claude-3-5-sonnet-latest", + ]; + +const DEFAULT_AGENT_MODELS = process.env.EVAL_AGENT_MODELS + ? process.env.EVAL_AGENT_MODELS.split(",") + : [ + // "computer-use-preview-2025-03-11", + // "claude-sonnet-4-20250514", + // "claude-opus-4-1-20250805", + // "claude-sonnet-4-5-20250929", + "computer-use-preview-10-2025", + // "computer-use-exp-07-16", + ]; + +/** + * getModelList: + * Returns a list of models to be used for the given category. + * If category is "experimental", it merges DEFAULT_EVAL_MODELS and EXPERIMENTAL_EVAL_MODELS. + * Otherwise, returns DEFAULT_EVAL_MODELS filtered by provider if specified. + */ +const getModelList = (category?: string): string[] => { + const provider = process.env.EVAL_PROVIDER?.toLowerCase(); + + if (category === "agent" || category === "external_agent_benchmarks") { + return DEFAULT_AGENT_MODELS; + } + + if (provider) { + return ALL_EVAL_MODELS.filter((model) => + filterModelByProvider(model, provider), + ); + } + + // If no agent category and no provider, return default eval models + return DEFAULT_EVAL_MODELS; +}; + +// Helper function to contain the provider filtering logic +const filterModelByProvider = (model: string, provider: string): boolean => { + const modelLower = model.toLowerCase(); + if (provider === "openai") { + return modelLower.startsWith("gpt"); + } else if (provider === "anthropic") { + return modelLower.startsWith("claude"); + } else if (provider === "google") { + return modelLower.startsWith("gemini"); + } else if (provider === "together") { + return ( + modelLower.startsWith("meta-llama") || + modelLower.startsWith("llama") || + modelLower.startsWith("deepseek") || + modelLower.startsWith("qwen") + ); + } else if (provider === "groq") { + return modelLower.startsWith("groq"); + } else if (provider === "cerebras") { + return modelLower.startsWith("cerebras"); + } + console.warn( + `Unknown provider specified or model doesn't match: ${provider}`, + ); + return false; +}; + +const MODELS: AvailableModel[] = getModelList().map((model) => { + return model as AvailableModel; +}); + +export { tasksByName, MODELS, tasksConfig, getModelList }; diff --git a/sdk/stagehand-ts/evals/tasks/agent/all_recipes.ts b/sdk/stagehand-ts/evals/tasks/agent/all_recipes.ts new file mode 100644 index 0000000..789d6dc --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/all_recipes.ts @@ -0,0 +1,58 @@ +import { Evaluator } from "@/evals/evaluator"; +import { EvalFunction } from "@/types/evals"; + +export const all_recipes: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.allrecipes.com/"); + const evaluator = new Evaluator(stagehand); + const agentResult = await agent.execute({ + instruction: + "Search for a recipe for Beef Wellington on Allrecipes that has at least 200 reviews and an average rating of 4.5 stars or higher. List the main ingredients required for the dish.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 40, + }); + + const { evaluation, reasoning } = await evaluator.ask({ + question: "Did the agent find a recipe for Beef Wellington", + }); + + logger.log(agentResult); + + const success = + evaluation === "YES" && + stagehand.page.url() === + "https://www.allrecipes.com/recipe/16899/beef-wellington/"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/apple_trade_in.ts b/sdk/stagehand-ts/evals/tasks/agent/apple_trade_in.ts new file mode 100644 index 0000000..37159b8 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/apple_trade_in.ts @@ -0,0 +1,56 @@ +//this eval is expected to fail due to issues scrolling within the trade in dialog +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const apple_trade_in: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.apple.com/shop/trade-in"); + const evaluator = new Evaluator(stagehand); + await agent.execute({ + instruction: + "Find out the trade-in value for an iPhone 13 Pro Max in good condition on the Apple website.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 35, + }); + + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Did the agent find the trade-in value for an iPhone 13 Pro Max in good condition on the Apple website?", + screenshot: false, + answer: "360", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/apple_tv.ts b/sdk/stagehand-ts/evals/tasks/agent/apple_tv.ts new file mode 100644 index 0000000..8c858f3 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/apple_tv.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +import { Evaluator } from "../../evaluator"; +export const apple_tv: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.apple.com/"); + + const agentResult = await agent.execute({ + instruction: + "Identify the size and weight for the Apple TV 4K and list the Siri Remote features introduced.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 50, + }); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: + "did the agent find the height and width of the Apple TV 4K in its reasoning which is 1.2 and 3.66?", + answer: agentResult.message, + }); + + const success = result.evaluation === "YES"; + if (!success) { + return { + _success: false, + message: agentResult.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/arxiv_gpt_report.ts b/sdk/stagehand-ts/evals/tasks/agent/arxiv_gpt_report.ts new file mode 100644 index 0000000..b6f19f6 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/arxiv_gpt_report.ts @@ -0,0 +1,60 @@ +//agent often fails on this one, +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; +export const arxiv_gpt_report: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://arxiv.org/"); + + await agent.execute({ + instruction: + "Find the paper 'GPT-4 Technical Report', when was v3 submitted?", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 25, + }); + + // Mon, 27 Mar 2023 17:46:54 UTC + + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Did the agent find the published paper 'GPT-4 Technical Report' and the date it was submitted?", + screenshot: false, + answer: "03-27-2023", + }); + + console.log(`reasoning: ${reasoning}`); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/gaia.ts b/sdk/stagehand-ts/evals/tasks/agent/gaia.ts new file mode 100644 index 0000000..5abac1e --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/gaia.ts @@ -0,0 +1,116 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; +import { modelToAgentProviderMap } from "@/lib/agent/AgentProvider"; +import { loadApiKeyFromEnv } from "@/lib/utils"; +import dotenv from "dotenv"; + +dotenv.config(); +/** + * Data-driven GAIA agent eval + * - Expects per-test params injected via eval runner: { id, level, web, ques } + * - Starts at `web`, runs the agent with `ques` as instruction + * - Requires the agent to output a final answer in the form: "Final Answer: " + * - Marks success if such an answer string is present (exact matching against dataset can be layered later) + */ +export const gaia: EvalFunction = async ({ + stagehand, + logger, + debugUrl, + sessionUrl, + modelName, + input, +}) => { + const startTime = Date.now(); + + try { + const params = ((input && input.params) || {}) as { + id?: string; + level?: number; + web?: string; + ques?: string; + }; + + if (!params.web || !params.ques) { + return { + _success: false, + error: `Missing GAIA params (web, ques). Got: ${JSON.stringify(params)}`, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + await stagehand.page.goto(params.web, { + timeout: 120_000, + }); + + if (!(modelName in modelToAgentProviderMap)) { + return { + _success: false, + error: `Model ${modelName} is not supported for agent tasks. Supported models: ${Object.keys(modelToAgentProviderMap).join(", ")}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const provider = modelToAgentProviderMap[modelName]; + const agent = stagehand.agent({ + model: modelName, + provider, + instructions: `You are a helpful assistant that must solve the task by browsing. At the end, produce a single line: "Final Answer: " summarizing the requested result (e.g., score, list, or text). Current page: ${await stagehand.page.title()}. ALWAYS OPERATE WITHIN THE PAGE OPENED BY THE USER, WHICHEVER TASK YOU ARE ATTEMPTING TO COMPLETE CAN BE ACCOMPLISHED WITHIN THE PAGE.`, + options: { + apiKey: loadApiKeyFromEnv(provider, stagehand.logger), + }, + }); + + const maxSteps = Number(process.env.AGENT_EVAL_MAX_STEPS) || 50; + const result = await agent.execute({ + instruction: params.ques, + maxSteps: maxSteps, + }); + logger.log(result); + + const expected = (params as Record).expected as + | string + | undefined; + const evaluator = new Evaluator(stagehand); + + let evalResult; + try { + evalResult = await evaluator.ask({ + question: `Did the agent provide the expected answer: "${expected}"?`, + answer: result?.message || "", + screenshot: false, + }); + } catch (evalError) { + logger.error({ + category: "gaia", + level: 0, + message: `Evaluator failed`, + auxiliary: { + error: { + value: + evalError instanceof Error + ? evalError.message + : String(evalError), + type: "string", + }, + }, + }); + throw evalError; // Let index.eval.ts handle error categorization + } + + return { + _success: evalResult.evaluation === "YES", + reasoning: evalResult.reasoning, + final_answer: result?.message, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/github.ts b/sdk/stagehand-ts/evals/tasks/agent/github.ts new file mode 100644 index 0000000..3211fbb --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/github.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; +export const github: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://github.com/"); + const evaluator = new Evaluator(stagehand); + const agentResult = await agent.execute({ + instruction: + "Find a Ruby repository on GitHub that has been updated in the past 3 days and has at least 1000 stars.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + logger.log(agentResult); + + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Ruby repository on GitHub that has been updated in the past 3 days and has at least 1000 stars.", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/github_react_version.ts b/sdk/stagehand-ts/evals/tasks/agent/github_react_version.ts new file mode 100644 index 0000000..894da93 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/github_react_version.ts @@ -0,0 +1,52 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; +export const github_react_version: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://github.com/"); + await agent.execute({ + instruction: + "Check the latest release version of React and the date it was published. ", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Does the page show the latest version of react and the date it was published", + }); + console.log(`evaluation: ${evaluation}`); + console.log(`reasoning: ${reasoning}`); + // only use url check for now, as using extract on the version is prone to breaking in future + const success = evaluation === "YES"; + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/google_flights.ts b/sdk/stagehand-ts/evals/tasks/agent/google_flights.ts new file mode 100644 index 0000000..fed1a8c --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/google_flights.ts @@ -0,0 +1,65 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const google_flights: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://google.com/travel/flights"); + + const agentResult = await agent.execute({ + instruction: + "Search for flights from San Francisco to New York for next weekend", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 40, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: + "Does the page show flights (options, available flights, not a search form) from San Francisco to New York?", + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES") { + return { + _success: true, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/google_maps.ts b/sdk/stagehand-ts/evals/tasks/agent/google_maps.ts new file mode 100644 index 0000000..edf7140 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/google_maps.ts @@ -0,0 +1,66 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const google_maps: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + const startTime = Date.now(); + + try { + await stagehand.page.goto("https://maps.google.com"); + + const maxSteps = Number(process.env.AGENT_EVAL_MAX_STEPS) || 15; + const agentResult = await agent.execute({ + instruction: + "How long does it take to get from San Francisco to New York driving?", + maxSteps: maxSteps, + }); + + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: + "Does the page show the time it takes to drive from San Francisco to New York at all?", + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES") { + return { + _success: true, + observations: result.reasoning, + final_answer: agentResult?.message, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: result.reasoning, + final_answer: agentResult?.message, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/google_maps_2.ts b/sdk/stagehand-ts/evals/tasks/agent/google_maps_2.ts new file mode 100644 index 0000000..ee04fce --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/google_maps_2.ts @@ -0,0 +1,85 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; +import { z } from "zod"; + +export const google_maps_2: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://maps.google.com"); + + const agentResult = await agent.execute({ + instruction: + "Search for the fastest walking route from La Puerta de Alcalá to La Puerta del Sol", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: + "Does the page show the fastest walking route from La Puerta de Alcalá to La Puerta del Sol?", + }); + const { distance } = await stagehand.page.extract({ + modelName: "google/gemini-2.5-flash", + instruction: + "Extract the distance for the fastest route walking to the decimal", + schema: z.object({ + distance: z + .number() + .describe("The distance between the two destinations in km"), + }), + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES") { + if (distance <= 1.3 || distance >= 1.6) { + return { + _success: false, + observations: "Distance is not 1.5 km", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/google_maps_3.ts b/sdk/stagehand-ts/evals/tasks/agent/google_maps_3.ts new file mode 100644 index 0000000..db6183d --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/google_maps_3.ts @@ -0,0 +1,52 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; +export const google_maps_3: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://maps.google.com/"); + const evaluator = new Evaluator(stagehand); + await agent.execute({ + instruction: + "Search for locksmiths open now but not open 24 hours in Texas City.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 35, + }); + + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Does the page show a locksmiths open now but not open 24 hours in Texas City?", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + observations: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/google_shopping.ts b/sdk/stagehand-ts/evals/tasks/agent/google_shopping.ts new file mode 100644 index 0000000..e26b991 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/google_shopping.ts @@ -0,0 +1,56 @@ +import { Evaluator } from "@/evals/evaluator"; +import { EvalFunction } from "@/types/evals"; + +export const google_shopping: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.google.com/shopping"); + + const agentResult = await agent.execute({ + instruction: + "Find a drip coffee maker that is on sale and within $25-60 and has a black finish", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Does the page show a drip coffee maker that is on sale and within $25-60 and has a black finish?", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/hotel_booking.ts b/sdk/stagehand-ts/evals/tasks/agent/hotel_booking.ts new file mode 100644 index 0000000..e5fda6a --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/hotel_booking.ts @@ -0,0 +1,56 @@ +//this eval is expected to fail. +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; +export const hotel_booking: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.hotels.com/"); + + const agentResult = await agent.execute({ + instruction: + "Find a hotel in Sydney with a rating of 8 or higher, providing free Wi-Fi and parking, available for a four-night stay starting on December 10, 2025.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Does the page show a hotel in Sydney with a rating of 8 or higher, providing free Wi-Fi and parking, available for a four-night stay starting on December 10, 2025?", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/hugging_face.ts b/sdk/stagehand-ts/evals/tasks/agent/hugging_face.ts new file mode 100644 index 0000000..656a5f2 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/hugging_face.ts @@ -0,0 +1,56 @@ +import { Evaluator } from "@/evals/evaluator"; +import { EvalFunction } from "@/types/evals"; + +export const hugging_face: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://huggingface.co/"); + const agentResult = await agent.execute({ + instruction: + "Search for a model on Hugging Face with an Apache-2.0 license that has received the highest number of likes.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 20, + }); + console.log(`agentResult: ${agentResult.message}`); + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Does the message mention 'kokoro-82m' or 'hexgrad/Kokoro-82M'?", + answer: agentResult.message || "", + screenshot: false, + }); + + const success = evaluation === "YES"; + + console.log(`reasoning: ${reasoning}`); + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/iframe_form.ts b/sdk/stagehand-ts/evals/tasks/agent/iframe_form.ts new file mode 100644 index 0000000..1ea0406 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/iframe_form.ts @@ -0,0 +1,86 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const iframe_form: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-form-filling/", + ); + + const agentResult = await agent.execute({ + instruction: "Fill in the form name with 'John Smith'", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 8, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: "Is the form name input filled with 'John Smith'?", + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const agentResult2 = await agent.execute({ + instruction: "Fill in the form email with 'john.smith@example.com'", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 5, + }); + logger.log(agentResult2); + + const result2 = await evaluator.ask({ + question: "Is the form email input filled with 'john.smith@example.com'?", + screenshot: true, + }); + + if (result2.evaluation !== "YES" && result2.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES" && result2.evaluation === "YES") { + return { + _success: true, + observations: "All fields were filled correctly", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: "One or more fields were not filled correctly", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/iframe_form_multiple.ts b/sdk/stagehand-ts/evals/tasks/agent/iframe_form_multiple.ts new file mode 100644 index 0000000..4b5e78e --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/iframe_form_multiple.ts @@ -0,0 +1,74 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const iframe_form_multiple: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-form-filling/", + ); + + const agentResult = await agent.execute({ + instruction: + "Fill in the form name with 'John Smith', the email with 'john.smith@example.com', and select the 'Are you the domain owner?' option as 'No'", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 12, + }); + logger.log(agentResult); + + await stagehand.page.mouse.wheel(0, -1000); + const evaluator = new Evaluator(stagehand); + const results = await evaluator.batchAsk({ + questions: [ + { question: "Is the form name input filled with 'John Smith'?" }, + { + question: + "Is the form email input filled with 'john.smith@example.com'?", + }, + ], + }); + + for (const r of results) { + if (r.evaluation !== "YES" && r.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + if (r.evaluation === "NO") { + return { + _success: false, + observations: r.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } + + return { + _success: true, + observations: "All fields were filled correctly", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/kayak.ts b/sdk/stagehand-ts/evals/tasks/agent/kayak.ts new file mode 100644 index 0000000..6a1d946 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/kayak.ts @@ -0,0 +1,65 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; + +export const kayak: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://www.kayak.com"); + + await agent.execute({ + instruction: "Find flights from San Francisco to Tokyo next week", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 25, + }); + await agent.execute({ + instruction: "Sort the flights by price", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 8, + }); + + if (stagehand.context.pages().length !== 2) { + return { + _success: false, + message: "No new pages were opened", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + const { evaluation, reasoning } = await evaluator.ask({ + question: + "Are the flights shown sorted by price? Check the sort button in the top left corner of the page. It should show cheapest first; use this as the success criteria since the page might promote other flights and not show the list in order.", + }); + + const success = evaluation === "YES"; + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/kith.ts b/sdk/stagehand-ts/evals/tasks/agent/kith.ts new file mode 100644 index 0000000..c5bced6 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/kith.ts @@ -0,0 +1,79 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; + +export const kith: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto( + "https://kith.com/collections/nike-air-force-1/products/nkcw2288-111?variant=19439468707968", + ); + + await agent.execute({ + instruction: + "add the shoes to cart, go to checkout, and fill the delivery information. Don't fill the payment information", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 25, + }); + + const { evaluation, reasoning } = await evaluator.ask({ + question: "Did the agent fill the delivery information", + }); + + const success = evaluation === "YES"; + + if (success) { + await agent.execute({ + instruction: + "fill the credit card information, do not submit the order just add placeholders", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 10, + }); + + const { evaluation: evaluation2, reasoning: reasoning2 } = + await evaluator.ask({ + question: "Did the agent fill the payment information", + }); + + const success2 = evaluation2 === "YES"; + + if (success2) { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + message: reasoning2, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } else { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/nba_trades.ts b/sdk/stagehand-ts/evals/tasks/agent/nba_trades.ts new file mode 100644 index 0000000..716deff --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/nba_trades.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; +export const nba_trades: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://www.espn.com/"); + + const agentResult = await agent.execute({ + instruction: + "Find the latest Team transaction in the NBA within the past week.", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 25, + }); + logger.log(agentResult); + + const { evaluation, reasoning } = await evaluator.ask({ + question: "Did the agent make it to the nba transactions page?", + }); + + const success = evaluation === "YES"; + + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/onlineMind2Web.ts b/sdk/stagehand-ts/evals/tasks/agent/onlineMind2Web.ts new file mode 100644 index 0000000..a25a92c --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/onlineMind2Web.ts @@ -0,0 +1,123 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; +import { ScreenshotCollector } from "../../utils/ScreenshotCollector"; +import { modelToAgentProviderMap } from "@/lib/agent/AgentProvider"; +import { loadApiKeyFromEnv } from "@/lib/utils"; +import dotenv from "dotenv"; + +dotenv.config(); + +export const onlineMind2Web: EvalFunction = async ({ + stagehand, + logger, + debugUrl, + sessionUrl, + modelName, + input, +}) => { + const startTime = Date.now(); + + try { + const params = ((input && input.params) || {}) as { + task_id?: string; + confirmed_task?: string; + website?: string; + reference_length?: number; + level?: string; + }; + + if (!params.website || !params.confirmed_task) { + return { + _success: false, + error: `Missing onlineMind2Web params (website, confirmed_task). Got: ${JSON.stringify(params)}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.page.goto(params.website, { + timeout: 120_000, + }); + + if (!(modelName in modelToAgentProviderMap)) { + return { + _success: false, + error: `Model ${modelName} is not supported for agent tasks. Supported models: ${Object.keys(modelToAgentProviderMap).join(", ")}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const provider = modelToAgentProviderMap[modelName]; + const agent = stagehand.agent({ + model: modelName, + provider, + instructions: `You are a helpful assistant that must solve the task by browsing. At the end, produce a single line: "Final Answer: " summarizing the requested result (e.g., score, list, or text). Current page: ${await stagehand.page.title()}. ALWAYS OPERATE WITHIN THE PAGE OPENED BY THE USER, WHICHEVER TASK YOU ARE ATTEMPTING TO COMPLETE CAN BE ACCOMPLISHED WITHIN THE PAGE.`, + options: { + apiKey: loadApiKeyFromEnv(provider, stagehand.logger), + }, + }); + + // Start collecting screenshots in parallel + const screenshotCollector = new ScreenshotCollector(stagehand.page, { + maxScreenshots: 8, // Keep up to the last 8 screenshots + }); + + // Set the collector on the agent so it captures screenshots + if (agent.setScreenshotCollector) { + agent.setScreenshotCollector(screenshotCollector); + } + + screenshotCollector.start(); + + const maxSteps = Number(process.env.AGENT_EVAL_MAX_STEPS) || 80; + const agentResult = await agent.execute({ + instruction: params.confirmed_task, + maxSteps: maxSteps, + }); + + logger.log(agentResult); + // Stop collecting and get all screenshots + const screenshots = screenshotCollector.stop(); + + logger.log({ + category: "evaluation", + message: `Collected ${screenshots.length} screenshots for evaluation`, + level: 1, + }); + + const evaluator = new Evaluator(stagehand); + const evalResult = await evaluator.ask({ + question: `Did the agent successfully complete this task: "${params.confirmed_task}"?`, + screenshot: screenshots, + agentReasoning: + agentResult.message || + "no reasoning available, agent potentially hit step limit", + }); + + if ( + evalResult.reasoning.includes("access denied") && + evalResult.evaluation === "NO" + ) { + throw new Error("access denied"); + } + + return { + _success: evalResult.evaluation === "YES", + reasoning: evalResult.reasoning, + final_answer: agentResult?.message, + screenshotCount: screenshots.length, + task_level: params.level, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + // Let the error propagate - the parent runner will handle cleanup + console.error(error); + throw error; + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/sf_library_card.ts b/sdk/stagehand-ts/evals/tasks/agent/sf_library_card.ts new file mode 100644 index 0000000..6d10830 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/sf_library_card.ts @@ -0,0 +1,64 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const sf_library_card: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://sflib1.sfpl.org/selfreg"); + + const agentResult = await agent.execute({ + instruction: "Fill in the 'street address' field with '166 Geary St'", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 5, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: + "Does the page show the 'street address' field filled with '166 Geary St'?", + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES") { + return { + _success: true, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/sf_library_card_multiple.ts b/sdk/stagehand-ts/evals/tasks/agent/sf_library_card_multiple.ts new file mode 100644 index 0000000..398ac37 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/sf_library_card_multiple.ts @@ -0,0 +1,64 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; + +export const sf_library_card_multiple: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://sflib1.sfpl.org/selfreg"); + + const agentResult = await agent.execute({ + instruction: + "Fill in ALL the REQUIRED fields with mock data. DO NOT submit the form", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 25, + }); + logger.log(agentResult); + + const evaluator = new Evaluator(stagehand); + const result = await evaluator.ask({ + question: "Does the page show all the required fields filled?", + }); + + if (result.evaluation !== "YES" && result.evaluation !== "NO") { + return { + _success: false, + observations: "Evaluator provided an invalid response", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (result.evaluation === "YES") { + return { + _success: true, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: result.reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/sign_in.ts b/sdk/stagehand-ts/evals/tasks/agent/sign_in.ts new file mode 100644 index 0000000..b216212 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/sign_in.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; + +export const sign_in: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://v0-modern-login-flow.vercel.app/"); + + const agentResult = await agent.execute({ + instruction: + "Sign in with the email address 'test@browserbaser.com' and the password 'stagehand=goated' ", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 15, + }); + logger.log(agentResult); + const url = await stagehand.page.url(); + + if (url === "https://v0-modern-login-flow.vercel.app/authorized") { + return { + _success: true, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: false, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/steam_games.ts b/sdk/stagehand-ts/evals/tasks/agent/steam_games.ts new file mode 100644 index 0000000..14923c1 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/steam_games.ts @@ -0,0 +1,50 @@ +import { EvalFunction } from "@/types/evals"; + +export const steam_games: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://store.steampowered.com/"); + + const agentResult = await agent.execute({ + instruction: + "Show most played games in Steam. And tell me the number of players in game at this time", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 30, + }); + + //strictly used url check and no extract as the top games / players can vary + const success = stagehand.page + .url() + .includes("https://store.steampowered.com/"); + + if (!success) { + return { + _success: false, + message: agentResult.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/trivago.ts b/sdk/stagehand-ts/evals/tasks/agent/trivago.ts new file mode 100644 index 0000000..55d3bab --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/trivago.ts @@ -0,0 +1,53 @@ +import { EvalFunction } from "@/types/evals"; + +export const trivago: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://www.trivago.com/"); + + const agentResult = await agent.execute({ + instruction: + "Find the cheapest room in the hotel H10 Tribeca in Madrid next weekend. Stop at the trivago page showing the results", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 13, + }); + logger.log(agentResult); + + const url = await stagehand.page.url(); + + if ( + url.includes("hotel-h10-tribeca-madrid") && + url.includes("trivago.com") + ) { + return { + _success: true, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else { + return { + _success: false, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/ubereats.ts b/sdk/stagehand-ts/evals/tasks/agent/ubereats.ts new file mode 100644 index 0000000..54fb414 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/ubereats.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "@/evals/evaluator"; + +export const ubereats: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + const evaluator = new Evaluator(stagehand); + await stagehand.page.goto("https://www.ubereats.com/"); + + await agent.execute({ + instruction: + "Order a pizza from ubereats to 639 geary st in sf, call the task complete once the login page is shown after adding pizza and viewing the cart", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 40, + }); + + const { evaluation, reasoning } = await evaluator.ask({ + question: "Did the agent make it to the login page?", + }); + + const success = + evaluation === "YES" && + stagehand.page.url().includes("https://auth.uber.com/"); + if (!success) { + return { + _success: false, + message: reasoning, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/webvoyager.ts b/sdk/stagehand-ts/evals/tasks/agent/webvoyager.ts new file mode 100644 index 0000000..9b50617 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/webvoyager.ts @@ -0,0 +1,112 @@ +import { EvalFunction } from "@/types/evals"; +import { Evaluator } from "../../evaluator"; +import { ScreenshotCollector } from "../../utils/ScreenshotCollector"; +import { modelToAgentProviderMap } from "@/lib/agent/AgentProvider"; +import { loadApiKeyFromEnv } from "@/lib/utils"; +import dotenv from "dotenv"; +dotenv.config(); + +export const webvoyager: EvalFunction = async ({ + stagehand, + logger, + debugUrl, + sessionUrl, + modelName, + input, +}) => { + const startTime = Date.now(); + + try { + const params = ((input && input.params) || {}) as { + id?: string; + web?: string; + ques?: string; + web_name?: string; + }; + + if (!params.web || !params.ques) { + return { + _success: false, + error: `Missing WebVoyager params (web, ques). Got: ${JSON.stringify(params)}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + await stagehand.page.goto(params.web, { + timeout: 120_000, + }); + + if (!(modelName in modelToAgentProviderMap)) { + return { + _success: false, + error: `Model ${modelName} is not supported for agent tasks. Supported models: ${Object.keys(modelToAgentProviderMap).join(", ")}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const provider = modelToAgentProviderMap[modelName]; + const agent = stagehand.agent({ + model: modelName, + provider, + instructions: `You are a helpful assistant that must solve the task by browsing. At the end, produce a single line: "Final Answer: " summarizing the requested result (e.g., score, list, or text). Current page: ${await stagehand.page.title()}. ALWAYS OPERATE WITHIN THE PAGE OPENED BY THE USER, WHICHEVER TASK YOU ARE ATTEMPTING TO COMPLETE CAN BE ACCOMPLISHED WITHIN THE PAGE.`, + options: { + apiKey: loadApiKeyFromEnv(provider, stagehand.logger), + }, + }); + + // Start collecting screenshots in parallel + const screenshotCollector = new ScreenshotCollector(stagehand.page, { + maxScreenshots: 8, // Keep last 10 screenshots + }); + + if (agent.setScreenshotCollector) { + agent.setScreenshotCollector(screenshotCollector); + } + + screenshotCollector.start(); + + const maxSteps = Number(process.env.AGENT_EVAL_MAX_STEPS) || 75; + const agentResult = await agent.execute({ + instruction: params.ques, + maxSteps: maxSteps, + }); + logger.log(agentResult); + + // Stop collecting and get all screenshots + const screenshots = screenshotCollector.stop(); + + logger.log({ + category: "evaluation", + message: `Collected ${screenshots.length} screenshots for evaluation`, + level: 1, + }); + + const evaluator = new Evaluator(stagehand); + const evalResult = await evaluator.ask({ + question: `Did the agent successfully complete this task: "${params.ques}"?`, + screenshot: screenshots, + agentReasoning: + agentResult.message || + "no reasoning available, agent potentially hit step limit", + }); + + return { + _success: evalResult.evaluation === "YES", + reasoning: evalResult.reasoning, + final_answer: agentResult?.message, + screenshotCount: screenshots.length, + execution_time: Date.now() - startTime, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + // Let the error propagate - the parent runner will handle cleanup + console.error(error); + throw error; + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/agent/youtube.ts b/sdk/stagehand-ts/evals/tasks/agent/youtube.ts new file mode 100644 index 0000000..f6d58c6 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/agent/youtube.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; + +export const youtube: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, + agent, +}) => { + try { + await stagehand.page.goto("https://youtube.com"); + + const agentResult = await agent.execute({ + instruction: + "Search for Keinemusik's set under some very famous pointy landmarks. Make sure to click on the video", + maxSteps: Number(process.env.AGENT_EVAL_MAX_STEPS) || 15, + }); + logger.log(agentResult); + const url = await stagehand.page.url(); + + if (url.includes("https://www.youtube.com/watch?v=eEobh8iCbIE")) { + return { + _success: true, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: false, + observations: url, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/allrecipes.ts b/sdk/stagehand-ts/evals/tasks/allrecipes.ts new file mode 100644 index 0000000..f7e64f5 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/allrecipes.ts @@ -0,0 +1,101 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const allrecipes: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://www.allrecipes.com/", { + waitUntil: "domcontentloaded", + }); + + await stagehand.page.act({ + action: 'Type "chocolate chip cookies" in the search bar', + }); + await stagehand.page.act({ + action: "press enter", + }); + + const recipeDetails = await stagehand.page.extract({ + instruction: + "Extract the title of the first recipe and the total number of ratings it has received.", + schema: z.object({ + title: z.string().describe("Title of the recipe"), + total_ratings: z + .string() + .describe("Total number of ratings for the recipe"), + }), + }); + + const { title, total_ratings } = recipeDetails; + const expectedTitle = "Best Chocolate Chip Cookies"; + const expectedRatings = 19164; + + const extractedRatings = parseInt(total_ratings.replace(/[^\d]/g, ""), 10); + const isRatingsWithinRange = + extractedRatings >= expectedRatings - 1000 && + extractedRatings <= expectedRatings + 1000; + + if (title !== expectedTitle || !isRatingsWithinRange) { + const errors = []; + if (title !== expectedTitle) { + errors.push({ + message: "Extracted title does not match the expected title", + expected: expectedTitle, + actual: title, + }); + } + if (!isRatingsWithinRange) { + errors.push({ + message: "Extracted ratings are not within the expected range", + expected: `${expectedRatings} ± 1000`, + actual: extractedRatings.toString(), + }); + } + + logger.error({ + message: "Failed to extract correct recipe details", + level: 0, + auxiliary: { + errors: { + value: JSON.stringify(errors), + type: "object", + }, + }, + }); + + return { + _success: false, + error: "Recipe details extraction validation failed", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + return { + _success: true, + recipeDetails: { + title, + total_ratings: extractedRatings, + }, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + message: "Recipe details extraction validation failed", + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/amazon_add_to_cart.ts b/sdk/stagehand-ts/evals/tasks/amazon_add_to_cart.ts new file mode 100644 index 0000000..c054132 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/amazon_add_to_cart.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; + +export const amazon_add_to_cart: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/amazon/", + ); + + await stagehand.page.waitForTimeout(5000); + + await stagehand.page.act({ + action: "click the 'Add to Cart' button", + }); + + await stagehand.page.waitForTimeout(2000); + + await stagehand.page.act({ + action: "click the 'Proceed to checkout' button", + }); + + await stagehand.page.waitForTimeout(2000); + const currentUrl = stagehand.page.url(); + const expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/amazon/sign-in.html"; + + return { + _success: currentUrl === expectedUrl, + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/apple.ts b/sdk/stagehand-ts/evals/tasks/apple.ts new file mode 100644 index 0000000..0f9cd56 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/apple.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; + +export const apple: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://www.apple.com/iphone-16-pro/"); + + await stagehand.page.act({ action: "click on the buy button" }); + await stagehand.page.act({ action: "select the Pro Max model" }); + await stagehand.page.act({ action: "select the natural titanium color" }); + await stagehand.page.act({ action: "select the 256GB storage option" }); + await stagehand.page.act({ + action: "click on the 'select a smartphone' trade-in option", + }); + + await stagehand.page.act({ + action: "select the iPhone 13 mini model from the dropdown", + }); + await stagehand.page.act({ + action: "select the iPhone 13 mini is in good condition", + }); + + const successMessageLocator = stagehand.page.locator( + 'text="Good News. Your iPhone 13 mini qualifies for credit."', + ); + const isVisible = await successMessageLocator.isVisible(); + + return { + _success: isVisible, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/arxiv.ts b/sdk/stagehand-ts/evals/tasks/arxiv.ts new file mode 100644 index 0000000..c64287a --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/arxiv.ts @@ -0,0 +1,186 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const arxiv: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://arxiv.org/search/"); + + await stagehand.page.act( + "type web agents with multimodal models in the search bar", + ); + + await stagehand.page.act("hit enter"); + + const paper_links = await stagehand.page.extract({ + instruction: "extract the titles and links for two papers", + schema: z.object({ + papers: z + .array( + z.object({ + title: z.string().describe("the title of the paper"), + link: z.string().url().describe("the link to the paper"), + }), + ) + .describe("list of papers"), + }), + }); + + if ( + !paper_links || + !paper_links.papers || + paper_links.papers.length === 0 + ) { + return { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + const papers = []; + for (const paper of paper_links.papers) { + if (paper.link) { + await stagehand.page.goto(paper.link); + const abstract = await stagehand.page.extract({ + instruction: "extract details of the paper from the abstract", + schema: z.object({ + category: z + .string() + .describe( + "the category of the paper. one of {'Benchmark', 'Dataset', 'Model', 'Framework', 'System', 'Other'}", + ), + problem: z + .string() + .describe( + "summarize the problem that the paper is trying to solve in one sentence", + ) + .nullable(), + methodology: z + .string() + .describe( + "summarize the methodology of the paper in one sentence", + ) + .nullable(), + results: z + .string() + .describe("summarize the results of the paper in one sentence") + .nullable(), + conclusion: z + .string() + .describe("summarize the conclusion of the paper in one sentence") + .nullable(), + code: z + .string() + .describe( + "if provided, extract only the link to the code repository, without additional text. this is often optional and not always provided.", + ) + .nullable(), + }), + }); + + papers.push({ + title: paper.title, + link: paper.link, + ...abstract, + }); + } + } + + if (!papers || papers.length === 0) { + return { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + if (papers.length !== 2) { + logger.error({ + message: "incorrect number of papers extracted", + level: 0, + auxiliary: { + expected: { + value: "2", + type: "integer", + }, + actual: { + value: papers.length.toString(), + type: "integer", + }, + }, + }); + + return { + _success: false, + error: "Incorrect number of papers extracted", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + // Ensure that every paper has a problem and methodology + for (const paper of papers) { + if (!paper.problem || !paper.methodology) { + logger.error({ + message: `paper missing problem or methodology`, + level: 0, + auxiliary: { + paper: { + value: JSON.stringify(paper), + type: "object", + }, + }, + }); + + return { + _success: false, + error: "Incomplete paper information", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + } + + return { + _success: true, + papers, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + logger.error({ + message: `error in arxiv function`, + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string", + }, + trace: { + value: error.stack, + type: "string", + }, + }, + }); + + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/bidnet.ts b/sdk/stagehand-ts/evals/tasks/bidnet.ts new file mode 100644 index 0000000..4723263 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/bidnet.ts @@ -0,0 +1,38 @@ +import { EvalFunction } from "@/types/evals"; + +export const bidnet: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://www.bidnetdirect.com/"); + + await stagehand.page.act({ + action: 'Click on the "Construction" keyword', + }); + + const expectedUrl = + "https://www.bidnetdirect.com/public/solicitations/open?keywords=Construction"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl.startsWith(expectedUrl), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/checkboxes.ts b/sdk/stagehand-ts/evals/tasks/checkboxes.ts new file mode 100644 index 0000000..af7e692 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/checkboxes.ts @@ -0,0 +1,47 @@ +import { EvalFunction } from "@/types/evals"; + +export const checkboxes: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/checkboxes/", + ); + + await stagehand.page.act({ + action: "click the 'baseball' option", + }); + + await stagehand.page.act({ + action: "click the 'netball' option", + }); + + const baseballChecked = await stagehand.page + .locator('input[type="checkbox"][name="sports"][value="baseball"]') + .isChecked(); + + const netballChecked = await stagehand.page + .locator('input[type="checkbox"][name="sports"][value="netball"]') + .isChecked(); + + return { + _success: baseballChecked && netballChecked, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (e) { + return { + _success: false, + error: e, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/combination_sauce.ts b/sdk/stagehand-ts/evals/tasks/combination_sauce.ts new file mode 100644 index 0000000..0233fd4 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/combination_sauce.ts @@ -0,0 +1,60 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const combination_sauce: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://www.saucedemo.com/"); + + const { usernames, password } = await stagehand.page.extract({ + instruction: "extract the accepted usernames and the password for login", + schema: z.object({ + usernames: z.array(z.string()).describe("the accepted usernames"), + password: z.string().describe("the password for login"), + }), + }); + + await stagehand.page.act({ + action: `enter username 'standard_user'`, + }); + + await stagehand.page.act({ + action: `enter password '${password}'`, + }); + + await stagehand.page.act({ + action: "click on 'login'", + }); + + const observations = await stagehand.page.observe({ + instruction: "find all the 'add to cart' buttons", + }); + + const url = stagehand.page.url(); + + const usernamesCheck = usernames.length === 6; + const urlCheck = url === "https://www.saucedemo.com/inventory.html"; + const observationsCheck = observations.length === 6; + + return { + _success: usernamesCheck && urlCheck && observationsCheck, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/costar.ts b/sdk/stagehand-ts/evals/tasks/costar.ts new file mode 100644 index 0000000..5c6b4d5 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/costar.ts @@ -0,0 +1,77 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const costar: EvalFunction = async ({ + logger, + debugUrl, + sessionUrl, + stagehand, +}) => { + try { + await stagehand.page.goto("https://www.costar.com/"); + + await stagehand.page.act({ action: "click on the first article" }); + + await stagehand.page.act({ + action: "click on the learn more button for the first job", + }); + + const articleTitle = await stagehand.page.extract({ + instruction: "extract the title of the article", + schema: z.object({ + title: z.string().describe("the title of the article").nullable(), + }), + }); + + logger.log({ + message: "got article title", + level: 1, + auxiliary: { + articleTitle: { + value: JSON.stringify(articleTitle), + type: "object", + }, + }, + }); + + // Check if the title is more than 5 characters + const isTitleValid = + articleTitle.title !== null && articleTitle.title.length > 5; + + await stagehand.close(); + + return { + title: articleTitle.title, + _success: isTitleValid, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + logger.error({ + message: "error in costar function", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string", + }, + trace: { + value: error.stack, + type: "string", + }, + }, + }); + + return { + title: null, + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/csr_in_oopif.ts b/sdk/stagehand-ts/evals/tasks/csr_in_oopif.ts new file mode 100644 index 0000000..e034e89 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/csr_in_oopif.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const csr_in_oopif: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside an CSR (closed mode shadow) root that is inside an + // OOPIF (out of process iframe) + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/closed-shadow-root-in-oopif/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/csr_in_spif.ts b/sdk/stagehand-ts/evals/tasks/csr_in_spif.ts new file mode 100644 index 0000000..f74f45d --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/csr_in_spif.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const csr_in_spif: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside an CSR (closed mode shadow) root that is inside an + // SPIF (same process iframe) + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/closed-shadow-dom-in-spif/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/custom_dropdown.ts b/sdk/stagehand-ts/evals/tasks/custom_dropdown.ts new file mode 100644 index 0000000..f500fd7 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/custom_dropdown.ts @@ -0,0 +1,60 @@ +import { EvalFunction } from "@/types/evals"; + +export const custom_dropdown: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + /** + * This eval is meant to test whether we do not incorrectly attempt + * the selectOptionFromDropdown method (defined in actHandlerUtils.ts) on a + * 'dropdown' that is not a element. + * + * This kind of dropdown must be clicked to be expanded before being interacted + * with. + */ + + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/expand-dropdown/", + ); + + await page.act({ + description: "The 'Select a country' dropdown", + selector: "/html/not-a-dropdown", + arguments: [], + method: "click", + }); + + // we are expecting stagehand to click the dropdown to expand it, + // and therefore the available options should now be contained in the full + // a11y tree. + + // to test, we'll grab the full a11y tree, and make sure it contains 'Canada' + const extraction = await page.extract(); + const fullTree = extraction.page_text; + + if (fullTree.includes("Canada")) { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: "unable to expand the dropdown", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error attempting to select an option from the dropdown: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/heal_scroll_50.ts b/sdk/stagehand-ts/evals/tasks/heal_scroll_50.ts new file mode 100644 index 0000000..99eaf04 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/heal_scroll_50.ts @@ -0,0 +1,60 @@ +import { EvalFunction } from "@/types/evals"; + +export const heal_scroll_50: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/aigrant/", + ); + await stagehand.page.act({ + description: "the element to scroll on", + selector: "/html/body/div/div/button", + arguments: ["50%"], + method: "scrollTo", + }); + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + // Get the current scroll position and total scroll height + const scrollInfo = await stagehand.page.evaluate(() => { + return { + scrollTop: window.scrollY + window.innerHeight / 2, + scrollHeight: document.documentElement.scrollHeight, + }; + }); + + const halfwayScroll = scrollInfo.scrollHeight / 2; + const halfwayReached = + Math.abs(scrollInfo.scrollTop - halfwayScroll) <= 200; + const evaluationResult = halfwayReached + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll position (${scrollInfo.scrollTop}px) is not halfway down the page (${halfwayScroll}px).`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/heal_simple_google_search.ts b/sdk/stagehand-ts/evals/tasks/heal_simple_google_search.ts new file mode 100644 index 0000000..4254ab9 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/heal_simple_google_search.ts @@ -0,0 +1,45 @@ +import { EvalFunction } from "@/types/evals"; + +export const heal_simple_google_search: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/google/", + ); + + await stagehand.page.act({ + description: "The search bar", + selector: "/html/not-the-search-bar", + arguments: ["OpenAI"], + method: "fill", + }); + + await stagehand.page.act("click the google search button"); + + const expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/google/openai.html"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl.startsWith(expectedUrl), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/hidden_input_dropdown.ts b/sdk/stagehand-ts/evals/tasks/hidden_input_dropdown.ts new file mode 100644 index 0000000..0492f04 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/hidden_input_dropdown.ts @@ -0,0 +1,60 @@ +import { EvalFunction } from "@/types/evals"; + +export const hidden_input_dropdown: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + /** + * This eval is meant to test whether we do not incorrectly attempt + * the selectOptionFromDropdown method (defined in actHandlerUtils.ts) on a + * hidden input 'dropdown'. + * + * This kind of dropdown must be clicked to be expanded before being interacted + * with. + */ + + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/hidden-input-dropdown/", + ); + + await page.act("click to expand the 'Favourite Colour' dropdown"); + + // we are expecting stagehand to click the dropdown to expand it, + // and therefore the available options should now be contained in the full + // a11y tree. + + // to test, we'll grab the full a11y tree, and make sure it contains 'Green' + const extraction = await page.extract(); + const fullTree = extraction.page_text; + + if (fullTree.includes("Green")) { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: "unable to expand the dropdown", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error attempting click to expand the dropdown: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/history.ts b/sdk/stagehand-ts/evals/tasks/history.ts new file mode 100644 index 0000000..5d453b6 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/history.ts @@ -0,0 +1,58 @@ +import { EvalFunction } from "@/types/evals"; + +export const history: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://docs.stagehand.dev"); + await stagehand.page.act("click on the 'Quickstart' tab"); + await stagehand.page.extract("Extract the title of the page"); + await stagehand.page.observe("Find all links on the page"); + + const history = stagehand.history; + + const hasCorrectNumberOfEntries = history.length === 4; + + const hasNavigateEntry = history[0].method === "navigate"; + const hasActEntry = history[1].method === "act"; + const hasExtractEntry = history[2].method === "extract"; + const hasObserveEntry = history[3].method === "observe"; + + const allEntriesHaveTimestamps = history.every( + (entry) => + typeof entry.timestamp === "string" && entry.timestamp.length > 0, + ); + const allEntriesHaveResults = history.every( + (entry) => entry.result !== undefined, + ); + + const success = + hasCorrectNumberOfEntries && + hasNavigateEntry && + hasActEntry && + hasExtractEntry && + hasObserveEntry && + allEntriesHaveTimestamps && + allEntriesHaveResults; + + return { + _success: success, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/homedepot.ts b/sdk/stagehand-ts/evals/tasks/homedepot.ts new file mode 100644 index 0000000..88197af --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/homedepot.ts @@ -0,0 +1,82 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const homedepot: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.homedepot.com/"); + await stagehand.page.act("enter 'gas grills' in the search bar"); + await stagehand.page.act("press enter"); + await stagehand.page.act("click on the best selling gas grill"); + await stagehand.page.act("click on the Product Details"); + + const productSpecs = await stagehand.page.extract({ + instruction: "Extract the Primary exact Burner BTU of the product", + schema: z.object({ + productSpecs: z.object({ + burnerBTU: z.number().describe("Primary Burner BTU exact value"), + }), + }), + }); + + logger.log({ + message: `gas grill primary burner BTU`, + level: 1, + auxiliary: { + productSpecs: { + value: JSON.stringify(productSpecs), + type: "object", + }, + }, + }); + + if (!productSpecs || !productSpecs.productSpecs) { + return { + _success: false, + productSpecs, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const isLargerThan1000 = productSpecs.productSpecs.burnerBTU >= 10000; + + return { + _success: isLargerThan1000, + productSpecs, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + logger.error({ + message: "error in homedepot function", + level: 0, + auxiliary: { + error: { + value: error.message, + type: "string", + }, + trace: { + value: error.stack, + type: "string", + }, + }, + }); + + return { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/iframe_form_filling.ts b/sdk/stagehand-ts/evals/tasks/iframe_form_filling.ts new file mode 100644 index 0000000..782c8af --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/iframe_form_filling.ts @@ -0,0 +1,82 @@ +import { EvalFunction } from "@/types/evals"; + +export const iframe_form_filling: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-form-filling/", + ); + + await page.act({ + action: "type 'nunya' into the 'first name' field", + iframes: true, + }); + await page.act({ + action: "type 'business' into the 'last name' field", + iframes: true, + }); + await page.act({ + action: "type 'test@email.com' into the 'email' field", + iframes: true, + }); + await page.act({ + action: "click 'phone' as the preferred contact method", + iframes: true, + }); + await page.act({ + action: "type 'yooooooooooooooo' into the message box", + iframes: true, + }); + + const iframe = page.frameLocator("iframe"); + + const firstNameValue: string = await iframe + .locator('input[placeholder="Jane"]') + .inputValue(); + + const lastNameValue: string = await iframe + .locator('input[placeholder="Doe"]') + .inputValue(); + + const emailValue: string = await iframe + .locator('input[placeholder="jane@example.com"]') + .inputValue(); + + const contactValue: boolean = await iframe + .locator("xpath=/html/body/main/section[1]/form/fieldset/label[2]/input") + .isChecked(); + + const messageValue: string = await iframe + .locator('textarea[placeholder="Say hello…"]') + .inputValue(); + + const passed: boolean = + firstNameValue.toLowerCase().trim() === "nunya" && + lastNameValue.toLowerCase().trim() === "business" && + emailValue.toLowerCase() === "test@email.com" && + messageValue.toLowerCase() === "yooooooooooooooo" && + contactValue; + + return { + _success: passed, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/iframe_hn.ts b/sdk/stagehand-ts/evals/tasks/iframe_hn.ts new file mode 100644 index 0000000..8d7f523 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/iframe_hn.ts @@ -0,0 +1,58 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const iframe_hn: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-hn/", + ); + + const result = await page.extract({ + instruction: "extract the title of the first hackernews story", + schema: z.object({ + story_title: z.string(), + }), + iframes: true, + }); + + const title = result.story_title.toLowerCase(); + const expectedTitleSubstring = "overengineered anchor links"; + + if (!title.includes(expectedTitleSubstring)) { + logger.error({ + message: `Extracted title: ${title} does not contain expected substring: ${expectedTitleSubstring}`, + level: 0, + }); + return { + _success: false, + error: `Extracted title: ${title} does not contain expected substring: ${expectedTitleSubstring}`, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + return { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/iframe_same_proc.ts b/sdk/stagehand-ts/evals/tasks/iframe_same_proc.ts new file mode 100644 index 0000000..7e5adb8 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/iframe_same_proc.ts @@ -0,0 +1,57 @@ +import { EvalFunction } from "@/types/evals"; + +export const iframe_same_proc: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-same-proc/", + ); + + await page.act({ + action: "type 'stagehand' into the 'your name' field", + iframes: true, + }); + + // overly specific prompting is okay here. we are just trying to evaluate whether + // we are properly traversing iframes + await page.act({ + action: + "select 'Green' from the favorite colour dropdown. Ensure the word 'Green' is capitalized. Choose the selectOption playwright method.", + iframes: true, + }); + + const iframe = page.frameLocator("iframe"); + + const nameValue: string = await iframe + .locator('input[placeholder="Alice"]') + .inputValue(); + + const colorValue: string = await iframe.locator("select").inputValue(); + + const passed: boolean = + nameValue.toLowerCase().trim() === "stagehand" && + colorValue.toLowerCase().trim() === "green"; + + return { + _success: passed, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/iframe_scroll.ts b/sdk/stagehand-ts/evals/tasks/iframe_scroll.ts new file mode 100644 index 0000000..8091c08 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/iframe_scroll.ts @@ -0,0 +1,60 @@ +import { EvalFunction } from "@/types/evals"; + +export const iframe_scroll: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/iframe-same-proc-scroll/", + ); + await stagehand.page.act({ + action: "scroll down 50% inside the iframe", + iframes: true, + }); + + const frames = stagehand.page.frames(); + const frame = frames[1]; + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + // Get the current scroll position and total scroll height + const scrollInfo = await frame.evaluate(() => { + return { + scrollTop: window.scrollY + window.innerHeight / 2, + scrollHeight: document.documentElement.scrollHeight, + }; + }); + + const halfwayScroll = scrollInfo.scrollHeight / 2; + const halfwayReached = Math.abs(scrollInfo.scrollTop - halfwayScroll) <= 1; + const evaluationResult = halfwayReached + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll position (${scrollInfo.scrollTop}px) is not halfway down the page (${halfwayScroll}px).`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/iframes_nested.ts b/sdk/stagehand-ts/evals/tasks/iframes_nested.ts new file mode 100644 index 0000000..6fe9aff --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/iframes_nested.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; +import { FrameLocator } from "playwright"; + +export const iframes_nested: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/nested-iframes/", + ); + + await page.act({ + action: "type 'stagehand' into the 'username' field", + iframes: true, + }); + + const inner: FrameLocator = page + .frameLocator("iframe.lvl1") // level 1 + .frameLocator("iframe.lvl2") // level 2 + .frameLocator("iframe.lvl3"); // level 3 – form lives here + + const usernameText = await inner + .locator('input[name="username"]') + .inputValue(); + + const passed: boolean = usernameText.toLowerCase().trim() === "stagehand"; + + return { + _success: passed, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/imdb_movie_details.ts b/sdk/stagehand-ts/evals/tasks/imdb_movie_details.ts new file mode 100644 index 0000000..a2ea3bf --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/imdb_movie_details.ts @@ -0,0 +1,107 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const imdb_movie_details: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.imdb.com/title/tt0111161/", { + waitUntil: "domcontentloaded", + }); + await stagehand.page.act({ + action: "click on the movie ratings", + }); + + const movieDetails = await stagehand.page.extract({ + instruction: "Extract the list of countries with the most ratings.", + schema: z.object({ + countries: z + .array(z.string()) + .describe("List of countries with the most ratings"), + }), + }); + + const expectedCountries = [ + "United States", + "United Kingdom", + "Turkey", + "India", + "Germany", + ]; + + if (!movieDetails.countries || movieDetails.countries.length !== 5) { + logger.error({ + message: "Failed to extract exactly five countries", + level: 0, + auxiliary: { + expected: { + value: JSON.stringify(expectedCountries), + type: "object", + }, + actual: { + value: JSON.stringify(movieDetails.countries || []), + type: "object", + }, + }, + }); + + return { + _success: false, + error: "Incorrect number of countries extracted", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + const missingCountries = expectedCountries.filter( + (country) => !movieDetails.countries.includes(country), + ); + + if (missingCountries.length > 0) { + logger.error({ + message: "Extracted countries do not match expected countries", + level: 0, + auxiliary: { + missing: { + value: JSON.stringify(missingCountries), + type: "object", + }, + extracted: { + value: JSON.stringify(movieDetails.countries), + type: "object", + }, + }, + }); + + return { + _success: false, + error: "Extracted countries do not match expected countries", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + return { + _success: true, + countries: movieDetails.countries, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/instructions.ts b/sdk/stagehand-ts/evals/tasks/instructions.ts new file mode 100644 index 0000000..eda0663 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/instructions.ts @@ -0,0 +1,42 @@ +import { EvalFunction } from "@/types/evals"; + +export const instructions: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + const page = stagehand.page; + + await page.goto("https://docs.browserbase.com/"); + + await page.act({ + action: "secret12345", + }); + + await page.waitForLoadState("domcontentloaded"); + + const url = page.url(); + + const isCorrectUrl = + url === "https://docs.browserbase.com/introduction/what-is-browserbase"; + + return { + _success: isCorrectUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/ionwave.ts b/sdk/stagehand-ts/evals/tasks/ionwave.ts new file mode 100644 index 0000000..fa36bb7 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/ionwave.ts @@ -0,0 +1,40 @@ +import { EvalFunction } from "@/types/evals"; + +export const ionwave: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/ionwave/", + ); + + await stagehand.page.act({ + action: 'Click on "Closed Bids"', + }); + + const expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/ionwave/closed-bids.html"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl.startsWith(expectedUrl), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/ionwave_observe.ts b/sdk/stagehand-ts/evals/tasks/ionwave_observe.ts new file mode 100644 index 0000000..fb3fe88 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/ionwave_observe.ts @@ -0,0 +1,73 @@ +import { EvalFunction } from "@/types/evals"; + +export const ionwave_observe: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/ionwave/", + ); + + const observations = await stagehand.page.observe(); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const expectedLocator = `#Form1 > div:nth-child(5) > div:nth-child(1) > a`; + + const expectedResult = await stagehand.page + .locator(expectedLocator) + .first() + .innerText(); + + let foundMatch = false; + for (const observation of observations) { + try { + const observationResult = await stagehand.page + .locator(observation.selector) + .first() + .innerText(); + + if (observationResult === expectedResult) { + foundMatch = true; + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + expected: expectedResult, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/login.ts b/sdk/stagehand-ts/evals/tasks/login.ts new file mode 100644 index 0000000..ef9ea3e --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/login.ts @@ -0,0 +1,45 @@ +import { EvalFunction } from "@/types/evals"; + +export const login: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/login/", + ); + + await stagehand.page.act({ + action: "type %nunya% into the username field", + variables: { + nunya: "business", + }, + }); + + const xpath = "xpath=/html/body/main/form/div[1]/input"; + const actualValue = await stagehand.page.locator(xpath).inputValue(); + + const expectedValue = "business"; + + return { + _success: actualValue === expectedValue, + expectedValue, + actualValue, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/multi_tab.ts b/sdk/stagehand-ts/evals/tasks/multi_tab.ts new file mode 100644 index 0000000..b73efcc --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/multi_tab.ts @@ -0,0 +1,92 @@ +import { EvalFunction } from "@/types/evals"; + +export const multi_tab: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + const stagehandPage = stagehand.page; + await stagehandPage.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/", + ); + + await stagehandPage.act({ + action: "click the button to open the other page", + }); + await stagehandPage.act({ + action: "click the button to open the other page", + }); + await stagehandPage.act({ + action: "click the button to open the other page", + }); + await stagehandPage.act({ + action: "click the button to open the other page", + }); + + let currentPageUrl = stagehandPage.url(); + let expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/page5.html"; + + if (currentPageUrl !== expectedUrl) { + return { + _success: false, + message: "expected URL does not match current URL", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + // try acting on the first page again + const pages = stagehand.context.pages(); + const page1 = pages[0]; + await page1.act({ + action: "click the button to open the other page", + }); + + // stagehandPage.url() should point to the URL of the active page + currentPageUrl = stagehandPage.url(); + expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/five-tab/page2.html"; + if (currentPageUrl !== expectedUrl) { + return { + _success: false, + message: "expected URL does not match current URL", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const page2text = await stagehandPage.extract(); + const expectedPage2text = "You've made it to page 2"; + + if (page2text.page_text.includes(expectedPage2text)) { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `extracted page text: ${page2text.page_text} does not match expected page text: ${expectedPage2text}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/namespace_xpath.ts b/sdk/stagehand-ts/evals/tasks/namespace_xpath.ts new file mode 100644 index 0000000..fe12f50 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/namespace_xpath.ts @@ -0,0 +1,39 @@ +import { EvalFunction } from "@/types/evals"; + +export const namespace_xpath: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/namespaced-xpath/", + ); + + await stagehand.page.act({ + action: "fill 'nunya' into the 'type here' form", + }); + + const inputValue = await stagehand.page.locator("#ns-text").inputValue(); + // confirm that the form was filled + const formHasBeenFilled = inputValue === "nunya"; + + return { + _success: formHasBeenFilled, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/nested_iframes_2.ts b/sdk/stagehand-ts/evals/tasks/nested_iframes_2.ts new file mode 100644 index 0000000..e777673 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/nested_iframes_2.ts @@ -0,0 +1,48 @@ +import { EvalFunction } from "@/types/evals"; +import { FrameLocator } from "playwright"; + +export const nested_iframes_2: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/nested-iframes-2/", + ); + + await page.act({ + action: "click the button called 'click me (inner 2)'", + iframes: true, + }); + + const inner: FrameLocator = page + .frameLocator('iframe[src="iframe2.html"]') + .frameLocator('iframe[src="inner2.html"]'); + + const messageText = await inner.locator("#msg").textContent(); + + const passed: boolean = + messageText.toLowerCase().trim() === + "clicked the button in the second inner iframe"; + + return { + _success: passed, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + error, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/nextChunk.ts b/sdk/stagehand-ts/evals/tasks/nextChunk.ts new file mode 100644 index 0000000..18f86ad --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/nextChunk.ts @@ -0,0 +1,85 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { EvalFunction } from "@/types/evals"; + +export const nextChunk: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + domSettleTimeoutMs: 3000, + }); + try { + await stagehand.init(); + + await stagehand.page.goto("https://www.apartments.com/san-francisco-ca/"); + await stagehand.page.act({ + action: "click on the all filters button", + }); + + const { initialScrollTop, chunkHeight } = await stagehand.page.evaluate( + () => { + const container = document.querySelector( + "#advancedFilters > div", + ) as HTMLElement; + if (!container) { + console.warn( + "Could not find #advancedFilters > div. Returning 0 for measurements.", + ); + return { initialScrollTop: 0, chunkHeight: 0 }; + } + return { + initialScrollTop: container.scrollTop, + chunkHeight: container.getBoundingClientRect().height, + }; + }, + ); + + await stagehand.page.act({ + action: "scroll down one chunk on the filters modal", + }); + + await new Promise((resolve) => setTimeout(resolve, 2000)); + + const newScrollTop = await stagehand.page.evaluate(() => { + const container = document.querySelector( + "#advancedFilters > div", + ) as HTMLElement; + return container?.scrollTop ?? 0; + }); + + const actualDiff = newScrollTop - initialScrollTop; + const threshold = 20; // allowable difference in px + const scrolledOneChunk = Math.abs(actualDiff - chunkHeight) <= threshold; + + const evaluationResult = scrolledOneChunk + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Successfully scrolled ~one chunk: expected ~${chunkHeight}, got ${actualDiff}`, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll difference expected ~${chunkHeight} but only scrolled ${actualDiff}.`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/no_js_click.ts b/sdk/stagehand-ts/evals/tasks/no_js_click.ts new file mode 100644 index 0000000..d4258a3 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/no_js_click.ts @@ -0,0 +1,56 @@ +import { EvalFunction } from "@/types/evals"; +import { ObserveResult } from "@/types/stagehand"; + +export const no_js_click: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + /** + * This eval is meant to test whether our `clickElement` function + * (inside actHandlerUtils.ts) is able to click elements even if + * the site blocks programmatic JS click events. + */ + + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/no-js-click/", + ); + + const observeResult: ObserveResult = { + method: "click", + selector: "xpath=/html/body/button", + description: "the button to click", + arguments: [], + }; + await stagehand.page.act(observeResult); + + const text = await stagehand.page.textContent("#success-msg"); + if (text?.trim() === "click succeeded") { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: "unable to click element on website that blocks JS click events", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error attempting to click the button: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/nonsense_action.ts b/sdk/stagehand-ts/evals/tasks/nonsense_action.ts new file mode 100644 index 0000000..3434677 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/nonsense_action.ts @@ -0,0 +1,33 @@ +import { EvalFunction } from "@/types/evals"; + +export const nonsense_action: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.homedepot.com/"); + + const result = await stagehand.page.act({ + action: "what is the capital of the moon?", + }); + + return { + _success: !result.success, // We expect this to fail + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_amazon_add_to_cart.ts b/sdk/stagehand-ts/evals/tasks/observe_amazon_add_to_cart.ts new file mode 100644 index 0000000..411d5aa --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_amazon_add_to_cart.ts @@ -0,0 +1,61 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_amazon_add_to_cart: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/amazon/", + ); + + await stagehand.page.waitForTimeout(5000); + + const observations1 = await stagehand.page.observe({ + instruction: "Find and click the 'Add to Cart' button", + }); + + // Example of using performPlaywrightMethod if you have the xpath + if (observations1.length > 0) { + const action1 = observations1[0]; + await stagehand.page.act(action1); + } + + await stagehand.page.waitForTimeout(2000); + + const observations2 = await stagehand.page.observe({ + instruction: "Find and click the 'Proceed to checkout' button", + }); + + // Example of using performPlaywrightMethod if you have the xpath + if (observations2.length > 0) { + const action2 = observations2[0]; + await stagehand.page.act(action2); + } + await stagehand.page.waitForTimeout(2000); + + const currentUrl = stagehand.page.url(); + const expectedUrlPrefix = + "https://browserbase.github.io/stagehand-eval-sites/sites/amazon/sign-in.html"; + + return { + _success: currentUrl.startsWith(expectedUrlPrefix), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_github.ts b/sdk/stagehand-ts/evals/tasks/observe_github.ts new file mode 100644 index 0000000..f337668 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_github.ts @@ -0,0 +1,106 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_github: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/github/", + ); + + const observations = await stagehand.page.observe({ + instruction: + "find the scrollable element that holds the repos file tree.", + }); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const possibleLocators = [ + `#repo-content-pjax-container > react-app > div > div > div.prc-PageLayout-PageLayoutRoot-1zlEO > div > div > div.Box-sc-g0xbh4-0.gISSDQ`, + `#repo-content-pjax-container > react-app > div > div > div.prc-PageLayout-PageLayoutRoot-1zlEO > div > div > div.Box-sc-g0xbh4-0.gISSDQ > div`, + `#repo-content-pjax-container > react-app > div > div > div.prc-PageLayout-PageLayoutRoot-1zlEO > div > div > div.Box-sc-g0xbh4-0.gISSDQ > div > div.prc-PageLayout-Pane-Vl5LI`, + `#repo-content-pjax-container > react-app > div > div > div.prc-PageLayout-PageLayoutRoot-1zlEO > div > div > div.Box-sc-g0xbh4-0.gISSDQ > div > div.prc-PageLayout-Pane-Vl5LI > div`, + `#repos-file-tree > div.Box-sc-g0xbh4-0.ReposFileTreePane-module__Box_5--tQNH_`, + `#repos-file-tree > div.Box-sc-g0xbh4-0.ReposFileTreePane-module__Box_5--tQNH_ > div`, + `#repos-file-tree > div.Box-sc-g0xbh4-0.ReposFileTreePane-module__Box_5--tQNH_ > div > div`, + `#repos-file-tree > div.Box-sc-g0xbh4-0.ReposFileTreePane-module__Box_5--tQNH_ > div > div > div > nav`, + `#repos-file-tree > div.Box-sc-g0xbh4-0.ReposFileTreePane-module__Box_5--tQNH_ > div > div > div > nav > ul`, + ]; + + const possibleHandles = []; + for (const locatorStr of possibleLocators) { + const locator = stagehand.page.locator(locatorStr); + const handle = await locator.elementHandle(); + if (handle) { + possibleHandles.push({ locatorStr, handle }); + } + } + + let foundMatch = false; + let matchedLocator: string | null = null; + + for (const observation of observations) { + try { + const observationLocator = stagehand.page + .locator(observation.selector) + .first(); + const observationHandle = await observationLocator.elementHandle(); + if (!observationHandle) { + continue; + } + + for (const { locatorStr, handle: candidateHandle } of possibleHandles) { + const isSameNode = await observationHandle.evaluate( + (node, otherNode) => node === otherNode, + candidateHandle, + ); + if (isSameNode) { + foundMatch = true; + matchedLocator = locatorStr; + break; + } + } + + if (foundMatch) { + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + matchedLocator, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_iframes1.ts b/sdk/stagehand-ts/evals/tasks/observe_iframes1.ts new file mode 100644 index 0000000..21b1beb --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_iframes1.ts @@ -0,0 +1,96 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_iframes1: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://tucowsdomains.com/abuse-form/phishing/"); + + const observations = await stagehand.page.observe({ + instruction: "find the main header of the page", + }); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const possibleLocators = [ + `#primary > div.singlePage > section > div > div > article > div > iframe`, + `#primary > div.heroBanner > section > div > h1`, + ]; + + const possibleHandles = []; + for (const locatorStr of possibleLocators) { + const locator = stagehand.page.locator(locatorStr); + const handle = await locator.elementHandle(); + if (handle) { + possibleHandles.push({ locatorStr, handle }); + } + } + + let foundMatch = false; + let matchedLocator: string | null = null; + + for (const observation of observations) { + try { + const observationLocator = stagehand.page + .locator(observation.selector) + .first(); + const observationHandle = await observationLocator.elementHandle(); + if (!observationHandle) { + continue; + } + + for (const { locatorStr, handle: candidateHandle } of possibleHandles) { + const isSameNode = await observationHandle.evaluate( + (node, otherNode) => node === otherNode, + candidateHandle, + ); + if (isSameNode) { + foundMatch = true; + matchedLocator = locatorStr; + break; + } + } + + if (foundMatch) { + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + matchedLocator, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_iframes2.ts b/sdk/stagehand-ts/evals/tasks/observe_iframes2.ts new file mode 100644 index 0000000..25277d1 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_iframes2.ts @@ -0,0 +1,113 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { EvalFunction } from "@/types/evals"; +import { ObserveResult } from "@/types/stagehand"; + +export const observe_iframes2: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + }); + await stagehand.init(); + try { + await stagehand.page.goto( + "https://iframetester.com/?url=https://shopify.com", + ); + await new Promise((resolve) => setTimeout(resolve, 5000)); + + let observations: ObserveResult[]; + try { + observations = await stagehand.page.observe({ + instruction: "find the main header of the page", + }); + } catch (err) { + return { + _success: false, + message: err.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const possibleLocators = [`#iframe-window`, `body > header > h1`]; + + const possibleHandles = []; + for (const locatorStr of possibleLocators) { + const locator = stagehand.page.locator(locatorStr); + const handle = await locator.elementHandle(); + if (handle) { + possibleHandles.push({ locatorStr, handle }); + } + } + + let foundMatch = false; + let matchedLocator: string | null = null; + + for (const observation of observations) { + try { + const observationLocator = stagehand.page + .locator(observation.selector) + .first(); + const observationHandle = await observationLocator.elementHandle(); + if (!observationHandle) { + continue; + } + + for (const { locatorStr, handle: candidateHandle } of possibleHandles) { + const isSameNode = await observationHandle.evaluate( + (node, otherNode) => node === otherNode, + candidateHandle, + ); + if (isSameNode) { + foundMatch = true; + matchedLocator = locatorStr; + break; + } + } + + if (foundMatch) { + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + matchedLocator, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_simple_google_search.ts b/sdk/stagehand-ts/evals/tasks/observe_simple_google_search.ts new file mode 100644 index 0000000..65e85e7 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_simple_google_search.ts @@ -0,0 +1,52 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_simple_google_search: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/google/", + ); + const observation1 = await stagehand.page.observe({ + instruction: "Find the search bar and type 'OpenAI'", + }); + + if (observation1.length > 0) { + const action1 = observation1[0]; + await stagehand.page.act(action1); + } + const observation2 = await stagehand.page.observe({ + instruction: "Click the search button in the suggestions dropdown", + }); + + if (observation2.length > 0) { + const action2 = observation2[0]; + await stagehand.page.act(action2); + } + + const expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/google/openai.html"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl.startsWith(expectedUrl), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_taxes.ts b/sdk/stagehand-ts/evals/tasks/observe_taxes.ts new file mode 100644 index 0000000..40bb071 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_taxes.ts @@ -0,0 +1,82 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_taxes: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://file.1040.com/estimate/"); + + const observations = await stagehand.page.observe({ + instruction: + "Find all the form input elements under the 'Income' section", + }); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } else if (observations.length < 13) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const expectedLocator = `#tpWages`; + + const expectedResult = await stagehand.page + .locator(expectedLocator) + .first() + .innerText(); + + let foundMatch = false; + for (const observation of observations) { + try { + const observationResult = await stagehand.page + .locator(observation.selector) + .first() + .innerText(); + + if (observationResult === expectedResult) { + foundMatch = true; + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + expected: expectedResult, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_vantechjournal.ts b/sdk/stagehand-ts/evals/tasks/observe_vantechjournal.ts new file mode 100644 index 0000000..d8efa27 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_vantechjournal.ts @@ -0,0 +1,83 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_vantechjournal: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://vantechjournal.com/archive"); + await stagehand.page.waitForTimeout(1000); + + const observations = await stagehand.page.observe({ + instruction: "Find the 'load more' link", + }); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const expectedLocator = `xpath=/html/body/div[3]/section/div/div/div[3]/a`; + + const expectedResult = await stagehand.page.locator(expectedLocator); + + let foundMatch = false; + + for (const observation of observations) { + try { + const observationLocator = stagehand.page + .locator(observation.selector) + .first(); + const observationHandle = await observationLocator.elementHandle(); + const expectedHandle = await expectedResult.elementHandle(); + + if (!observationHandle || !expectedHandle) { + // Couldn’t get handles, skip + continue; + } + + const isSameNode = await observationHandle.evaluate( + (node, otherNode) => node === otherNode, + expectedHandle, + ); + + if (isSameNode) { + foundMatch = true; + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + expected: expectedResult, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/observe_yc_startup.ts b/sdk/stagehand-ts/evals/tasks/observe_yc_startup.ts new file mode 100644 index 0000000..451e780 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/observe_yc_startup.ts @@ -0,0 +1,98 @@ +import { EvalFunction } from "@/types/evals"; + +export const observe_yc_startup: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.ycombinator.com/companies"); + await stagehand.page.waitForLoadState("networkidle"); + + const observations = await stagehand.page.observe({ + instruction: + "Click the container element that holds links to each of the startup companies. The companies each have a name, a description, and a link to their website.", + }); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const possibleLocators = [ + `div._rightCol_i9oky_592`, + `div._section_i9oky_163._results_i9oky_343`, + ]; + + const possibleHandles = []; + for (const locatorStr of possibleLocators) { + const locator = stagehand.page.locator(locatorStr); + const handle = await locator.elementHandle(); + if (handle) { + possibleHandles.push({ locatorStr, handle }); + } + } + + let foundMatch = false; + let matchedLocator: string | null = null; + + for (const observation of observations) { + try { + const observationLocator = stagehand.page + .locator(observation.selector) + .first(); + const observationHandle = await observationLocator.elementHandle(); + if (!observationHandle) { + continue; + } + + for (const { locatorStr, handle: candidateHandle } of possibleHandles) { + const isSameNode = await observationHandle.evaluate( + (node, otherNode) => node === otherNode, + candidateHandle, + ); + if (isSameNode) { + foundMatch = true; + matchedLocator = locatorStr; + break; + } + } + + if (foundMatch) { + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + matchedLocator, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/oopif_in_csr.ts b/sdk/stagehand-ts/evals/tasks/oopif_in_csr.ts new file mode 100644 index 0000000..7badd3c --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/oopif_in_csr.ts @@ -0,0 +1,57 @@ +import { EvalFunction } from "@/types/evals"; + +export const oopif_in_csr: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // fill a form inside a OOPIF (out of process iframe) that is inside an + // CSR (closed mode shadow) root + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/oopif-in-open-shadow-dom/", + ); + await page.act({ + action: "fill 'nunya' into the first name field", + iframes: true, + }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("nunya")) { + return { + _success: true, + message: `successfully filled the form`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to fill the form`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/oopif_in_osr.ts b/sdk/stagehand-ts/evals/tasks/oopif_in_osr.ts new file mode 100644 index 0000000..32385b1 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/oopif_in_osr.ts @@ -0,0 +1,57 @@ +import { EvalFunction } from "@/types/evals"; + +export const oopif_in_osr: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // fill a form inside a OOPIF (out of process iframe) that is inside an + // OSR (open mode shadow) root + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/oopif-in-open-shadow-dom/", + ); + await page.act({ + action: "fill 'nunya' into the first name field", + iframes: true, + }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("nunya")) { + return { + _success: true, + message: `successfully filled the form`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to fill the form`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/os_dropdown.ts b/sdk/stagehand-ts/evals/tasks/os_dropdown.ts new file mode 100644 index 0000000..e727611 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/os_dropdown.ts @@ -0,0 +1,53 @@ +import { EvalFunction } from "@/types/evals"; + +export const os_dropdown: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + /** + * This eval is meant to test whether we can correctly select an element + * from an OS level dropdown + */ + + try { + const page = stagehand.page; + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/nested-dropdown/", + ); + + await page.act( + "choose 'Smog Check Technician' from the 'License Type' dropdown", + ); + const selectedOption = await page + .locator("#licenseType >> option:checked") + .textContent(); + + if (selectedOption === "Smog Check Technician") { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: "incorrect option selected from the dropdown", + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error attempting to select an option from the dropdown: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/osr_in_oopif.ts b/sdk/stagehand-ts/evals/tasks/osr_in_oopif.ts new file mode 100644 index 0000000..47ae0ab --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/osr_in_oopif.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const osr_in_oopif: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside an OSR (open mode shadow) root that is inside an + // OOPIF (out of process iframe) + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/open-shadow-root-in-oopif/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/osr_in_spif.ts b/sdk/stagehand-ts/evals/tasks/osr_in_spif.ts new file mode 100644 index 0000000..86cb1be --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/osr_in_spif.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const osr_in_spif: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside an OSR (open mode shadow) root that is inside an + // SPIF (same process iframe) + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/open-shadow-root-in-spif/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/panamcs.ts b/sdk/stagehand-ts/evals/tasks/panamcs.ts new file mode 100644 index 0000000..1261fa0 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/panamcs.ts @@ -0,0 +1,75 @@ +import { EvalFunction } from "@/types/evals"; + +export const panamcs: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/panamcs/", + ); + + const observations = await stagehand.page.observe( + "click the 'about us' link", + ); + + if (observations.length === 0) { + return { + _success: false, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + const expectedLocator = `#menu > li:nth-child(1) > a`; + + const expectedResult = await stagehand.page + .locator(expectedLocator) + .first() + .innerText(); + + let foundMatch = false; + for (const observation of observations) { + try { + const observationResult = await stagehand.page + .locator(observation.selector) + .first() + .innerText(); + + if (observationResult === expectedResult) { + foundMatch = true; + break; + } + } catch (error) { + console.warn( + `Failed to check observation with selector ${observation.selector}:`, + error.message, + ); + continue; + } + } + + return { + _success: foundMatch, + expected: expectedResult, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/peeler_complex.ts b/sdk/stagehand-ts/evals/tasks/peeler_complex.ts new file mode 100644 index 0000000..c556dc4 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/peeler_complex.ts @@ -0,0 +1,64 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const peeler_complex: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto(`https://chefstoys.com/`, { timeout: 60000 }); + await stagehand.page.waitForLoadState("networkidle"); + + await stagehand.page.act("find the button to close the popup"); + await stagehand.page.act({ + action: "search for %search_query%", + variables: { + search_query: "peeler", + }, + }); + + await stagehand.page.act({ + action: 'click on the first "OXO" brand peeler', + }); + + const { price } = await stagehand.page.extract({ + instruction: "get the price of the peeler", + schema: z.object({ price: z.number().nullable() }), + }); + + return { + _success: price === 11.99, + price, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + logger.error({ + message: "error in peeler_complex function", + level: 0, + auxiliary: { + error: { + value: JSON.stringify(error, null, 2), + type: "object", + }, + trace: { + value: error.stack, + type: "string", + }, + }, + }); + + return { + _success: false, + error: JSON.parse(JSON.stringify(error, null, 2)), + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/peeler_simple.ts b/sdk/stagehand-ts/evals/tasks/peeler_simple.ts new file mode 100644 index 0000000..12628c6 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/peeler_simple.ts @@ -0,0 +1,39 @@ +import { EvalFunction } from "@/types/evals"; +import { StagehandEnvironmentError } from "@/types/stagehandErrors"; + +const env: "BROWSERBASE" | "LOCAL" = + process.env.EVAL_ENV?.toLowerCase() === "browserbase" + ? "BROWSERBASE" + : "LOCAL"; + +export const peeler_simple: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + if (env === "BROWSERBASE") { + throw new StagehandEnvironmentError( + "BROWSERBASE", + "LOCAL", + "peeler_simple eval", + ); + } + + await stagehand.page.goto(`file://${process.cwd()}/evals/assets/peeler.html`); + await stagehand.page.act({ action: "add the peeler to cart" }); + + const successMessageLocator = stagehand.page.locator( + 'text="Congratulations, you have 1 A in your cart"', + ); + const isVisible = await successMessageLocator.isVisible(); + + await stagehand.close(); + + return { + _success: isVisible, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; +}; diff --git a/sdk/stagehand-ts/evals/tasks/prevChunk.ts b/sdk/stagehand-ts/evals/tasks/prevChunk.ts new file mode 100644 index 0000000..67197a5 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/prevChunk.ts @@ -0,0 +1,79 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { EvalFunction } from "@/types/evals"; + +export const prevChunk: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + domSettleTimeoutMs: 3000, + }); + await stagehand.init(); + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/aigrant/", + ); + await new Promise((resolve) => setTimeout(resolve, 2000)); + const { initialScrollTop, chunkHeight } = await stagehand.page.evaluate( + () => { + const halfPage = document.body.scrollHeight / 2; + + window.scrollTo({ + top: halfPage, + left: 0, + behavior: "instant", + }); + + const chunk = window.innerHeight; + + return { + initialScrollTop: window.scrollY, + chunkHeight: chunk, + }; + }, + ); + await new Promise((resolve) => setTimeout(resolve, 2000)); + await stagehand.page.act({ + action: "scroll up one chunk", + }); + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + const finalScrollTop = await stagehand.page.evaluate(() => window.scrollY); + + const actualDiff = initialScrollTop - finalScrollTop; + const threshold = 20; // px tolerance + const scrolledOneChunk = Math.abs(actualDiff - chunkHeight) <= threshold; + + const evaluationResult = scrolledOneChunk + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Successfully scrolled ~one chunk UP: expected ~${chunkHeight}, got ${actualDiff}.`, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll difference expected ~${chunkHeight} but only scrolled ${actualDiff}.`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/radio_btn.ts b/sdk/stagehand-ts/evals/tasks/radio_btn.ts new file mode 100644 index 0000000..f5a2f95 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/radio_btn.ts @@ -0,0 +1,40 @@ +import { EvalFunction } from "@/types/evals"; + +export const radio_btn: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/paneer-pizza/", + ); + + await stagehand.page.act({ + action: "click the 'medium' option", + }); + + // confirm that the Medium radio is now checked + const radioBtnClicked = await stagehand.page + .locator('input[type="radio"][name="Pizza"][value="Medium"]') + .isChecked(); + + return { + _success: radioBtnClicked, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/rakuten_jp.ts b/sdk/stagehand-ts/evals/tasks/rakuten_jp.ts new file mode 100644 index 0000000..4d22c73 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/rakuten_jp.ts @@ -0,0 +1,35 @@ +import { EvalFunction } from "@/types/evals"; + +export const rakuten_jp: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.rakuten.co.jp/"); + + await stagehand.page.act({ action: "type '香菜' into the search bar" }); + await stagehand.page.act({ action: "press enter" }); + const url = stagehand.page.url(); + const successUrl = + "https://search.rakuten.co.jp/search/mall/%E9%A6%99%E8%8F%9C/"; + + return { + _success: url === successUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/sciquest.ts b/sdk/stagehand-ts/evals/tasks/sciquest.ts new file mode 100644 index 0000000..6d965e5 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/sciquest.ts @@ -0,0 +1,79 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const sciquest: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://bids.sciquest.com/apps/Router/PublicEvent?tab=PHX_NAV_SourcingAllOpps&CustomerOrg=StateOfUtah", + ); + + await stagehand.page.act({ + action: 'Click on the "Closed" tab', + }); + + const result = await stagehand.page.extract({ + instruction: + "Extract the total number of results that the search produced. Not the number of results displayed on the page.", + schema: z.object({ + total_results: z.string(), + }), + }); + + const { total_results } = result; + + const expectedNumber = 12637; + const extractedNumber = parseInt(total_results.replace(/[^\d]/g, ""), 10); + + const isWithinRange = + extractedNumber >= expectedNumber - 1000 && + extractedNumber <= expectedNumber + 1000; + + if (!isWithinRange) { + logger.error({ + message: "Total number of results is not within the expected range", + level: 0, + auxiliary: { + expected: { + value: `${expectedNumber} ± 1000`, + type: "string", + }, + actual: { + value: extractedNumber.toString(), + type: "integer", + }, + }, + }); + return { + _success: false, + error: "Total number of results is not within the expected range", + extractedNumber, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + extractedNumber, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/scroll_50.ts b/sdk/stagehand-ts/evals/tasks/scroll_50.ts new file mode 100644 index 0000000..81e7d07 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/scroll_50.ts @@ -0,0 +1,57 @@ +import { EvalFunction } from "@/types/evals"; + +export const scroll_50: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/aigrant/", + ); + await stagehand.page.act({ + action: "Scroll 50% down the page", + }); + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + // Get the current scroll position and total scroll height + const scrollInfo = await stagehand.page.evaluate(() => { + return { + scrollTop: window.scrollY + window.innerHeight / 2, + scrollHeight: document.documentElement.scrollHeight, + }; + }); + + const halfwayScroll = scrollInfo.scrollHeight / 2; + const halfwayReached = + Math.abs(scrollInfo.scrollTop - halfwayScroll) <= 200; + const evaluationResult = halfwayReached + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll position (${scrollInfo.scrollTop}px) is not halfway down the page (${halfwayScroll}px).`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/scroll_75.ts b/sdk/stagehand-ts/evals/tasks/scroll_75.ts new file mode 100644 index 0000000..32544c8 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/scroll_75.ts @@ -0,0 +1,64 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { EvalFunction } from "@/types/evals"; + +export const scroll_75: EvalFunction = async ({ + logger, + stagehandConfig, + debugUrl, + sessionUrl, +}) => { + const stagehand = new Stagehand({ + ...stagehandConfig, + domSettleTimeoutMs: 3000, + }); + await stagehand.init(); + + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/aigrant/", + ); + await stagehand.page.act({ + action: "Scroll 75% down the page", + }); + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + // Get the current scroll position and total scroll height + const scrollInfo = await stagehand.page.evaluate(() => { + return { + scrollTop: window.scrollY + window.innerHeight * 0.75, + scrollHeight: document.documentElement.scrollHeight, + }; + }); + + const threeQuartersScroll = scrollInfo.scrollHeight * 0.75; + const threeQuartersReached = + Math.abs(scrollInfo.scrollTop - threeQuartersScroll) <= 200; + const evaluationResult = threeQuartersReached + ? { + _success: true, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + } + : { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + message: `Scroll position (${scrollInfo.scrollTop}px) is not three quarters down the page (${threeQuartersScroll}px).`, + }; + + return evaluationResult; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/shadow_dom.ts b/sdk/stagehand-ts/evals/tasks/shadow_dom.ts new file mode 100644 index 0000000..52cadb3 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/shadow_dom.ts @@ -0,0 +1,46 @@ +import { EvalFunction } from "@/types/evals"; + +export const shadow_dom: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/shadow-dom/", + ); + await page.act("click the button"); + const extraction = await page.extract({ + instruction: "extract the page text", + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/simple_google_search.ts b/sdk/stagehand-ts/evals/tasks/simple_google_search.ts new file mode 100644 index 0000000..822251d --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/simple_google_search.ts @@ -0,0 +1,42 @@ +import { EvalFunction } from "@/types/evals"; + +export const simple_google_search: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/google/", + ); + + await stagehand.page.act({ + action: 'type "OpenAI" into the search bar', + }); + + await stagehand.page.act("click the search button"); + + const expectedUrl = + "https://browserbase.github.io/stagehand-eval-sites/sites/google/openai.html"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl.startsWith(expectedUrl), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/spif_in_csr.ts b/sdk/stagehand-ts/evals/tasks/spif_in_csr.ts new file mode 100644 index 0000000..b12ac63 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/spif_in_csr.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const spif_in_csr: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside a SPIF (same process iframe) that is inside an + // CSR (closed mode shadow) root + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/spif-in-closed-shadow-dom/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/spif_in_osr.ts b/sdk/stagehand-ts/evals/tasks/spif_in_osr.ts new file mode 100644 index 0000000..75cdbbe --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/spif_in_osr.ts @@ -0,0 +1,54 @@ +import { EvalFunction } from "@/types/evals"; + +export const spif_in_osr: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + // this eval is designed to test whether stagehand can successfully + // click inside a SPIF (same process iframe) that is inside an + // OSR (open mode shadow) root + + const page = stagehand.page; + try { + await page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/spif-in-open-shadow-dom/", + ); + await page.act({ action: "click the button", iframes: true }); + + const extraction = await page.extract({ + instruction: "extract the entire page text", + iframes: true, + }); + + const pageText = extraction.extraction; + + if (pageText.includes("button successfully clicked")) { + return { + _success: true, + message: `successfully clicked the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + return { + _success: false, + message: `unable to click on the button`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: `error: ${error.message}`, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/stock_x.ts b/sdk/stagehand-ts/evals/tasks/stock_x.ts new file mode 100644 index 0000000..8dad158 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/stock_x.ts @@ -0,0 +1,44 @@ +import { EvalFunction } from "@/types/evals"; + +export const stock_x: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://stockx.com/air-jordan-3-retro-black-cement-2024", + ); + + await stagehand.page.waitForTimeout(3000); + + await stagehand.page.act({ + action: "click on Jordan 3 Retro Crimson in the related products", + }); + + await stagehand.page.waitForTimeout(2000); + const currentUrl = stagehand.page.url(); + const expectedUrlPrefix = "https://stockx.com/jordan-3-retro-crimson"; + + await stagehand.close(); + + return { + _success: currentUrl.startsWith(expectedUrlPrefix), + currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/tab_handling.ts b/sdk/stagehand-ts/evals/tasks/tab_handling.ts new file mode 100644 index 0000000..36d4b93 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/tab_handling.ts @@ -0,0 +1,49 @@ +import { EvalFunction } from "@/types/evals"; + +export const tab_handling: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://browserbase.github.io/stagehand-eval-sites/sites/new-tab/", + ); + + await stagehand.page.act({ + action: "click the button to open the other page", + }); + + const pages = stagehand.context.pages(); + const page1 = pages[0]; + const page2 = pages[1]; + + // extract all the text from the first page + const extraction1 = await page1.extract(); + // extract all the text from the second page + const extraction2 = await page2.extract(); + + const extraction1Success = extraction1.page_text.includes("Welcome!"); + const extraction2Success = extraction2.page_text.includes( + "You’re on the other page", + ); + + return { + _success: extraction1Success && extraction2Success, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + message: error.message, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/ted_talk.ts b/sdk/stagehand-ts/evals/tasks/ted_talk.ts new file mode 100644 index 0000000..bb48dc1 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/ted_talk.ts @@ -0,0 +1,130 @@ +import { EvalFunction } from "@/types/evals"; +import { normalizeString } from "@/evals/utils"; +import { z } from "zod/v3"; + +export const ted_talk: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto( + "https://www.ted.com/talks/sir_ken_robinson_do_schools_kill_creativity", + { + waitUntil: "domcontentloaded", + }, + ); + + await stagehand.page.act({ + action: "scroll 10% down the page", + }); + + await new Promise((resolve) => setTimeout(resolve, 5000)); + + await stagehand.page.act({ + action: + "Click the link that takes you to the page about the 'Culture' topic", + }); + + const playlists = await stagehand.page.extract({ + instruction: + "Extract the video playlist titles and the number of talks in each playlist. This info is in the Video Playlists about Culture section of the webpage.", + schema: z.object({ + playlists: z + .array( + z.object({ + title: z.string().describe("Title of the playlist"), + num_talks: z.number().describe("Number of talks in the playlist"), + }), + ) + .describe("List of culture video playlists"), + }), + }); + + const expectedPlaylists = [ + { + title: "Talks that celebrate the boundless creativity of an open mind", + num_talks: 6, + }, + { + title: "Little-known big history", + num_talks: 15, + }, + { + title: "Extraordinary, larger-than-life art", + num_talks: 10, + }, + { + title: "How perfectionism fails us", + num_talks: 4, + }, + ]; + + if (!playlists.playlists || playlists.playlists.length === 0) { + logger.error({ + message: "Failed to extract playlists on culture", + level: 0, + }); + + return { + _success: false, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + const missingPlaylists = expectedPlaylists.filter((expected) => + playlists.playlists.every( + (extracted) => + normalizeString(extracted.title) !== + normalizeString(expected.title) || + extracted.num_talks !== expected.num_talks, + ), + ); + + if (missingPlaylists.length > 0) { + logger.error({ + message: "Extracted playlists do not match expected playlists", + level: 0, + auxiliary: { + missing: { + value: JSON.stringify(missingPlaylists), + type: "object", + }, + extracted: { + value: JSON.stringify(playlists.playlists), + type: "object", + }, + }, + }); + + return { + _success: false, + error: "Extracted playlists do not match expected playlists", + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } + + return { + _success: true, + playlists: playlists.playlists, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } catch (error) { + return { + _success: false, + error: error, + logs: logger.getLogs(), + debugUrl, + sessionUrl, + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/vanta_h.ts b/sdk/stagehand-ts/evals/tasks/vanta_h.ts new file mode 100644 index 0000000..91dca44 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/vanta_h.ts @@ -0,0 +1,35 @@ +import { EvalFunction } from "@/types/evals"; + +export const vanta_h: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.vanta.com/"); + + const observations = await stagehand.page.observe( + "click the buy now button if it is available", + ); + + // we should have no saved observation since the element shouldn't exist + return { + _success: observations.length === 0, + observations, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/vantechjournal.ts b/sdk/stagehand-ts/evals/tasks/vantechjournal.ts new file mode 100644 index 0000000..7830595 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/vantechjournal.ts @@ -0,0 +1,38 @@ +import { EvalFunction } from "@/types/evals"; + +export const vantechjournal: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://vantechjournal.com"); + + await stagehand.page.act({ + action: "click on page 'recommendations'", + }); + + const expectedUrl = "https://vantechjournal.com/recommendations"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl === expectedUrl, + currentUrl, + expectedUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/wichita.ts b/sdk/stagehand-ts/evals/tasks/wichita.ts new file mode 100644 index 0000000..de9adf3 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/wichita.ts @@ -0,0 +1,76 @@ +import { EvalFunction } from "@/types/evals"; +import { z } from "zod/v3"; + +export const wichita: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto("https://www.wichitafallstx.gov/Bids.aspx"); + + await stagehand.page.act({ + action: 'Click on "Show Closed/Awarded/Cancelled bids"', + }); + + const result = await stagehand.page.extract({ + instruction: "Extract the total number of bids that the search produced.", + schema: z.object({ + total_results: z.string(), + }), + }); + + const { total_results } = result; + + const expectedNumber = 418; + const extractedNumber = parseInt(total_results.replace(/[^\d]/g, ""), 10); + + const isWithinRange = + extractedNumber >= expectedNumber - 10 && + extractedNumber <= expectedNumber + 10; + + if (!isWithinRange) { + logger.error({ + message: "Total number of results is not within the expected range", + level: 0, + auxiliary: { + expected: { + value: `${expectedNumber} ± 10`, + type: "string", + }, + actual: { + value: extractedNumber.toString(), + type: "integer", + }, + }, + }); + return { + _success: false, + error: "Total number of results is not within the expected range", + extractedNumber, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } + + return { + _success: true, + extractedNumber, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/tasks/wikipedia.ts b/sdk/stagehand-ts/evals/tasks/wikipedia.ts new file mode 100644 index 0000000..e3b5303 --- /dev/null +++ b/sdk/stagehand-ts/evals/tasks/wikipedia.ts @@ -0,0 +1,38 @@ +import { EvalFunction } from "@/types/evals"; + +export const wikipedia: EvalFunction = async ({ + debugUrl, + sessionUrl, + stagehand, + logger, +}) => { + try { + await stagehand.page.goto(`https://en.wikipedia.org/wiki/Baseball`); + await stagehand.page.act({ + action: 'click the "hit and run" link in this article', + timeoutMs: 360_000, + }); + + const url = "https://en.wikipedia.org/wiki/Hit_and_run_(baseball)"; + const currentUrl = stagehand.page.url(); + + return { + _success: currentUrl === url, + expected: url, + actual: currentUrl, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } catch (error) { + return { + _success: false, + error: error, + debugUrl, + sessionUrl, + logs: logger.getLogs(), + }; + } finally { + await stagehand.close(); + } +}; diff --git a/sdk/stagehand-ts/evals/utils.ts b/sdk/stagehand-ts/evals/utils.ts new file mode 100644 index 0000000..770f479 --- /dev/null +++ b/sdk/stagehand-ts/evals/utils.ts @@ -0,0 +1,213 @@ +/** + * This file provides utility functions and classes to assist with evaluation tasks. + * + * Key functionalities: + * - String normalization and fuzzy comparison utility functions to compare output strings + * against expected results in a flexible and robust way. + * - Generation of unique experiment names based on the current timestamp, environment, + * and eval name or category. + */ +import fs from "fs"; +import { LogLine } from "@browserbasehq/stagehand"; +import stringComparison from "string-comparison"; +import sharp from "sharp"; +const { jaroWinkler } = stringComparison; + +/** + * normalizeString: + * Prepares a string for comparison by: + * - Converting to lowercase + * - Collapsing multiple spaces to a single space + * - Removing punctuation and special characters that are not alphabetic or numeric + * - Normalizing spacing around commas + * - Trimming leading and trailing whitespace + * + * This helps create a stable string representation to compare against expected outputs, + * even if the actual output contains minor formatting differences. + */ +export function normalizeString(str: string): string { + return str + .toLowerCase() + .replace(/\s+/g, " ") + .replace(/[;/#!$%^&*:{}=\-_`~()]/g, "") + .replace(/\s*,\s*/g, ", ") + .trim(); +} + +/** + * compareStrings: + * Compares two strings (actual vs. expected) using a similarity metric (Jaro-Winkler). + * + * Arguments: + * - actual: The actual output string to be checked. + * - expected: The expected string we want to match against. + * - similarityThreshold: A number between 0 and 1. Default is 0.85. + * If the computed similarity is greater than or equal to this threshold, + * we consider the strings sufficiently similar. + * + * Returns: + * - similarity: A number indicating how similar the two strings are. + * - meetsThreshold: A boolean indicating if the similarity meets or exceeds the threshold. + * + * This function is useful for tasks where exact string matching is too strict, + * allowing for fuzzy matching that tolerates minor differences in formatting or spelling. + */ +export function compareStrings( + actual: string, + expected: string, + similarityThreshold: number = 0.85, +): { similarity: number; meetsThreshold: boolean } { + const similarity = jaroWinkler.similarity( + normalizeString(actual), + normalizeString(expected), + ); + return { + similarity, + meetsThreshold: similarity >= similarityThreshold, + }; +} + +/** + * generateTimestamp: + * Generates a timestamp string formatted as "YYYYMMDDHHMMSS". + * Used to create unique experiment names, ensuring that results can be + * distinguished by the time they were generated. + */ +export function generateTimestamp(): string { + const now = new Date(); + return now + .toISOString() + .replace(/[-:TZ]/g, "") + .slice(0, 14); +} + +/** + * generateExperimentName: + * Creates a unique name for the experiment based on optional evalName or category, + * the environment (e.g., dev or CI), and the current timestamp. + * This is used to label the output files and directories. + */ +export function generateExperimentName({ + evalName, + category, + environment, +}: { + evalName?: string; + category?: string; + environment: string; +}): string { + const timestamp = generateTimestamp(); + if (evalName) { + return `${evalName}_${environment.toLowerCase()}_${timestamp}`; + } + if (category) { + return `${category}_${environment.toLowerCase()}_${timestamp}`; + } + return `all_${environment.toLowerCase()}_${timestamp}`; +} + +export function logLineToString(logLine: LogLine): string { + try { + const timestamp = logLine.timestamp || new Date().toISOString(); + if (logLine.auxiliary?.error) { + return `${timestamp}::[stagehand:${logLine.category}] ${logLine.message}\n ${logLine.auxiliary.error.value}\n ${logLine.auxiliary.trace.value}`; + } + return `${timestamp}::[stagehand:${logLine.category}] ${logLine.message} ${ + logLine.auxiliary ? JSON.stringify(logLine.auxiliary) : "" + }`; + } catch (error) { + console.error(`Error logging line:`, error); + return "error logging line"; + } +} + +export function dedent( + strings: TemplateStringsArray, + ...values: unknown[] +): string { + // Interleave raw strings with substitution values + const raw = strings.raw; + let result = ""; + + for (let i = 0; i < raw.length; i++) { + result += raw[i] + // replace newline + any mix of spaces/tabs with “\n” + .replace(/\n[ \t]+/g, "\n") + .replace(/^\n/, ""); // remove leading newline + if (i < values.length) result += values[i]; + } + + // trim trailing/leading blank lines + return result.trimEnd(); +} + +// Dataset helpers shared by suites + +export function sampleUniform(arr: T[], k: number): T[] { + const n = arr.length; + if (k >= n) return arr.slice(); + const copy = arr.slice(); + for (let i = n - 1; i > 0; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const tmp = copy[i]; + copy[i] = copy[j]; + copy[j] = tmp; + } + return copy.slice(0, k); +} + +export function readJsonlFile(filePath: string): string[] { + let lines: string[] = []; + try { + const content = fs.readFileSync(filePath, "utf-8"); + lines = content.split(/\r?\n/).filter((l) => l.trim().length > 0); + } catch (e) { + console.warn( + `Could not read file at ${filePath}. Error: ${e instanceof Error ? e.message : String(e)}`, + ); + lines = []; + } + return lines; +} + +export function parseJsonlRows( + lines: string[], + validator: (parsed: unknown) => parsed is T, +): T[] { + const candidates: T[] = []; + for (const line of lines) { + try { + const parsed = JSON.parse(line); + if (validator(parsed)) { + candidates.push(parsed); + } + } catch { + // skip invalid lines + } + } + return candidates; +} + +export function applySampling( + candidates: T[], + sampleCount?: number, + maxCases: number = 25, +): T[] { + if (sampleCount && sampleCount > 0) { + return sampleUniform(candidates, sampleCount); + } else { + const result: T[] = []; + for (const candidate of candidates) { + result.push(candidate); + if (result.length >= maxCases) break; + } + return result; + } +} + +export async function optimizedScreenshot( + img: Buffer, + scaleFactor: number, +): Promise { + return await sharp(img).resize(scaleFactor).toBuffer(); +} diff --git a/sdk/stagehand-ts/evals/utils/ScreenshotCollector.ts b/sdk/stagehand-ts/evals/utils/ScreenshotCollector.ts new file mode 100644 index 0000000..417b7b4 --- /dev/null +++ b/sdk/stagehand-ts/evals/utils/ScreenshotCollector.ts @@ -0,0 +1,268 @@ +import { Page } from "@playwright/test"; +import sharp from "sharp"; + +export interface ScreenshotCollectorOptions { + interval?: number; + maxScreenshots?: number; + captureOnNavigation?: boolean; +} + +export class ScreenshotCollector { + private screenshots: Buffer[] = []; + private page: Page; + private interval: number; + private maxScreenshots: number; + private captureOnNavigation: boolean; + private intervalId?: NodeJS.Timeout; + private navigationListeners: Array<() => void> = []; + private isCapturing: boolean = false; + private lastScreenshot?: Buffer; + private ssimThreshold: number = 0.75; + private mseThreshold: number = 30; + + constructor(page: Page, options: ScreenshotCollectorOptions = {}) { + this.page = page; + this.interval = options.interval || 5000; + this.maxScreenshots = options.maxScreenshots || 10; + this.captureOnNavigation = options.captureOnNavigation ?? false; + } + + start(): void { + if (this.intervalId) { + return; + } + + // Set up time-based screenshot capture + this.intervalId = setInterval(() => { + this.captureScreenshot("interval").catch((error) => { + console.error("Interval screenshot failed:", error); + }); + }, this.interval); + + if (this.captureOnNavigation) { + const loadListener = async () => { + try { + await this.captureScreenshot("load"); + } catch (error) { + console.error("Navigation screenshot failed (load):", error); + } + }; + const domContentListener = async () => { + try { + await this.captureScreenshot("domcontentloaded"); + } catch (error) { + console.error( + "Navigation screenshot failed (domcontentloaded):", + error, + ); + } + }; + + this.page.on("load", loadListener); + this.page.on("domcontentloaded", domContentListener); + + this.navigationListeners = [ + () => this.page.off("load", loadListener), + () => this.page.off("domcontentloaded", domContentListener), + ]; + } + + // Capture initial screenshot without blocking + this.captureScreenshot("initial").catch((error) => { + console.error("Failed to capture initial screenshot:", error); + }); + } + + stop(): Buffer[] { + if (this.intervalId) { + clearInterval(this.intervalId); + this.intervalId = undefined; + } + + this.navigationListeners.forEach((removeListener) => removeListener()); + this.navigationListeners = []; + + // Capture final screenshot without blocking + this.captureScreenshot("final").catch((error) => { + console.error("Failed to capture final screenshot:", error); + }); + + return this.getScreenshots(); + } + + private async captureScreenshot(trigger: string): Promise { + if (this.isCapturing) { + return; + } + this.isCapturing = true; + + try { + const screenshot = await this.page.screenshot(); + + // Check if we should keep this screenshot based on image diff + let shouldKeep = true; + if (this.lastScreenshot && trigger !== "initial" && trigger !== "final") { + try { + // First do a quick MSE check + const mse = await this.calculateMSE(this.lastScreenshot, screenshot); + if (mse < this.mseThreshold) { + // Very similar, skip + shouldKeep = false; + } else { + // Significant difference detected, verify with SSIM + const ssim = await this.calculateSSIM( + this.lastScreenshot, + screenshot, + ); + shouldKeep = ssim < this.ssimThreshold; + } + } catch (error) { + // If comparison fails, keep the screenshot + console.error("Image comparison failed:", error); + shouldKeep = true; + } + } + + if (shouldKeep) { + this.screenshots.push(screenshot); + this.lastScreenshot = screenshot; + + if (this.screenshots.length > this.maxScreenshots) { + this.screenshots.shift(); + } + } + } catch (error) { + console.error(`Failed to capture screenshot (${trigger}):`, error); + } finally { + this.isCapturing = false; + } + } + + getScreenshots(): Buffer[] { + return [...this.screenshots]; + } + + getScreenshotCount(): number { + return this.screenshots.length; + } + + clear(): void { + this.screenshots = []; + } + + /** + * Manually add a screenshot to the collection + * @param screenshot The screenshot buffer to add + * @param source Optional source identifier for logging + */ + async addScreenshot(screenshot: Buffer): Promise { + // Prevent concurrent processing + if (this.isCapturing) { + return; + } + this.isCapturing = true; + + try { + // Apply MSE/SSIM logic to decide if we should keep this screenshot + let shouldKeep = true; + if (this.lastScreenshot) { + try { + // First do a quick MSE check + const mse = await this.calculateMSE(this.lastScreenshot, screenshot); + if (mse < this.mseThreshold) { + // Very similar, skip + shouldKeep = false; + } else { + // Significant difference detected, verify with SSIM + const ssim = await this.calculateSSIM( + this.lastScreenshot, + screenshot, + ); + shouldKeep = ssim < this.ssimThreshold; + } + } catch (error) { + // If comparison fails, keep the screenshot + console.error("Image comparison failed:", error); + shouldKeep = true; + } + } + + if (shouldKeep) { + this.screenshots.push(screenshot); + this.lastScreenshot = screenshot; + + if (this.screenshots.length > this.maxScreenshots) { + this.screenshots.shift(); + } + } + } finally { + this.isCapturing = false; + } + } + private async calculateMSE(img1: Buffer, img2: Buffer): Promise { + try { + // Resize images for faster comparison + const size = { width: 400, height: 300 }; + const data1 = await sharp(img1).resize(size).raw().toBuffer(); + const data2 = await sharp(img2).resize(size).raw().toBuffer(); + + if (data1.length !== data2.length) return Number.MAX_SAFE_INTEGER; + + let sum = 0; + for (let i = 0; i < data1.length; i++) { + const diff = data1[i] - data2[i]; + sum += diff * diff; + } + + return sum / data1.length; + } catch { + // If sharp is not available, assume images are different + return Number.MAX_SAFE_INTEGER; + } + } + + private async calculateSSIM(img1: Buffer, img2: Buffer): Promise { + try { + // Resize and convert to grayscale for SSIM calculation + const size = { width: 400, height: 300 }; + const gray1 = await sharp(img1).resize(size).grayscale().raw().toBuffer(); + const gray2 = await sharp(img2).resize(size).grayscale().raw().toBuffer(); + + if (gray1.length !== gray2.length) return 0; + + // Simplified SSIM calculation + const c1 = 0.01 * 0.01; + const c2 = 0.03 * 0.03; + + let sum1 = 0, + sum2 = 0, + sum1_sq = 0, + sum2_sq = 0, + sum12 = 0; + const N = gray1.length; + + for (let i = 0; i < N; i++) { + sum1 += gray1[i]; + sum2 += gray2[i]; + sum1_sq += gray1[i] * gray1[i]; + sum2_sq += gray2[i] * gray2[i]; + sum12 += gray1[i] * gray2[i]; + } + + const mean1 = sum1 / N; + const mean2 = sum2 / N; + const var1 = sum1_sq / N - mean1 * mean1; + const var2 = sum2_sq / N - mean2 * mean2; + const cov12 = sum12 / N - mean1 * mean2; + + const numerator = (2 * mean1 * mean2 + c1) * (2 * cov12 + c2); + const denominator = + (mean1 * mean1 + mean2 * mean2 + c1) * (var1 + var2 + c2); + + return numerator / denominator; + } catch { + // If sharp is not available, assume images are different + return 0; + } + } +} diff --git a/sdk/stagehand-ts/evals/utils/imageUtils.ts b/sdk/stagehand-ts/evals/utils/imageUtils.ts new file mode 100644 index 0000000..812221b --- /dev/null +++ b/sdk/stagehand-ts/evals/utils/imageUtils.ts @@ -0,0 +1,19 @@ +import sharp from "sharp"; + +export async function imageResize( + img: Buffer, + scaleFactor: number, +): Promise { + const metadata = await sharp(img).metadata(); + // calculate new dimensions + const width = Math.round(metadata.width * scaleFactor); + const height = Math.round(metadata.height * scaleFactor); + return await sharp(img) + .resize(width, height, { fit: "inside", kernel: sharp.kernel.lanczos3 }) + .png({ + compressionLevel: 9, + adaptiveFiltering: true, + palette: true, + }) + .toBuffer(); +} diff --git a/sdk/stagehand-ts/evals/worker.ts b/sdk/stagehand-ts/evals/worker.ts new file mode 100644 index 0000000..5c89807 --- /dev/null +++ b/sdk/stagehand-ts/evals/worker.ts @@ -0,0 +1,131 @@ +// import { parentPort, workerData } from "worker_threads"; +// import path from "path"; +// import { initStagehand } from "./initStagehand"; +// import { EvalLogger } from "./logger"; +// import { StagehandEvalError } from "@/types/stagehandErrors"; +// import { CustomOpenAIClient } from "@/examples/external_clients/customOpenAI"; +// import { AISdkClient } from "@/examples/external_clients/aisdk"; +// import { getAISDKLanguageModel } from "@/lib/llm/LLMProvider"; +// import { loadApiKeyFromEnv } from "@/lib/utils"; +// import { AgentProvider } from "@/lib/agent/AgentProvider"; +// import { wrapAISDKModel, wrapOpenAI } from "braintrust"; +// import OpenAI from "openai"; +// import { AvailableModel, LLMClient } from "@browserbasehq/stagehand"; + +// async function runTask() { +// const { input, USE_API } = workerData; +// const logger = new EvalLogger(); + +// try { +// // Import task module +// const taskModulePath = path.join(__dirname, "tasks", `${input.name}.ts`); +// let taskModule; + +// try { +// taskModule = await import(taskModulePath); +// } catch (error) { +// if (input.name.includes("/")) { +// const subDirPath = path.join(__dirname, "tasks", `${input.name}.ts`); +// try { +// taskModule = await import(subDirPath); +// } catch (subError) { +// throw new StagehandEvalError( +// `Failed to import task module for ${input.name}`, +// ); +// } +// } else { +// throw error; +// } +// } + +// const taskName = input.name.includes("/") +// ? input.name.split("/").pop() +// : input.name; + +// const taskFunction = taskModule[taskName]; + +// if (typeof taskFunction !== "function") { +// throw new StagehandEvalError( +// `No Eval function found for task: ${taskName}`, +// ); +// } + +// // Initialize Stagehand +// let taskInput; + +// if (USE_API) { +// let provider: string; +// if (input.modelName.includes("/")) { +// provider = input.modelName.split("/")[0]; +// } else { +// try { +// provider = AgentProvider.getAgentProvider(input.modelName); +// } catch { +// provider = undefined as unknown as string; +// } +// } + +// const apiKey = loadApiKeyFromEnv(provider, (line) => logger.log(line)); + +// if (!apiKey) { +// throw new StagehandEvalError( +// `USE_API=true but no API key found for provider "${provider}".`, +// ); +// } + +// taskInput = await initStagehand({ +// logger, +// modelName: input.modelName, +// modelClientOptions: { apiKey }, +// }); +// } else { +// let llmClient: LLMClient; +// if (input.modelName.includes("/")) { +// llmClient = new AISdkClient({ +// model: wrapAISDKModel( +// getAISDKLanguageModel( +// input.modelName.split("/")[0], +// input.modelName.split("/")[1], +// ), +// ), +// }); +// } else { +// llmClient = new CustomOpenAIClient({ +// modelName: input.modelName as AvailableModel, +// client: wrapOpenAI( +// new OpenAI({ +// apiKey: process.env.TOGETHER_AI_API_KEY, +// baseURL: "https://api.together.xyz/v1", +// }), +// ), +// }); +// } +// taskInput = await initStagehand({ +// logger, +// llmClient, +// modelName: input.modelName, +// }); +// } + +// // Run the task +// let result; +// try { +// result = await taskFunction({ ...taskInput, input }); +// } finally { +// await taskInput.stagehand.close(); +// } + +// parentPort?.postMessage({ success: true, result }); +// } catch (error) { +// parentPort?.postMessage({ +// success: false, +// error: { +// message: error.message, +// stack: error.stack, +// logs: logger.getLogs(), +// }, +// }); +// } +// } + +// runTask(); diff --git a/sdk/stagehand-ts/examples/2048.ts b/sdk/stagehand-ts/examples/2048.ts new file mode 100644 index 0000000..0730258 --- /dev/null +++ b/sdk/stagehand-ts/examples/2048.ts @@ -0,0 +1,95 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { z } from "zod/v3"; + +async function example() { + console.log("🎮 Starting 2048 bot..."); + const stagehand = new Stagehand({ + env: "LOCAL", + verbose: 1, + domSettleTimeoutMs: 100, + }); + try { + console.log("🌟 Initializing Stagehand..."); + await stagehand.init(); + console.log("🌐 Navigating to 2048..."); + await stagehand.page.goto("https://ovolve.github.io/2048-AI/"); + console.log("⌛ Waiting for game to initialize..."); + await stagehand.page.waitForSelector(".grid-container", { timeout: 10000 }); + // Main game loop + while (true) { + console.log("🔄 Game loop iteration..."); + // Add a small delay for UI updates + await new Promise((resolve) => setTimeout(resolve, 300)); + // Get current game state + const gameState = await stagehand.page.extract({ + instruction: `Extract the current game state: + 1. Score from the score counter + 2. All tile values in the 4x4 grid (empty spaces as 0) + 3. Highest tile value present`, + schema: z.object({ + score: z.number(), + highestTile: z.number(), + grid: z.array(z.array(z.number())), + }), + }); + const transposedGrid = gameState.grid[0].map((_, colIndex) => + gameState.grid.map((row) => row[colIndex]), + ); + const grid = transposedGrid.map((row, rowIndex) => ({ + [`row${rowIndex + 1}`]: row, + })); + console.log("Game State:", { + score: gameState.score, + highestTile: gameState.highestTile, + grid: grid, + }); + // Analyze board and decide next move + const analysis = await stagehand.page.extract({ + instruction: `Based on the current game state: + - Score: ${gameState.score} + - Highest tile: ${gameState.highestTile} + - Grid: This is a 4x4 matrix ordered by row (top to bottom) and column (left to right). The rows are stacked vertically, and tiles can move vertically between rows or horizontally between columns:\n${grid + .map((row) => { + const rowName = Object.keys(row)[0]; + return ` ${rowName}: ${row[rowName].join(", ")}`; + }) + .join("\n")} + What is the best move (up/down/left/right)? Consider: + 1. Keeping high value tiles in corners (bottom left, bottom right, top left, top right) + 2. Maintaining a clear path to merge tiles + 3. Avoiding moves that could block merges + 4. Only adjacent tiles of the same value can merge + 5. Making a move will move all tiles in that direction until they hit a tile of a different value or the edge of the board + 6. Tiles cannot move past the edge of the board + 7. Each move must move at least one tile`, + schema: z.object({ + move: z.enum(["up", "down", "left", "right"]), + confidence: z.number(), + reasoning: z.string(), + }), + }); + console.log("Move Analysis:", analysis); + const moveKey = { + up: "ArrowUp", + down: "ArrowDown", + left: "ArrowLeft", + right: "ArrowRight", + }[analysis.move]; + await stagehand.page.keyboard.press(moveKey); + console.log("🎯 Executed move:", analysis.move); + } + } catch (error) { + console.error("❌ Error in game loop:", error); + const isGameOver = await stagehand.page.evaluate(() => { + return document.querySelector(".game-over") !== null; + }); + if (isGameOver) { + console.log("🏁 Game Over!"); + return; + } + throw error; // Re-throw non-game-over errors + } +} +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/actionable_observe_example.ts b/sdk/stagehand-ts/examples/actionable_observe_example.ts new file mode 100644 index 0000000..edb7324 --- /dev/null +++ b/sdk/stagehand-ts/examples/actionable_observe_example.ts @@ -0,0 +1,82 @@ +/** + * This example shows how to use actionable observe() + * + * You can use observe to get a cache-able Playwright action as JSON, then pass that JSON to act() to perform the action. + * + * This is useful for: + * - Previewing actions before running them + * - Saving actions to a file and replaying them later + * - Hiding sensitive information from LLMs + * + * For more on caching, see: https://docs.stagehand.dev/examples/caching + * Also check out the form_filling_sensible.ts example for a more complex example of using observe() to fill out a form. + */ + +import { ObserveResult, Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "../stagehand.config"; + +async function example() { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + const page = stagehand.page; + + await page.goto("https://www.apartments.com/san-francisco-ca/"); + + let observation: ObserveResult; + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the 'all filters' button", + }); + await page.act(observation); + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the '1+' button in the 'beds' section", + }); + await page.act(observation); + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the 'apartments' button in the 'home type' section", + }); + await page.act(observation); + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the pet policy dropdown to click on.", + }); + await page.act(observation); + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the 'Dog Friendly' option to click on", + }); + await page.act(observation); + + await new Promise((resolve) => setTimeout(resolve, 3000)); + [observation] = await page.observe({ + instruction: "find the 'see results' section", + }); + await page.act(observation); + + const currentUrl = page.url(); + await stagehand.close(); + if ( + currentUrl.includes( + "https://www.apartments.com/apartments/san-francisco-ca/min-1-bedrooms-pet-friendly-dog/", + ) + ) { + console.log("✅ Success! we made it to the correct page"); + } else { + console.log( + "❌ Whoops, looks like we didn't make it to the correct page. " + + "\nThanks for testing out this new Stagehand feature!" + + "\nReach us on Slack if you have any feedback/questions/suggestions!", + ); + } +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/bb-cua-example.ts b/sdk/stagehand-ts/examples/bb-cua-example.ts new file mode 100644 index 0000000..f0b4d0c --- /dev/null +++ b/sdk/stagehand-ts/examples/bb-cua-example.ts @@ -0,0 +1,76 @@ +/** + * This example shows how to use a computer use agent (CUA) to navigate a web page and extract data. + * + * To learn more about the CUA, see: https://docs.stagehand.dev/examples/computer_use + * + * NOTE: YOU MUST CONFIGURE BROWSER DIMENSIONS TO USE COMPUTER USE! + * Check out stagehand.config.ts for more information. + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; +import chalk from "chalk"; + +async function main() { + console.log( + `\n${chalk.bold("Stagehand 🤘 Computer Use Agent (CUA) Demo")}\n`, + ); + + // Initialize Stagehand + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "BROWSERBASE", + verbose: 1, // 0: silent, 1: info, 2: debug + useAPI: false, + }); + await stagehand.init(); + + try { + const page = stagehand.page; + + // Create a computer use agent + const agent = stagehand.agent({ + provider: "google", + // For Anthropic, use claude-sonnet-4-20250514 or claude-3-7-sonnet-latest + // For OpenAI use computer-use-preview + model: "computer-use-preview-10-2025", + instructions: `You are a helpful assistant that can use a web browser. + You are currently on the following page: ${page.url()}. + Do not ask follow up questions, the user will trust your judgement.`, + options: { + apiKey: process.env.GEMINI_API_KEY, + }, + }); + + // Navigate to the Browserbase careers page + await page.goto("https://www.browserbase.com/careers"); + + // Define the instruction for the CUA + const instruction = + "Apply for the first engineer position with mock data. Don't submit the form."; + console.log(`Instruction: ${chalk.white(instruction)}`); + + // Execute the instruction + const result = await agent.execute({ + instruction, + maxSteps: 20, + autoScreenshot: false, + }); + + console.log(`${chalk.green("✓")} Execution complete`); + console.log(`${chalk.yellow("⤷")} Result:`); + console.log(chalk.white(JSON.stringify(result, null, 2))); + } catch (error) { + console.log(`${chalk.red("✗")} Error: ${error}`); + if (error instanceof Error && error.stack) { + console.log(chalk.dim(error.stack.split("\n").slice(1).join("\n"))); + } + } finally { + // Close the browser + await stagehand.close(); + } +} + +main().catch((error) => { + console.log(`${chalk.red("✗")} Unhandled error in main function`); + console.log(chalk.red(error)); +}); diff --git a/sdk/stagehand-ts/examples/custom_client_aisdk.ts b/sdk/stagehand-ts/examples/custom_client_aisdk.ts new file mode 100644 index 0000000..cacbf3b --- /dev/null +++ b/sdk/stagehand-ts/examples/custom_client_aisdk.ts @@ -0,0 +1,42 @@ +/** + * This example shows how to use the Vercel AI SDK to power the Stagehand LLM Client. + * + * You will need to reference the AI SDK Client in /external_clients/aisdk.ts + * + * To learn more about the Vercel AI SDK, see: https://sdk.vercel.ai/docs + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; +import { AISdkClient } from "./external_clients/aisdk"; +import { z } from "zod/v3"; +import { openai } from "@ai-sdk/openai"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + llmClient: new AISdkClient({ + model: openai("gpt-4o"), + }), + }); + + await stagehand.init(); + const page = stagehand.page; + + await page.goto("https://news.ycombinator.com"); + + const { story } = await page.extract({ + instruction: "extract the title of the top story on the page", + schema: z.object({ + story: z.string().describe("the top story on the page"), + }), + }); + + console.log("The top story is:", story); + await page.act("click the first story"); + + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/custom_client_langchain.ts b/sdk/stagehand-ts/examples/custom_client_langchain.ts new file mode 100644 index 0000000..cc5136e --- /dev/null +++ b/sdk/stagehand-ts/examples/custom_client_langchain.ts @@ -0,0 +1,40 @@ +/** + * This example shows how to use the Langchain client with Stagehand. + * + * You will need to reference the Langchain Client in /external_clients/langchain.ts + */ +import { z } from "zod/v3"; +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; +import { LangchainClient } from "./external_clients/langchain"; +import { ChatOpenAI } from "@langchain/openai"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + llmClient: new LangchainClient( + new ChatOpenAI({ + model: "gpt-4o", + }), + ), + }); + + await stagehand.init(); + await stagehand.page.goto("https://news.ycombinator.com"); + + const { story } = await stagehand.page.extract({ + schema: z.object({ + story: z.string().describe("the top story on the page"), + }), + }); + + console.log("The top story is:", story); + + await stagehand.page.act("click the first story"); + + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/custom_client_openai.ts b/sdk/stagehand-ts/examples/custom_client_openai.ts new file mode 100644 index 0000000..574aae3 --- /dev/null +++ b/sdk/stagehand-ts/examples/custom_client_openai.ts @@ -0,0 +1,50 @@ +/** + * This example shows how to use a custom OpenAI client with Stagehand. + * + * The OpenAI API provides a simple, type-safe, and composable way to build AI applications. + * + * You will need to reference the Custom OpenAI Client in /external_clients/customOpenAI.ts + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import { z } from "zod/v3"; +import { CustomOpenAIClient } from "./external_clients/customOpenAI"; +import StagehandConfig from "@/stagehand.config"; +import OpenAI from "openai"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + llmClient: new CustomOpenAIClient({ + modelName: "gpt-4o-mini", + client: new OpenAI({ + apiKey: process.env.OPENAI_API_KEY, + }), + }), + }); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://news.ycombinator.com"); + await page.act("click on the 'new' link"); + + const headlines = await page.extract({ + instruction: "Extract the top 3 stories from the Hacker News homepage.", + schema: z.object({ + stories: z.array( + z.object({ + title: z.string(), + url: z.string(), + points: z.number(), + }), + ), + }), + }); + + console.log(headlines); + + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/example.ts b/sdk/stagehand-ts/examples/example.ts new file mode 100644 index 0000000..608b6ef --- /dev/null +++ b/sdk/stagehand-ts/examples/example.ts @@ -0,0 +1,26 @@ +/** + * This file is meant to be used as a scratchpad for developing new evals. + * To create a Stagehand project with best practices and configuration, run: + * + * npx create-browser-app@latest my-browser-app + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "../stagehand.config"; + +async function example(stagehand: Stagehand) { + /** + * Add your code here! + */ + const page = stagehand.page; + await page.goto("https://docs.stagehand.dev"); + await page.act("click the quickstart button"); +} + +(async () => { + const stagehand = new Stagehand({ + ...StagehandConfig, + }); + await stagehand.init(); + await example(stagehand); + await stagehand.close(); +})(); diff --git a/sdk/stagehand-ts/examples/external_clients/aisdk.ts b/sdk/stagehand-ts/examples/external_clients/aisdk.ts new file mode 100644 index 0000000..7d44b69 --- /dev/null +++ b/sdk/stagehand-ts/examples/external_clients/aisdk.ts @@ -0,0 +1,126 @@ +import { + CoreAssistantMessage, + CoreMessage, + CoreSystemMessage, + CoreTool, + CoreUserMessage, + generateObject, + generateText, + ImagePart, + LanguageModel, + TextPart, +} from "ai"; +import { + CreateChatCompletionOptions, + LLMClient, + AvailableModel, +} from "@browserbasehq/stagehand"; +import { ChatCompletion } from "openai/resources"; + +export class AISdkClient extends LLMClient { + public type = "aisdk" as const; + private model: LanguageModel; + + constructor({ model }: { model: LanguageModel }) { + super(model.modelId as AvailableModel); + this.model = model; + } + + async createChatCompletion({ + options, + }: CreateChatCompletionOptions): Promise { + const formattedMessages: CoreMessage[] = options.messages.map((message) => { + if (Array.isArray(message.content)) { + if (message.role === "system") { + const systemMessage: CoreSystemMessage = { + role: "system", + content: message.content + .map((c) => ("text" in c ? c.text : "")) + .join("\n"), + }; + return systemMessage; + } + + const contentParts = message.content.map((content) => { + if ("image_url" in content) { + const imageContent: ImagePart = { + type: "image", + image: content.image_url.url, + }; + return imageContent; + } else { + const textContent: TextPart = { + type: "text", + text: content.text, + }; + return textContent; + } + }); + + if (message.role === "user") { + const userMessage: CoreUserMessage = { + role: "user", + content: contentParts, + }; + return userMessage; + } else { + const textOnlyParts = contentParts.map((part) => ({ + type: "text" as const, + text: part.type === "image" ? "[Image]" : part.text, + })); + const assistantMessage: CoreAssistantMessage = { + role: "assistant", + content: textOnlyParts, + }; + return assistantMessage; + } + } + + return { + role: message.role, + content: message.content, + }; + }); + + if (options.response_model) { + const response = await generateObject({ + model: this.model, + messages: formattedMessages, + schema: options.response_model.schema, + }); + + return { + data: response.object, + usage: { + prompt_tokens: response.usage.promptTokens ?? 0, + completion_tokens: response.usage.completionTokens ?? 0, + total_tokens: response.usage.totalTokens ?? 0, + }, + } as T; + } + + const tools: Record = {}; + + for (const rawTool of options.tools) { + tools[rawTool.name] = { + description: rawTool.description, + parameters: rawTool.parameters, + }; + } + + const response = await generateText({ + model: this.model, + messages: formattedMessages, + tools, + }); + + return { + data: response.text, + usage: { + prompt_tokens: response.usage.promptTokens ?? 0, + completion_tokens: response.usage.completionTokens ?? 0, + total_tokens: response.usage.totalTokens ?? 0, + }, + } as T; + } +} diff --git a/sdk/stagehand-ts/examples/external_clients/customOpenAI.ts b/sdk/stagehand-ts/examples/external_clients/customOpenAI.ts new file mode 100644 index 0000000..c87a596 --- /dev/null +++ b/sdk/stagehand-ts/examples/external_clients/customOpenAI.ts @@ -0,0 +1,244 @@ +/** + * Welcome to the Stagehand custom OpenAI client! + * + * This is a client for models that are compatible with the OpenAI API, like Ollama, Gemini, etc. + * You can just pass in an OpenAI instance to the client and it will work. + */ + +import { + AvailableModel, + CreateChatCompletionOptions, + LLMClient, +} from "@browserbasehq/stagehand"; +import OpenAI from "openai"; +import { zodResponseFormat } from "openai/helpers/zod"; +import type { + ChatCompletion, + ChatCompletionAssistantMessageParam, + ChatCompletionContentPartImage, + ChatCompletionContentPartText, + ChatCompletionCreateParamsNonStreaming, + ChatCompletionMessageParam, + ChatCompletionSystemMessageParam, + ChatCompletionUserMessageParam, +} from "openai/resources/chat/completions"; +import { z } from "zod/v3"; +import { CreateChatCompletionResponseError } from "@/types/stagehandErrors"; + +function validateZodSchema(schema: z.ZodTypeAny, data: unknown) { + try { + schema.parse(data); + return true; + } catch { + return false; + } +} + +export class CustomOpenAIClient extends LLMClient { + public type = "openai" as const; + private client: OpenAI; + + constructor({ modelName, client }: { modelName: string; client: OpenAI }) { + super(modelName as AvailableModel); + this.client = client; + this.modelName = modelName as AvailableModel; + } + + async createChatCompletion({ + options, + retries = 3, + logger, + }: CreateChatCompletionOptions): Promise { + const { image, requestId, ...optionsWithoutImageAndRequestId } = options; + + // TODO: Implement vision support + if (image) { + console.warn( + "Image provided. Vision is not currently supported for openai", + ); + } + + logger({ + category: "openai", + message: "creating chat completion", + level: 1, + auxiliary: { + options: { + value: JSON.stringify({ + ...optionsWithoutImageAndRequestId, + requestId, + }), + type: "object", + }, + modelName: { + value: this.modelName, + type: "string", + }, + }, + }); + + if (options.image) { + console.warn( + "Image provided. Vision is not currently supported for openai", + ); + } + + let responseFormat = undefined; + if (options.response_model) { + responseFormat = zodResponseFormat( + options.response_model.schema, + options.response_model.name, + ); + } + + /* eslint-disable */ + // Remove unsupported options + const { response_model, ...openaiOptions } = { + ...optionsWithoutImageAndRequestId, + model: this.modelName, + }; + + logger({ + category: "openai", + message: "creating chat completion", + level: 1, + auxiliary: { + openaiOptions: { + value: JSON.stringify(openaiOptions), + type: "object", + }, + }, + }); + + const formattedMessages: ChatCompletionMessageParam[] = + options.messages.map((message) => { + if (Array.isArray(message.content)) { + const contentParts = message.content.map((content) => { + if ("image_url" in content) { + const imageContent: ChatCompletionContentPartImage = { + image_url: { + url: content.image_url.url, + }, + type: "image_url", + }; + return imageContent; + } else { + const textContent: ChatCompletionContentPartText = { + text: content.text, + type: "text", + }; + return textContent; + } + }); + + if (message.role === "system") { + const formattedMessage: ChatCompletionSystemMessageParam = { + ...message, + role: "system", + content: contentParts.filter( + (content): content is ChatCompletionContentPartText => + content.type === "text", + ), + }; + return formattedMessage; + } else if (message.role === "user") { + const formattedMessage: ChatCompletionUserMessageParam = { + ...message, + role: "user", + content: contentParts, + }; + return formattedMessage; + } else { + const formattedMessage: ChatCompletionAssistantMessageParam = { + ...message, + role: "assistant", + content: contentParts.filter( + (content): content is ChatCompletionContentPartText => + content.type === "text", + ), + }; + return formattedMessage; + } + } + + const formattedMessage: ChatCompletionUserMessageParam = { + role: "user", + content: message.content, + }; + + return formattedMessage; + }); + + const body: ChatCompletionCreateParamsNonStreaming = { + ...openaiOptions, + model: this.modelName, + messages: formattedMessages, + response_format: responseFormat, + stream: false, + tools: options.tools?.map((tool) => ({ + function: { + name: tool.name, + description: tool.description, + parameters: tool.parameters, + }, + type: "function", + })), + }; + + const response = await this.client.chat.completions.create(body); + + logger({ + category: "openai", + message: "response", + level: 1, + auxiliary: { + response: { + value: JSON.stringify(response), + type: "object", + }, + requestId: { + value: requestId, + type: "string", + }, + }, + }); + + if (options.response_model) { + const extractedData = response.choices[0].message.content; + if (!extractedData) { + throw new CreateChatCompletionResponseError("No content in response"); + } + const parsedData = JSON.parse(extractedData); + + if (!validateZodSchema(options.response_model.schema, parsedData)) { + if (retries > 0) { + return this.createChatCompletion({ + options, + logger, + retries: retries - 1, + }); + } + + throw new CreateChatCompletionResponseError("Invalid response schema"); + } + + return { + data: parsedData, + usage: { + prompt_tokens: response.usage?.prompt_tokens ?? 0, + completion_tokens: response.usage?.completion_tokens ?? 0, + total_tokens: response.usage?.total_tokens ?? 0, + }, + } as T; + } + + return { + data: response.choices[0].message.content, + usage: { + prompt_tokens: response.usage?.prompt_tokens ?? 0, + completion_tokens: response.usage?.completion_tokens ?? 0, + total_tokens: response.usage?.total_tokens ?? 0, + }, + } as T; + } +} diff --git a/sdk/stagehand-ts/examples/external_clients/langchain.ts b/sdk/stagehand-ts/examples/external_clients/langchain.ts new file mode 100644 index 0000000..d30f564 --- /dev/null +++ b/sdk/stagehand-ts/examples/external_clients/langchain.ts @@ -0,0 +1,91 @@ +import { BaseChatModel } from "@langchain/core/language_models/chat_models"; +import { + CreateChatCompletionOptions, + LLMClient, + AvailableModel, +} from "@browserbasehq/stagehand"; +import { zodToJsonSchema } from "zod-to-json-schema"; +import { + AIMessage, + BaseMessageLike, + HumanMessage, + SystemMessage, +} from "@langchain/core/messages"; +import { ChatCompletion } from "openai/resources"; + +export class LangchainClient extends LLMClient { + public type = "langchainClient" as const; + private model: BaseChatModel; + + constructor(model: BaseChatModel) { + super(model.name as AvailableModel); + this.model = model; + } + + async createChatCompletion({ + options, + }: CreateChatCompletionOptions): Promise { + const formattedMessages: BaseMessageLike[] = options.messages.map( + (message) => { + if (Array.isArray(message.content)) { + if (message.role === "system") { + return new SystemMessage( + message.content + .map((c) => ("text" in c ? c.text : "")) + .join("\n"), + ); + } + + const content = message.content.map((content) => + "image_url" in content + ? { type: "image", image: content.image_url.url } + : { type: "text", text: content.text }, + ); + + if (message.role === "user") return new HumanMessage({ content }); + + const textOnlyParts = content.map((part) => ({ + type: "text" as const, + text: part.type === "image" ? "[Image]" : part.text, + })); + + return new AIMessage({ content: textOnlyParts }); + } + + return { + role: message.role, + content: message.content, + }; + }, + ); + + if (options.response_model) { + const responseSchema = zodToJsonSchema(options.response_model.schema, { + $refStrategy: "none", + }); + const structuredModel = this.model.withStructuredOutput(responseSchema); + const response = await structuredModel.invoke(formattedMessages); + + return { + data: response, + usage: { + prompt_tokens: 0, // Langchain doesn't provide token counts by default + completion_tokens: 0, + total_tokens: 0, + }, + } as T; + } + + const modelWithTools = this.model.bindTools(options.tools); + const response = await modelWithTools.invoke(formattedMessages); + + return { + data: response, + usage: { + prompt_tokens: 0, // Langchain doesn't provide token counts by default + completion_tokens: 0, + total_tokens: 0, + }, + } as T; + } +} diff --git a/sdk/stagehand-ts/examples/form_filling_sensible.ts b/sdk/stagehand-ts/examples/form_filling_sensible.ts new file mode 100644 index 0000000..0106fee --- /dev/null +++ b/sdk/stagehand-ts/examples/form_filling_sensible.ts @@ -0,0 +1,92 @@ +/** + * This example shows you how to use observe() to get a cacheable Playwright action as JSON, then pass that JSON to act() to perform the action. + * + * In this specific example, we use observe() to get multiple actions, then iterate through each action to fill the form with sensitive data at lightning speed. + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; +import chalk from "chalk"; + +async function formFillingSensible() { + const stagehand = new Stagehand({ + ...StagehandConfig, + }); + await stagehand.init(); + const page = stagehand.page; + + // Block manifest worker to prevent PWA installation popup. + // This is necessary because the website prompts the user to install the PWA and prevents form filling. + await page.route("**/manifest.json", (route) => route.abort()); + + // Go to the website and wait for it to load + await page.goto("https://file.1040.com/estimate/", { + waitUntil: "networkidle", + timeout: 30000, + }); + + // Observe the form fields with suggested actions + const observed = await page.observe( + "fill all the form fields in the page with mock data. In the description include the field name", + ); + + // Uncomment the following snippet to see the stagehand candidate suggestions (initial) + console.log( + `${chalk.green("Observe:")} Form fields found:\n${observed + .map((r) => `${chalk.yellow(r.description)} -> ${chalk.gray(r.selector)}`) + .join("\n")}`, + ); + + // Create a mapping of 1+ keywords in the form fields to standardize field names + const mapping = (description: string): string | null => { + const keywords: { [key: string]: string[] } = { + age: ["old"], + dependentsUnder17: ["under age 17", "child", "minor"], + dependents17to23: ["17-23", "school", "student"], + wages: ["wages", "W-2 Box 1"], + federalTax: ["federal tax", "Box 2"], + stateTax: ["state tax", "Box 17"], + }; + + for (const [key, terms] of Object.entries(keywords)) { + if (terms.some((term) => description.toLowerCase().includes(term))) { + return key; + } + } + return null; + }; + + // Fill the form fields with sensible data. This data will only be used in your session and not be shared with LLM providers/external APIs. + const userInputs: { [key: string]: string } = { + age: "26", + dependentsUnder17: "1", + wages: "54321", + federalTax: "8345", + stateTax: "2222", + }; + + const updatedFields = observed.map((candidate) => { + const key = mapping(candidate.description); + if (key && userInputs[key]) { + candidate.arguments = [userInputs[key]]; + } + return candidate; + }); + // List of sensible-data candidates + console.log( + `\n${chalk.green("Sensible Data form inputs:")} Form fields to be filled:\n${updatedFields + .map( + (r) => + `${chalk.yellow(r.description)} -> ${chalk.blue(r.arguments?.[0] || "no value")}`, + ) + .join("\n")}`, + ); + + // Fill all the form fields with the sensible candidates + for (const candidate of updatedFields) { + await page.act(candidate); + } +} + +(async () => { + await formFillingSensible(); +})(); diff --git a/sdk/stagehand-ts/examples/google_enter.ts b/sdk/stagehand-ts/examples/google_enter.ts new file mode 100644 index 0000000..243a40a --- /dev/null +++ b/sdk/stagehand-ts/examples/google_enter.ts @@ -0,0 +1,24 @@ +/** + * This example shows how to use the Stagehand agent to navigate to Google and search for "Browserbase". + * + * It's mainly meant to sanity check using page.act() to press enter, since some LLMs have issues with it. + */ + +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + }); + await stagehand.init(); + const page = stagehand.page; + await page.goto("https://google.com"); + await page.act("type in 'Browserbase'"); + await page.act("press enter"); + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/instructions.ts b/sdk/stagehand-ts/examples/instructions.ts new file mode 100644 index 0000000..41af52c --- /dev/null +++ b/sdk/stagehand-ts/examples/instructions.ts @@ -0,0 +1,31 @@ +/** + * This example shows how to use custom system prompts with Stagehand. + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + systemPrompt: + "if the users says `secret12345`, click on the 'getting started' tab. additionally, if the user says to type something, translate their input into french and type it.", + }); + await stagehand.init(); + + const page = stagehand.page; + await page.goto("https://docs.browserbase.com/"); + + await page.act({ + action: "secret12345", + }); + + await page.act({ + action: "search for 'how to use browserbase'", + }); + + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/local-cua-example.ts b/sdk/stagehand-ts/examples/local-cua-example.ts new file mode 100644 index 0000000..80592da --- /dev/null +++ b/sdk/stagehand-ts/examples/local-cua-example.ts @@ -0,0 +1,137 @@ +/** + * This example shows how to use a computer use agent (CUA) to navigate a web page and extract data. + * + * To learn more about the CUA, see: https://docs.stagehand.dev/examples/computer_use + * + * NOTE: YOU MUST CONFIGURE BROWSER DIMENSIONS TO USE COMPUTER USE! + * Check out stagehand.config.ts for more information. + */ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; +import chalk from "chalk"; +import fs from "fs"; + +async function main() { + console.log( + `\n${chalk.bold("Stagehand 🤘 Computer Use Agent (CUA) Demo")}\n`, + ); + + // Initialize Stagehand + const stagehand = new Stagehand({ + ...StagehandConfig, + env: "LOCAL", + verbose: 2, // 0: silent, 1: info, 2: debug + useAPI: false, + }); + await stagehand.init(); + + try { + const page = stagehand.page; + // Create a computer use agent + const agent = stagehand.agent({ + provider: "google", + // For Anthropic, use claude-sonnet-4-20250514 or claude-3-7-sonnet-latest + // For OpenAI use computer-use-preview + model: "computer-use-preview-10-2025", + // model: "claude-sonnet-4-5-20250929", + instructions: `You are a helpful assistant that can use a web browser. + You are currently on the following page: ${page.url()}. + Do not ask follow up questions, the user will trust your judgement.`, + options: { + apiKey: process.env.GEMINI_API_KEY, + }, + }); + + // Navigate to the Browserbase careers page + await page.goto("https://www.amazon.com"); + fs.writeFileSync("screenshot.png", await page.screenshot()); + + // Define the instruction for the CUA + // const instruction = + // "Apply for the first engineer position with mock data. Don't submit the form."; + // console.log(`Instruction: ${chalk.white(instruction)}`); + // const client = await stagehand.context.newCDPSession(page); + // Draw a cursor on the page so we can see where it clicks + // await page.evaluate(() => { + // // Remove any existing cursor + // const existingCursor = document.getElementById('stagehand-cursor'); + // if (existingCursor) { + // existingCursor.remove(); + // } + + // // Create cursor element + // const cursor = document.createElement('div'); + // cursor.id = 'stagehand-cursor'; + // cursor.style.cssText = ` + // position: fixed; + // width: 14px; + // height: 14px; + // background: red; + // border: 2px solid white; + // border-radius: 50%; + // pointer-events: none; + // z-index: 999999; + // transform: translate(-50%, -50%); + // box-shadow: 0 0 10px rgba(255, 0, 0, 0.5); + // `; + // document.body.appendChild(cursor); + + // // Track mouse movements and update cursor position + // document.addEventListener('mousemove', (e) => { + // cursor.style.left = e.clientX + 'px'; + // cursor.style.top = e.clientY + 'px'; + // }); + + // // Add click animation + // document.addEventListener('mousedown', () => { + // cursor.style.transform = 'translate(-50%, -50%) scale(1.5)'; + // cursor.style.background = 'darkred'; + // }); + + // document.addEventListener('mouseup', () => { + // cursor.style.transform = 'translate(-50%, -50%) scale(1)'; + // cursor.style.background = 'red'; + // }); + // }); + + // await client.send("Input.dispatchMouseEvent", { + // type: "mouseMoved", + // x: 220, + // y: 360, + // button: "none", + // }); + // await client.send("Input.dispatchMouseEvent", { + // type: "mousePressed", + // x: 220, + // y: 360, + // button: "left", + // }); + // await page.keyboard.type("New York City"); + const instruction = + "Find climbing gears and sort the results by price high to low. Answer the first 3 results after sorting"; + + // Execute the instruction + const result = await agent.execute({ + instruction, + maxSteps: 20, + autoScreenshot: false, + }); + + console.log(`${chalk.green("✓")} Execution complete`); + console.log(`${chalk.yellow("⤷")} Result:`); + console.log(chalk.white(JSON.stringify(result, null, 2))); + } catch (error) { + console.log(`${chalk.red("✗")} Error: ${error}`); + if (error instanceof Error && error.stack) { + console.log(chalk.dim(error.stack.split("\n").slice(1).join("\n"))); + } + } finally { + // Close the browser + await stagehand.close(); + } +} + +main().catch((error) => { + console.log(`${chalk.red("✗")} Unhandled error in main function`); + console.log(chalk.red(error)); +}); diff --git a/sdk/stagehand-ts/examples/operator-example.ts b/sdk/stagehand-ts/examples/operator-example.ts new file mode 100644 index 0000000..d73a2a3 --- /dev/null +++ b/sdk/stagehand-ts/examples/operator-example.ts @@ -0,0 +1,51 @@ +/** + * This example shows how to use the Stagehand operator to do simple autonomous tasks. + * + * This is built off of our open source project, Open Operator: https://operator.browserbase.com + * + * To learn more about Stagehand Agents, see: https://docs.stagehand.dev/concepts/agent + */ + +import { Stagehand } from "@browserbasehq/stagehand"; +import dotenv from "dotenv"; +import StagehandConfig from "@/stagehand.config"; +import chalk from "chalk"; + +// Load environment variables +dotenv.config(); + +const INSTRUCTION = + "Go to Google Japan and interact with it in Japanese. Tell me (in English) an authentic recipe that I can make with ingredients found in American grocery stores."; + +async function main() { + console.log(`\n${chalk.bold("Stagehand 🤘 Operator Example")}\n`); + + // Initialize Stagehand + const stagehand = new Stagehand({ + ...StagehandConfig, + }); + + await stagehand.init(); + + try { + const agent = stagehand.agent(); + + // Execute the agent + console.log(`${chalk.cyan("↳")} Instruction: ${INSTRUCTION}`); + const result = await agent.execute({ + instruction: INSTRUCTION, + maxSteps: 20, + }); + + console.log(`${chalk.green("✓")} Execution complete`); + console.log(`${chalk.yellow("⤷")} Result:`); + console.log(JSON.stringify(result, null, 2)); + console.log(chalk.white(result.message)); + } catch (error) { + console.log(`${chalk.red("✗")} Error: ${error}`); + } finally { + await stagehand.close(); + } +} + +main(); diff --git a/sdk/stagehand-ts/examples/package.json b/sdk/stagehand-ts/examples/package.json new file mode 100644 index 0000000..aee01f9 --- /dev/null +++ b/sdk/stagehand-ts/examples/package.json @@ -0,0 +1,18 @@ +{ + "name": "@browserbasehq/stagehand-examples", + "version": "1.0.6", + "private": true, + "description": "Example scripts for Stagehand", + "main": "./", + "scripts": { + "build": "pnpm --filter @browserbasehq/stagehand run build", + "start": "pnpm run build && sh -c 'if [ -n \"$1\" ]; then tsx \"$1.ts\"; else tsx example.ts; fi' --" + }, + "dependencies": { + "@browserbasehq/stagehand": "workspace:*" + }, + "devDependencies": { + "tsx": "^4.10.5", + "jszip": "^3.10.1" + } +} diff --git a/sdk/stagehand-ts/examples/parameterizeApiKey.ts b/sdk/stagehand-ts/examples/parameterizeApiKey.ts new file mode 100644 index 0000000..1e67f09 --- /dev/null +++ b/sdk/stagehand-ts/examples/parameterizeApiKey.ts @@ -0,0 +1,40 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import { z } from "zod/v3"; + +/** + * This example shows how to parameterize the API key for the LLM provider. + * + * In order to best demonstrate, unset the OPENAI_API_KEY environment variable and + * set the USE_OPENAI_API_KEY environment variable to your OpenAI API key. + * + * export USE_OPENAI_API_KEY=$OPENAI_API_KEY + * unset OPENAI_API_KEY + */ + +async function example() { + const stagehand = new Stagehand({ + env: "LOCAL", + verbose: 1, + enableCaching: false, + modelName: "gpt-4o", + modelClientOptions: { + apiKey: process.env.USE_OPENAI_API_KEY, + }, + }); + + await stagehand.init(); + await stagehand.page.goto("https://github.com/browserbase/stagehand"); + await stagehand.page.act({ action: "click on the contributors" }); + const contributor = await stagehand.page.extract({ + instruction: "extract the top contributor", + schema: z.object({ + username: z.string(), + url: z.string(), + }), + }); + console.log(`Our favorite contributor is ${contributor.username}`); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/popup.ts b/sdk/stagehand-ts/examples/popup.ts new file mode 100644 index 0000000..ce9d9d7 --- /dev/null +++ b/sdk/stagehand-ts/examples/popup.ts @@ -0,0 +1,45 @@ +/** + * This example shows how to use nested Stagehand pages within event listeners + * + * It also shows how to wait for something to happen on a page before continuing. + */ + +import { ObserveResult, Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; + +async function example() { + const stagehand = new Stagehand(StagehandConfig); + await stagehand.init(); + + const page = await stagehand.page; + + let observePromise: Promise; + + page.on("popup", async (newPage) => { + observePromise = newPage.observe({ + instruction: "return all the next possible actions from the page", + }); + }); + + await page.goto( + "https://docs.browserbase.com/integrations/crew-ai/introduction", + ); + + await page.click( + "#content-area > div.relative.mt-8.prose.prose-gray.dark\\:prose-invert > p:nth-child(2) > a", + ); + + await page.waitForTimeout(5000); + + if (observePromise) { + const observeResult = await observePromise; + + console.log("Observed", observeResult.length, "actions"); + } + + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/examples/pwtest.ts b/sdk/stagehand-ts/examples/pwtest.ts new file mode 100644 index 0000000..a223d30 --- /dev/null +++ b/sdk/stagehand-ts/examples/pwtest.ts @@ -0,0 +1,32 @@ +import { chromium } from "playwright"; +import Browserbase from "@browserbasehq/sdk"; +import dotenv from "dotenv"; + +dotenv.config(); + +const bb = new Browserbase({ + apiKey: process.env.BROWSERBASE_API_KEY, +}); +console.log(bb); + +(async () => { + // Create a new session + const session = await bb.sessions.create({ + projectId: process.env.BROWSERBASE_PROJECT_ID, + }); + console.log(session.id); + + // Connect to the session + const browser = await chromium.connectOverCDP(session.connectUrl); + + // Getting the default context to ensure the sessions are recorded. + const defaultContext = browser.contexts()[0]; + const page = defaultContext.pages()[0]; + let i = 0; + while (true) { + await page.goto("https://douglas.de/"); + i++; + console.log(i); + // await new Promise((resolve) => setTimeout(resolve, 1000)); + } +})().catch((error) => console.error(error.message)); diff --git a/sdk/stagehand-ts/examples/wordle.ts b/sdk/stagehand-ts/examples/wordle.ts new file mode 100644 index 0000000..9129f79 --- /dev/null +++ b/sdk/stagehand-ts/examples/wordle.ts @@ -0,0 +1,24 @@ +import { Stagehand } from "@browserbasehq/stagehand"; +import StagehandConfig from "@/stagehand.config"; + +async function example() { + const stagehand = new Stagehand({ + ...StagehandConfig, + }); + await stagehand.init(); + const page = stagehand.page; + await page.goto("https://www.nytimes.com/games/wordle/index.html"); + await page.act("click 'Continue'"); + await page.act("click 'Play'"); + await page.act("click cross sign on top right of 'How To Play' card"); + const word = "WORDS"; + for (const letter of word) { + await page.act(`press ${letter}`); + } + await page.act("press enter"); + await stagehand.close(); +} + +(async () => { + await example(); +})(); diff --git a/sdk/stagehand-ts/google-ts-sdk/google-genai-1.11.0.tgz b/sdk/stagehand-ts/google-ts-sdk/google-genai-1.11.0.tgz new file mode 100644 index 0000000..2fc0a96 Binary files /dev/null and b/sdk/stagehand-ts/google-ts-sdk/google-genai-1.11.0.tgz differ diff --git a/sdk/stagehand-ts/google-ts-sdk/package/LICENSE b/sdk/stagehand-ts/google-ts-sdk/package/LICENSE new file mode 100644 index 0000000..d645695 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/sdk/stagehand-ts/google-ts-sdk/package/README.google.md b/sdk/stagehand-ts/google-ts-sdk/package/README.google.md new file mode 100644 index 0000000..6d3257d --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/README.google.md @@ -0,0 +1,198 @@ +# GenAI JavaScript SDK User Guide (Internal) + +go/genai-js-sdk + + + +## Important + +### Open bugs and frictions against this [template](https://b.corp.google.com/issues/new?component=962606&template=2062941). It should be assigned to @asobran directly. + +### Use this [chat space](https://mail.google.com/mail/u/0/#chat/space/AAAAXILcELs) for questions or ping @annieluc or @yyyu. + +- This doc targets Google's internal developers only. + +- Go through the setup section before running the code. + +- Create a .ts file using the samples of this doc and run the code on this + doc. + +- Try to test out discovered functionality. + +# Module TOC + +- [Prerequisites](#prerequisites) +- [Models](#models) + +Use left nav table of contents to navigate to specific functionality. + +# Prerequisites + +## Get an API Key to access ML Dev APIs + +You need to get an `API key` to be able to call the ML Dev APIs using the +TypeScript SDK module. You can reuse the key that has been used in the +[Python SDK demo Colab](https://colab.research.google.com/drive/1K-RuGeP5WHV9gpGfm6_Gkk_IkTyCc2b0#scrollTo=EULDpjbDJ9LZ). + +## Export environment variables + +The samples will rely on environment variables to initialize the client. + +```bash +export GOOGLE_API_KEY={YOUR_API_KEY} +export GOOGLE_CLOUD_PROJECT={YOUR_CLOUD_PROJECT} +export GOOGLE_CLOUD_LOCATION={YOUR_CLOUD_LOCATION} +``` + +## Install NPM packages and run the samples + +The sample code is located at `./google/genai/sdk-samples` directory. Assuming you +are at the directory `google/genai`, run them as follows: + +```shell +# Run the sample against Vertex AI +export GOOGLE_GENAI_USE_VERTEXAI=true && npm install && npm run build && node dist/samples/generate_content_text.js +``` + +```shell +# Run the sample against ML Dev API +export GOOGLE_GENAI_USE_VERTEXAI=false && npm install && npm run build && node dist/samples/generate_content_text.js +``` + +You can see all the existing samples by running: + +```bash +ls -R samples | grep ".*\.ts$" +``` + +# Let's break it down: + +## Import + +```typescript +import { GoogleAuth, GoogleAuthOptions } from "google-auth-library"; + +import { Client } from "../src/client"; + +import process = require("process"); +``` + +## Create a client + +Please use one of the following code blocks to create a client for different +services (MLDev or Vertex). Feel free to switch the client and run all the +examples to see how it behaves under different APIs. + +```typescript +// Only use this block for ML Developer API +const client = new Client({ vertexai: false, apiKey: GOOGLE_API_KEY }); +``` + +```typescript +// Only use this block for Vertex AI API +const googleAuthOptions: GoogleAuthOptions = { + scopes: ["https://www.googleapis.com/auth/cloud-platform"], +}; +const googleAuth = new GoogleAuth(googleAuthOptions); +const client = new Client({ + vertexai: true, + project: GOOGLE_CLOUD_PROJECT, + googleAuth: googleAuth, +}); +``` + +## Models + +The `client.models` module exposes model inferencing and model getters. Below +are the models that are supported by the Go SDK so far: + +```javascript +generateContent(...): Promise +generateContentStream(...): Promise> +``` + +## Generate Content + +```typescript +const response = await client.models.generateContent( + "gemini-2.0-flash", + "why is the sky blue?", + {}, +); +console.debug(response.text()); +``` + +**Output:** + +```the + +**1. Sunlight and its Colors:** + +* Sunlight, as we know, appears white. However, it's actually made up of all the colors of the rainbow, each with a different wavelength. +* **Wavelength** refers to the distance between the peaks of a light wave. Red light has the longest wavelengths, and violet light has the shortest. + +**2. Earth's Atmosphere and Air Molecules:** + +* The Earth's atmosphere is primarily composed of nitrogen and oxygen molecules. These molecules are much smaller than the wavelengths of visible light. + +**3. Rayleigh Scattering Explained:** + +* When sunlight enters the atmosphere, it collides with these tiny air molecules. +* This collision causes the light to be scattered in different directions. +* **Crucially, shorter wavelengths of light (like blue and violet) are scattered much more effectively than longer wavelengths (like red and orange).** This is because the smaller wavelengths are more likely to be absorbed and re-emitted by the small air molecules. +* This preferential scattering of blue and violet light is called Rayleigh scattering. + +**4. Why We See Blue and Not Violet:** + +* While violet light is scattered even more than blue light, our eyes are less sensitive to violet. +* Additionally, the sun emits slightly less violet light than blue light. +* The combination of these factors results in us seeing a predominantly blue sky. + +**In simple terms, think of it like this:** + +Imagine you're throwing small balls (light waves) at a bunch of tiny obstacles (air molecules). The small balls (blue and violet light) are more likely to bounce off in many directions, while the larger balls (red and orange light) are more likely to pass through. The scattered small balls (blue and violet light) are what we see in the sky. + +**Other Relevant Points:** + +* **Why Sunsets and Sunrises are Red/Orange:** When the sun is near the horizon, the sunlight travels through a much longer path in the atmosphere. The blue light is scattered away in all directions, and the red and orange light, which is less scattered, makes it through to our eyes, giving us the beautiful sunsets and sunrises. +* **Why the Sky is Dark at Night:** When the sun is below the horizon, there is no direct sunlight to be scattered, resulting in a dark sky. We do see the stars, which emit their own light. + +**In summary, the sky is blue because of the way sunlight interacts with the small air molecules in our atmosphere. This interaction, known as Rayleigh scattering, preferentially scatters shorter wavelengths of light, like blue, in all directions.** +``` + +## Generate Content Streaming + +```typescript +const response = await client.models.generateContentStream( + "gemini-2.0-flash", + "tell me a joke", + {}, +); + +for await (const chunk of response) { + console.debug(chunk.text()); +} +``` + +**Output:** + +```okay +, here's a joke: + +Why don't scientists trust atoms? + + +Because they make up everything! +``` + +# Cleanup + +Once you're done running the samples, you can clean up the build artifacts by +running: + +```bash +rm -rf dist node_modules +``` diff --git a/sdk/stagehand-ts/google-ts-sdk/package/README.md b/sdk/stagehand-ts/google-ts-sdk/package/README.md new file mode 100644 index 0000000..6db8a77 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/README.md @@ -0,0 +1,359 @@ +# Google Gen AI SDK for TypeScript and JavaScript + +[![NPM Downloads](https://img.shields.io/npm/dw/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) +[![Node Current](https://img.shields.io/node/v/%40google%2Fgenai)](https://www.npmjs.com/package/@google/genai) + +--- + +**Documentation:** https://googleapis.github.io/js-genai/ + +--- + +The Google Gen AI JavaScript SDK is designed for +TypeScript and JavaScript developers to build applications powered by Gemini. The SDK +supports both the [Gemini Developer API](https://ai.google.dev/gemini-api/docs) +and [Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview). + +The Google Gen AI SDK is designed to work with Gemini 2.0 features. + +> [!CAUTION] > **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +## Prerequisites + +1. Node.js version 20 or later + +### The following are required for Vertex AI users (excluding Vertex AI Studio) + +1. [Select](https://console.cloud.google.com/project) or [create](https://cloud.google.com/resource-manager/docs/creating-managing-projects#creating_a_project) a Google Cloud project. +1. [Enable billing for your project](https://cloud.google.com/billing/docs/how-to/modify-project). +1. [Enable the Vertex AI API](https://console.cloud.google.com/flows/enableapi?apiid=aiplatform.googleapis.com). +1. [Configure authentication](https://cloud.google.com/docs/authentication) for your project. + _ [Install the gcloud CLI](https://cloud.google.com/sdk/docs/install). + _ [Initialize the gcloud CLI](https://cloud.google.com/sdk/docs/initializing). \* Create local authentication credentials for your user account: + + ```sh + gcloud auth application-default login + ``` + + A list of accepted authentication options are listed in [GoogleAuthOptions](https://github.com/googleapis/google-auth-library-nodejs/blob/3ae120d0a45c95e36c59c9ac8286483938781f30/src/auth/googleauth.ts#L87) interface of google-auth-library-node.js GitHub repo. + +## Installation + +To install the SDK, run the following command: + +```shell +npm install @google/genai +``` + +## Quickstart + +The simplest way to get started is to use an API key from +[Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import { GoogleGenAI } from "@google/genai"; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY }); + +async function main() { + const response = await ai.models.generateContent({ + model: "gemini-2.0-flash-001", + contents: "Why is the sky blue?", + }); + console.log(response.text); +} + +main(); +``` + +## Initialization + +The Google Gen AI SDK provides support for both the +[Google AI Studio](https://ai.google.dev/gemini-api/docs) and +[Vertex AI](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) +implementations of the Gemini API. + +### Gemini Developer API + +For server-side applications, initialize using an API key, which can +be acquired from [Google AI Studio](https://aistudio.google.com/apikey): + +```typescript +import { GoogleGenAI } from "@google/genai"; +const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" }); +``` + +#### Browser + +> [!CAUTION] > **API Key Security:** Avoid exposing API keys in client-side code. +> Use server-side implementations in production environments. + +In the browser the initialization code is identical: + +```typescript +import { GoogleGenAI } from "@google/genai"; +const ai = new GoogleGenAI({ apiKey: "GEMINI_API_KEY" }); +``` + +### Vertex AI + +Sample code for VertexAI initialization: + +```typescript +import { GoogleGenAI } from "@google/genai"; + +const ai = new GoogleGenAI({ + vertexai: true, + project: "your_project", + location: "your_location", +}); +``` + +### (Optional) (NodeJS only) Using environment variables: + +For NodeJS environments, you can create a client by configuring the necessary +environment variables. Configuration setup instructions depends on whether +you're using the Gemini Developer API or the Gemini API in Vertex AI. + +**Gemini Developer API:** Set `GOOGLE_API_KEY` as shown below: + +```bash +export GOOGLE_API_KEY='your-api-key' +``` + +**Gemini API on Vertex AI:** Set `GOOGLE_GENAI_USE_VERTEXAI`, +`GOOGLE_CLOUD_PROJECT` and `GOOGLE_CLOUD_LOCATION`, as shown below: + +```bash +export GOOGLE_GENAI_USE_VERTEXAI=true +export GOOGLE_CLOUD_PROJECT='your-project-id' +export GOOGLE_CLOUD_LOCATION='us-central1' +``` + +```typescript +import { GoogleGenAI } from "@google/genai"; + +const ai = new GoogleGenAI(); +``` + +## API Selection + +By default, the SDK uses the beta API endpoints provided by Google to support +preview features in the APIs. The stable API endpoints can be selected by +setting the API version to `v1`. + +To set the API version use `apiVersion`. For example, to set the API version to +`v1` for Vertex AI: + +```typescript +const ai = new GoogleGenAI({ + vertexai: true, + project: "your_project", + location: "your_location", + apiVersion: "v1", +}); +``` + +To set the API version to `v1alpha` for the Gemini Developer API: + +```typescript +const ai = new GoogleGenAI({ + apiKey: "GEMINI_API_KEY", + apiVersion: "v1alpha", +}); +``` + +## GoogleGenAI overview + +All API features are accessed through an instance of the `GoogleGenAI` classes. +The submodules bundle together related API methods: + +- [`ai.models`](https://googleapis.github.io/js-genai/release_docs/classes/models.Models.html): + Use `models` to query models (`generateContent`, `generateImages`, ...), or + examine their metadata. +- [`ai.caches`](https://googleapis.github.io/js-genai/release_docs/classes/caches.Caches.html): + Create and manage `caches` to reduce costs when repeatedly using the same + large prompt prefix. +- [`ai.chats`](https://googleapis.github.io/js-genai/release_docs/classes/chats.Chats.html): + Create local stateful `chat` objects to simplify multi turn interactions. +- [`ai.files`](https://googleapis.github.io/js-genai/release_docs/classes/files.Files.html): + Upload `files` to the API and reference them in your prompts. + This reduces bandwidth if you use a file many times, and handles files too + large to fit inline with your prompt. +- [`ai.live`](https://googleapis.github.io/js-genai/release_docs/classes/live.Live.html): + Start a `live` session for real time interaction, allows text + audio + video + input, and text or audio output. + +## Samples + +More samples can be found in the +[github samples directory](https://github.com/googleapis/js-genai/tree/main/sdk-samples). + +### Streaming + +For quicker, more responsive API interactions use the `generateContentStream` +method which yields chunks as they're generated: + +```typescript +import { GoogleGenAI } from "@google/genai"; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY }); + +async function main() { + const response = await ai.models.generateContentStream({ + model: "gemini-2.0-flash-001", + contents: "Write a 100-word poem.", + }); + for await (const chunk of response) { + console.log(chunk.text); + } +} + +main(); +``` + +### Function Calling + +To let Gemini to interact with external systems, you can provide +`functionDeclaration` objects as `tools`. To use these tools it's a 4 step + +1. **Declare the function name, description, and parametersJsonSchema** +2. **Call `generateContent` with function calling enabled** +3. **Use the returned `FunctionCall` parameters to call your actual function** +4. **Send the result back to the model (with history, easier in `ai.chat`) + as a `FunctionResponse`** + +```typescript +import { + GoogleGenAI, + FunctionCallingConfigMode, + FunctionDeclaration, + Type, +} from "@google/genai"; +const GEMINI_API_KEY = process.env.GEMINI_API_KEY; + +async function main() { + const controlLightDeclaration: FunctionDeclaration = { + name: "controlLight", + parametersJsonSchema: { + type: "object", + properties: { + brightness: { + type: "number", + }, + colorTemperature: { + type: "string", + }, + }, + required: ["brightness", "colorTemperature"], + }, + }; + + const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY }); + const response = await ai.models.generateContent({ + model: "gemini-2.0-flash-001", + contents: "Dim the lights so the room feels cozy and warm.", + config: { + toolConfig: { + functionCallingConfig: { + // Force it to call any function + mode: FunctionCallingConfigMode.ANY, + allowedFunctionNames: ["controlLight"], + }, + }, + tools: [{ functionDeclarations: [controlLightDeclaration] }], + }, + }); + + console.log(response.functionCalls); +} + +main(); +``` + +#### Model Context Protocol (MCP) support (experimental) + +Built-in [MCP](https://modelcontextprotocol.io/introduction) support is an +experimental feature. You can pass a local MCP server as a tool directly. + +```javascript +import { + GoogleGenAI, + FunctionCallingConfigMode, + mcpToTool, +} from "@google/genai"; +import { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js"; + +// Create server parameters for stdio connection +const serverParams = new StdioClientTransport({ + command: "npx", // Executable + args: ["-y", "@philschmid/weather-mcp"], // MCP Server +}); + +const client = new Client({ + name: "example-client", + version: "1.0.0", +}); + +// Configure the client +const ai = new GoogleGenAI({}); + +// Initialize the connection between client and server +await client.connect(serverParams); + +// Send request to the model with MCP tools +const response = await ai.models.generateContent({ + model: "gemini-2.5-flash", + contents: `What is the weather in London in ${new Date().toLocaleDateString()}?`, + config: { + tools: [mcpToTool(client)], // uses the session, will automatically call the tool using automatic function calling + }, +}); +console.log(response.text); + +// Close the connection +await client.close(); +``` + +### Generate Content + +#### How to structure `contents` argument for `generateContent` + +The SDK allows you to specify the following types in the `contents` parameter: + +#### Content + +- `Content`: The SDK will wrap the singular `Content` instance in an array which + contains only the given content instance +- `Content[]`: No transformation happens + +#### Part + +Parts will be aggregated on a singular Content, with role 'user'. + +- `Part | string`: The SDK will wrap the `string` or `Part` in a `Content` + instance with role 'user'. +- `Part[] | string[]`: The SDK will wrap the full provided list into a single + `Content` with role 'user'. + +**_NOTE:_** This doesn't apply to `FunctionCall` and `FunctionResponse` parts, +if you are specifying those, you need to explicitly provide the full +`Content[]` structure making it explicit which Parts are 'spoken' by the model, +or the user. The SDK will throw an exception if you try this. + +## How is this different from the other Google AI SDKs + +This SDK (`@google/genai`) is Google Deepmind’s "vanilla" SDK for its generative +AI offerings, and is where Google Deepmind adds new AI features. + +Models hosted either on the [Vertex AI platform](https://cloud.google.com/vertex-ai/generative-ai/docs/learn/overview) or the [Gemini Developer platform](https://ai.google.dev/gemini-api/docs) are accessible through this SDK. + +Other SDKs may be offering additional AI frameworks on top of this SDK, or may +be targeting specific project environments (like Firebase). + +The `@google/generative_language` and `@google-cloud/vertexai` SDKs are previous +iterations of this SDK and are no longer receiving new Gemini 2.0+ features. diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/genai.d.ts b/sdk/stagehand-ts/google-ts-sdk/package/dist/genai.d.ts new file mode 100644 index 0000000..2a9a536 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/genai.d.ts @@ -0,0 +1,7417 @@ +// @ts-ignore +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { GoogleAuthOptions } from "google-auth-library"; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd {} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION", +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart {} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO", +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH", +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig {} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH", +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule {} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: ( + params?: types.ListBatchJobsParameters, + ) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteBatchJobParameters, + ): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = + | BatchJobSource + | InlinedRequest[] + | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING", +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob }; + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: ( + params?: types.ListCachedContentsParameters, + ) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create( + params: types.CreateCachedContentParameters, + ): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteCachedContentParameters, + ): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update( + params: types.UpdateCachedContentParameters, + ): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor( + apiClient: ApiClient, + modelsModule: Models, + model: string, + config?: types.GenerateContentConfig, + history?: types.Content[], + ); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage( + params: types.SendMessageParameters, + ): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream( + params: types.SendMessageParameters, + ): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = + | Content + | Content[] + | PartUnion + | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH", +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent( + partOrString: PartListUnion | string, +): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64( + data: string, + mimeType: string, +): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult( + outcome: Outcome, + output: string, +): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode( + code: string, + language: Language, +): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall( + name: string, + args: Record, +): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse( + id: string, + name: string, + response: Record, +): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-1.0-pro-002". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent( + partOrString: PartListUnion | string, +): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse {} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse {} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse {} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +/** Hyperparameters for Distillation. */ +export declare interface DistillationHyperParameters { + /** Optional. Adapter size for distillation. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; +} + +/** Tuning Spec for Distillation. */ +export declare interface DistillationSpec { + /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseTeacherModel?: string; + /** Optional. Hyperparameters for Distillation. */ + hyperParameters?: DistillationHyperParameters; + /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */ + pipelineRootDirectory?: string; + /** The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use base_model instead. */ + studentModel?: string; + /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */ + tunedTeacherModelSource?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type DownloadableFileUnion = + | string + | File_2 + | GeneratedVideo + | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE", +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW", +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch {} + +/** Required. The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER", +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams {} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST", +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File }; + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED", +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED", +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL", +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */ + data?: Part[]; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT", +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation + implements Operation +{ + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: + | "UNKNOWN" + | "PRIORITIZE_QUALITY" + | "BALANCED" + | "PRIORITIZE_COST"; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY", +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF", +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT", +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH", +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH", +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: "GET" | "POST" | "PATCH" | "DELETE"; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image }; + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es", +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED", +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON", +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT", +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete {} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts( + params: types.LiveMusicSetWeightedPromptsParameters, + ): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig( + params: types.LiveMusicSetConfigParameters, + ): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC", +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool( + ...args: [...Client[], CallableToolConfig | Client] +): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT", +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH", +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO", +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: ( + params: types.GenerateContentParameters, + ) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: ( + params: types.GenerateContentParameters, + ) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: ( + params: types.GenerateImagesParameters, + ) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: ( + params: types.EditImageParameters, + ) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: ( + params: types.UpscaleImageParameters, + ) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: ( + params: types.GenerateVideosParameters, + ) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent( + params: types.EmbedContentParameters, + ): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete( + params: types.DeleteModelParameters, + ): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens( + params: types.CountTokensParameters, + ): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens( + params: types.ComputeTokensParameters, + ): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation( + parameters: types.OperationGetParameters< + types.GenerateVideosResponse, + types.GenerateVideosOperation + >, + ): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>( + parameters: types.OperationGetParameters, + ): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED", +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents", +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: ( + params: PagedItemConfig, + ) => Promise>; + protected idxInternal: number; + constructor( + name: PagedItem, + request: (params: PagedItemConfig) => Promise>, + response: PagedItemResponse, + params: PagedItemConfig, + ); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL", +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +export declare type ReferenceImage = + | RawReferenceImage + | MaskReferenceImage + | ControlReferenceImage + | StyleReferenceImage + | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + 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", +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR", +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls( + baseUrlParams: BaseUrlParameters, +): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW", +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT", +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** + Tool to support the model interacting directly with the computer. + If enabled, it automatically populates computer-use specific Function + Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution {} + +/** Computer Use tool type. */ +export declare interface ToolComputerUse { + /** A list of predefined functions that the should not be prepopulated. */ + excludedPredefinedFunctions?: string[]; + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT", +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Tuning Spec for Distillation. */ + distillationSpec?: DistillationSpec; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** Output only. Reserved for future use. */ + satisfiesPzi?: boolean; + /** Output only. Reserved for future use. */ + satisfiesPzs?: boolean; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: ( + params?: types.ListTuningJobsParameters, + ) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT", +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL", +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + Environment, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + DistillationHyperParameters, + DistillationSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParameters, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveSendRealtimeInputParameters, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion, + }; +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload( + file: string | Blob, + uploadUrl: string, + apiClient: ApiClient, + ): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext {} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS", +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create( + url: string, + headers: Record, + callbacks: WebSocketCallbacks, + ): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export {}; diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/index.cjs b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.cjs new file mode 100644 index 0000000..d5daf24 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.cjs @@ -0,0 +1,20272 @@ +"use strict"; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule {} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ""; + } else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if ( + !value || + (typeof value === "object" && Object.keys(value).length === 0) + ) { + return; + } + if (value === existingData) { + return; + } + if ( + typeof existingData === "object" && + typeof value === "object" && + existingData !== null && + value !== null + ) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === "_self") { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== "object" || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } else { + return undefined; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = + "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = + "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = + "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = + "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** Required. The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = + "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = + "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = + "URL_RETRIEVAL_STATUS_ERROR"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = + "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = + "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = + "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})( + exports.FeatureSelectionPreference || + (exports.FeatureSelectionPreference = {}), +); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})( + exports.DynamicRetrievalConfigMode || + (exports.DynamicRetrievalConfigMode = {}), +); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})( + exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {}), +); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = + "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = + "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = + "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = + "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})( + exports.FunctionResponseScheduling || + (exports.FunctionResponseScheduling = {}), +); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = + "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse {} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === "object" && obj !== null) { + return ( + "fileData" in obj || + "text" in obj || + "functionCall" in obj || + "functionResponse" in obj || + "inlineData" in obj || + "videoMetadata" in obj || + "codeExecutionResult" in obj || + "executableCode" in obj + ); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === "string") { + parts.push(createPartFromText(partOrString)); + } else if (_isPart(partOrString)) { + parts.push(partOrString); + } else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error("partOrString cannot be an empty array"); + } + for (const part of partOrString) { + if (typeof part === "string") { + parts.push(createPartFromText(part)); + } else if (_isPart(part)) { + parts.push(part); + } else { + throw new Error("element in PartUnion must be a Part object or string"); + } + } + } else { + throw new Error("partOrString must be a Part object, string, or array"); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: "user", + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: "model", + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback {} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata {} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning text from the first one.", + ); + } + let text = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning data from the first one.", + ); + } + let data = ""; + const nonDataParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "inlineData" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning function calls from the first one.", + ); + } + const functionCalls = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.functionCall) + .map((part) => part.functionCall) + .filter((functionCall) => functionCall !== undefined); + if ( + (functionCalls === null || functionCalls === void 0 + ? void 0 + : functionCalls.length) === 0 + ) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning executable code from the first one.", + ); + } + const executableCode = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.executableCode) + .map((part) => part.executableCode) + .filter((executableCode) => executableCode !== undefined); + if ( + (executableCode === null || executableCode === void 0 + ? void 0 + : executableCode.length) === 0 + ) { + return undefined; + } + return (_j = + executableCode === null || executableCode === void 0 + ? void 0 + : executableCode[0]) === null || _j === void 0 + ? void 0 + : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning code execution result from the first one.", + ); + } + const codeExecutionResult = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.codeExecutionResult) + .map((part) => part.codeExecutionResult) + .filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ( + (codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult.length) === 0 + ) { + return undefined; + } + return (_j = + codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult[0]) === null || _j === void 0 + ? void 0 + : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse {} +/** The output images response. */ +class GenerateImagesResponse {} +/** Response for the request to edit an image. */ +class EditImageResponse {} +class UpscaleImageResponse {} +class ListModelsResponse {} +class DeleteModelResponse {} +/** Response for counting tokens. */ +class CountTokensResponse {} +/** Response for computing tokens. */ +class ComputeTokensResponse {} +/** Response with generated videos. */ +class GenerateVideosResponse {} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse {} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse {} +class ListCachedContentsResponse {} +/** Response for the list files method. */ +class ListFilesResponse {} +/** Response for the create file method. */ +class CreateFileResponse {} +/** Response for the delete file method. */ +class DeleteFileResponse {} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse {} +/** Config for batches.list return value. */ +class ListBatchJobsResponse {} +/** Represents a single response in a replay. */ +class ReplayResponse {} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_RAW", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_MASK", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_CONTROL", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_STYLE", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_SUBJECT", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + fieldValue !== null + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse["name"]; + operation.metadata = apiResponse["metadata"]; + operation.done = apiResponse["done"]; + operation.error = apiResponse["error"]; + if (isVertexAI) { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response["videos"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo["gcsUri"], + videoBytes: generatedVideo["bytesBase64Encoded"] + ? tBytes$1(generatedVideo["bytesBase64Encoded"]) + : undefined, + mimeType: generatedVideo["mimeType"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } else { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response["generateVideoResponse"]; + const responseVideos = + generatedVideoResponse === null || generatedVideoResponse === void 0 + ? void 0 + : generatedVideoResponse["generatedSamples"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + const video = generatedVideo["video"]; + return { + video: { + uri: + video === null || video === void 0 + ? void 0 + : video["uri"], + videoBytes: ( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"] + ) + ? tBytes$1( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"], + ) + : undefined, + mimeType: generatedVideo["encoding"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse {} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if ( + this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0 + ) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (apiClient.isVertexAI()) { + if ( + model.startsWith("publishers/") || + model.startsWith("projects/") || + model.startsWith("models/") + ) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error( + `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`, + ); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("image/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("audio/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "parts" in origin && + Array.isArray(origin.parts) + ); +} +function _isFunctionCallPart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionCall" in origin + ); +} +function _isFunctionResponsePart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionResponse" in origin + ); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: "user", + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error( + "To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them", + ); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new 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 (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(exports.Type).includes( + listWithoutNull[0].toUpperCase(), + ) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i of listWithoutNull) { + resultingSchema["anyOf"].push({ + type: Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error( + "type: null can not be the only possible type for the field.", + ); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema["type"] = Object.values(exports.Type).includes( + fieldValue.toUpperCase(), + ) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error( + "multiSpeakerVoiceConfig is not supported in the live API.", + ); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema( + functionDeclaration.parameters, + ); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema( + functionDeclaration.response, + ); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName( + client, + resourceName, + resourcePrefix, + splitsAfterPrefix = 1, +) { + const shouldAppendPrefix = + !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith("projects/")) { + return resourceName; + } else if (resourceName.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName}`; + } else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "name" in origin + ); +} +function isGeneratedVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "video" in origin + ); +} +function isVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "uri" in origin + ); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === undefined) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"], + }; + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [functionDeclaration], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== "string" && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set."); + } else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error("One of `gcsUri` or `bigqueryUri` must be set."); + } + } else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error( + "Only one of `inlinedRequests` or `fileName` can be set.", + ); + } else if (!src.inlinedRequests && !src.fileName) { + throw new Error("One of `inlinedRequests` or `fileName` must be set."); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } else if (typeof src === "string") { + if (src.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: [src], // GCS URI is expected as an array + }; + } else if (src.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: src, + }; + } else if (src.startsWith("files/")) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString, + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString, + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = + /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$4(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$4(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$4(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$4(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$2(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$2(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$4(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev$1(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$2(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev$1(fromThinkingConfig), + ); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath( + toObject, + ["request", "model"], + tModel(apiClient, fromModel), + ); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["request", "generationConfig"], + generateContentConfigToMldev$1(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["format"]) !== undefined) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["bigqueryUri"]) !== undefined) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, ["inlinedRequests"]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject, ["dest"]) !== undefined) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["batch", "inputConfig"], + batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject, ["filter"]) !== undefined) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedRequests"]) !== undefined) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath( + toObject, + ["bigqueryDestination", "outputUri"], + fromBigqueryUri, + ); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedResponses"]) !== undefined) { + throw new Error( + "inlinedResponses parameter is not supported in Vertex AI.", + ); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ["dest"]); + if (parentObject !== undefined && fromDest != null) { + setValueByPath( + parentObject, + ["outputConfig"], + batchJobDestinationToVertex(tBatchJobDestination(fromDest)), + ); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["inputConfig"], + batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev$1(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$2(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateContentResponseFromMldev$1(fromResponse), + ); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + "inlinedResponses", + "inlinedResponses", + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + "metadata", + "displayName", + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["metadata", "createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, ["metadata", "endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["metadata", "updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigquerySource", + "inputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + "gcsDestination", + "outputUriPrefix", + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigqueryDestination", + "outputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["batchPredictionJobs"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = + response === null || response === void 0 + ? void 0 + : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = + (_a = requestParams["config"]) === null || _a === void 0 + ? void 0 + : _a["pageSize"]) !== null && _b !== void 0 + ? _b + : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if ( + ((_a = this.params["config"]) === null || _a === void 0 + ? void 0 + : _a["pageToken"]) !== undefined + ) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error( + "InlinedRequest[] is not supported in Vertex AI. Please use " + + "Google Cloud Storage URI or BigQuery URI instead.", + ); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = "genaiBatchJob_${timestampStr}"; + } + if ( + params.config.dest === undefined && + typeof params.src === "string" + ) { + if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } else if (params.src.startsWith("bq://")) { + params.config.dest = `${params.src}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source:" + params.src); + } + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_BATCH_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$3(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$3(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$3(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$3(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$3(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$1(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["kmsKeyName"]) !== undefined) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$2() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$2(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$2(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$2(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$2(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$2()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex$1(fromToolConfig), + ); + } + const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath( + parentObject, + ["encryption_spec", "kmsKeyName"], + fromKmsKeyName, + ); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined.", + ); +} + +function __await(v) { + return this instanceof __await ? ((this.v = v), this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = Object.create( + (typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype, + )), + verb("next"), + verb("throw"), + verb("return", awaitReturn), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" ? __values(o) : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ value: v, done: d }); + }, reject); + } +} + +typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = + (_a = response.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (!part.thought && part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === "user") { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === "model") { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history), + ); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = + (_b = + (_a = response.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = + response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && + _c !== void 0 + ? _c + : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory( + inputContent, + modelOutput, + automaticFunctionCallingHistory, + ); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for ( + var _f = true, + streamResponse_1 = __asyncValues(streamResponse), + streamResponse_1_1; + (streamResponse_1_1 = yield __await(streamResponse_1.next())), + (_c = streamResponse_1_1.done), + !_c; + _f = true + ) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = + (_b = + (_a = chunk.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) + yield __await(_d.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }, + ); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if ( + modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined) + ) { + outputContents = modelOutput; + } else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: "model", + parts: [], + }); + } + if ( + automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0 + ) { + this.history.push( + ...extractCuratedHistory(automaticFunctionCallingHistory), + ); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = "Content-Type"; +const SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; +const USER_AGENT_HEADER = "User-Agent"; +const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; +const SDK_VERSION = "1.11.0"; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; +const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { + project: opts.project, + location: opts.location, + apiKey: opts.apiKey, + vertexai: opts.vertexai, + }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 + ? _a + : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 + ? _b + : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions( + initHttpOptions, + opts.httpOptions, + ); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if ( + this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== "global" + ) { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 + ? _a + : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined + ) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error("API version is not set."); + } + getBaseUrl() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined + ) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error("Base URL is not set."); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined + ) { + return this.clientOptions.httpOptions.headers; + } else { + throw new Error("Headers are not set."); + } + } + getRequestUrlInternal(httpOptions) { + if ( + !httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined + ) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== "") { + urlElement.push(path); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if ( + request.httpMethod === "GET" && + request.path.startsWith("publishers/google/models") + ) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error( + "Request body should be empty for GET request, but got non empty request body", + ); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === "object") { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign( + Object.assign({}, patchedHttpOptions[key]), + value, + ); + } else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit( + requestInit, + httpOptions, + abortSignal, + ) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if ( + httpOptions.timeout && + (httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.timeout) > 0 + ) { + const timeoutHandle = setTimeout( + () => abortController.abort(), + httpOptions.timeout, + ); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + const reader = + (_a = + response === null || response === void 0 + ? void 0 + : response.body) === null || _a === void 0 + ? void 0 + : _a.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse( + JSON.stringify(chunkJson["error"]), + ); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } catch (e) { + const error = e; + if (error.name === "ApiError") { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: + response === null || response === void 0 + ? void 0 + : response.headers, + status: + response === null || response === void 0 + ? void 0 + : response.status, + statusText: + response === null || response === void 0 + ? void 0 + : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } catch (e) { + throw new Error( + `exception parsing stream chunk ${processedChunkString}. ${e}`, + ); + } + } + } + } finally { + reader.releaseLock(); + } + }, + ); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = + LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append( + SERVER_TIMEOUT_HEADER, + String(Math.ceil(httpOptions.timeout / 1000)), + ); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = + (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== + null && _a !== void 0 + ? _a + : fileStat.type; + if (mimeType === undefined || mimeType === "") { + throw new Error( + "Can not determine mimeType. Please provide mimeType in the config.", + ); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } else { + httpOptions = { + apiVersion: "", + headers: { + "Content-Type": "application/json", + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`, + "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`, + }, + }; + } + const body = { + file: file, + }; + const httpResponse = await this.request({ + path: formatMap("upload/v1beta/files", body["_url"]), + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions, + }); + if ( + !httpResponse || + !(httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) + ) { + throw new Error( + "Server did not return an HttpResponse or the returned HttpResponse did not have headers.", + ); + } + const uploadUrl = + (_a = + httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) === null || _a === void 0 + ? void 0 + : _a["x-goog-upload-url"]; + if (uploadUrl === undefined) { + throw new Error( + "Failed to get upload url. Server did not return the x-google-upload-url in the headers", + ); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ( + (_a = response.headers.get("content-type")) === null || _a === void 0 + ? void 0 + : _a.includes("application/json") + ) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn( + "includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.", + ); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if ( + typeof parsedBody === "object" && + parsedBody !== null && + !Array.isArray(parsedBody) + ) { + currentBodyObject = parsedBody; + } else { + console.warn( + "includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.", + ); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } catch (e) { + console.warn( + "includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.", + ); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if ( + sourceValue && + typeof sourceValue === "object" && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === "object" && + !Array.isArray(targetValue) + ) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if ( + targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue + ) { + console.warn( + `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`, + ); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + throw crossError(); + } else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === "string") { + throw crossError(); + } else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 ? void 0 : response.headers) === + null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listFilesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_FILES, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error( + "Vertex AI does not support uploading files. You can share files through a GCS bucket.", + ); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = listFilesParametersToMldev(params); + path = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createFileParametersToMldev(params); + path = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = getFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = deleteFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$2(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev$1(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev$1(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev$1(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev$1(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev$1(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev$1(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ["setup"]); + if (fromSetup != null) { + setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentToMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + const fromPlaybackControl = getValueByPath(fromObject, ["playbackControl"]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ["playbackControl"], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex$1(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$1(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$1(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$1(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$1(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$1()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ["transparent"]); + if (fromTransparent != null) { + setValueByPath(toObject, ["transparent"], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToVertex(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToVertex(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToVertex$1(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToVertex(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToVertex(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToVertex(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToVertex(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromMldev(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromMldev(fromOutputTranscription), + ); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$1(fromUrlContextMetadata), + ); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "responseTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "responseTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromMldev(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromMldev(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromMldev(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromMldev(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate), + ); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentFromMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, ["sourceMetadata"]); + if (fromSourceMetadata != null) { + setValueByPath( + toObject, + ["sourceMetadata"], + liveMusicSourceMetadataFromMldev(fromSourceMetadata), + ); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ["audioChunks"], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, ["filteredReason"]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ["filteredReason"], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveMusicServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveMusicServerContentFromMldev(fromServerContent), + ); + } + const fromFilteredPrompt = getValueByPath(fromObject, ["filteredPrompt"]); + if (fromFilteredPrompt != null) { + setValueByPath( + toObject, + ["filteredPrompt"], + liveMusicFilteredPromptFromMldev(fromFilteredPrompt), + ); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ["sessionId"]); + if (fromSessionId != null) { + setValueByPath(toObject, ["sessionId"], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromVertex(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromVertex(fromOutputTranscription), + ); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "candidatesTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "candidatesTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromVertex(fromSetupComplete), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromVertex(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromVertex(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromVertex(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromVertex(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath( + toObject, + ["goAway"], + liveServerGoAwayFromVertex(fromGoAway), + ); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$1(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$1(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["requests[]", "outputDimensionality"], + fromOutputDimensionality, + ); + } + if (getValueByPath(fromObject, ["mimeType"]) !== undefined) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["autoTruncate"]) !== undefined) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["requests[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToMldev(fromConfig, toObject), + ); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]); + if (fromModelForEmbedContent !== undefined) { + setValueByPath( + toObject, + ["requests[]", "model"], + tModel(apiClient, fromModelForEmbedContent), + ); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["negativePrompt"]) !== undefined) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + if (getValueByPath(fromObject, ["addWatermark"]) !== undefined) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["imageSize"]) !== undefined) { + throw new Error("imageSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["enhancePrompt"]) !== undefined) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["systemInstruction"]) !== undefined) { + throw new Error( + "systemInstruction parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["tools"]) !== undefined) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["generationConfig"]) !== undefined) { + throw new Error( + "generationConfig parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["fps"]) !== undefined) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + if (getValueByPath(fromObject, ["resolution"]) !== undefined) { + throw new Error("resolution parameter is not supported in Gemini API."); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + if (getValueByPath(fromObject, ["pubsubTopic"]) !== undefined) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + if (getValueByPath(fromObject, ["generateAudio"]) !== undefined) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["lastFrame"]) !== undefined) { + throw new Error("lastFrame parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["compressionQuality"]) !== undefined) { + throw new Error( + "compressionQuality parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToMldev(fromImage), + ); + } + if (getValueByPath(fromObject, ["video"]) !== undefined) { + throw new Error("video parameter is not supported in Gemini API."); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + "featureSelectionPreference", + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath( + toObject, + ["featureSelectionPreference"], + fromFeatureSelectionPreference, + ); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ["method"]); + if (fromMethod != null) { + setValueByPath(toObject, ["method"], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToVertex(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, ["routingConfig"]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + "modelSelectionConfig", + ]); + if (fromModelSelectionConfig != null) { + setValueByPath( + toObject, + ["modelConfig"], + modelSelectionConfigToVertex(fromModelSelectionConfig), + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex(fromToolConfig), + ); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToVertex(tSpeechConfig(fromSpeechConfig)), + ); + } + const fromAudioTimestamp = getValueByPath(fromObject, ["audioTimestamp"]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToVertex(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["parameters", "outputDimensionality"], + fromOutputDimensionality, + ); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath( + parentObject, + ["parameters", "autoTruncate"], + fromAutoTruncate, + ); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["instances[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromImageSize = getValueByPath(fromObject, ["imageSize"]); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath( + parentObject, + ["parameters", "sampleImageSize"], + fromImageSize, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + "segmentationClasses", + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + "enableControlImageComputation", + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath( + toObject, + ["computeControl"], + fromEnableControlImageComputation, + ); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, ["styleDescription"]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ["styleDescription"], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ["subjectType"]); + if (fromSubjectType != null) { + setValueByPath(toObject, ["subjectType"], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + "subjectDescription", + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, ["referenceImage"]); + if (fromReferenceImage != null) { + setValueByPath( + toObject, + ["referenceImage"], + imageToVertex(fromReferenceImage), + ); + } + const fromReferenceId = getValueByPath(fromObject, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, ["referenceType"]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, ["maskImageConfig"]); + if (fromMaskImageConfig != null) { + setValueByPath( + toObject, + ["maskImageConfig"], + maskReferenceConfigToVertex(fromMaskImageConfig), + ); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + "controlImageConfig", + ]); + if (fromControlImageConfig != null) { + setValueByPath( + toObject, + ["controlImageConfig"], + controlReferenceConfigToVertex(fromControlImageConfig), + ); + } + const fromStyleImageConfig = getValueByPath(fromObject, ["styleImageConfig"]); + if (fromStyleImageConfig != null) { + setValueByPath( + toObject, + ["styleImageConfig"], + styleReferenceConfigToVertex(fromStyleImageConfig), + ); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + "subjectImageConfig", + ]); + if (fromSubjectImageConfig != null) { + setValueByPath( + toObject, + ["subjectImageConfig"], + subjectReferenceConfigToVertex(fromSubjectImageConfig), + ); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromEditMode = getValueByPath(fromObject, ["editMode"]); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath( + parentObject, + ["parameters", "editConfig", "baseSteps"], + fromBaseSteps, + ); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, ["referenceImages"]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath( + toObject, + ["instances[0]", "referenceImages"], + transformedList, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + editImageConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + "enhanceInputImage", + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "enhanceInputImage"], + fromEnhanceInputImage, + ); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + "imagePreservationFactor", + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "imagePreservationFactor"], + fromImagePreservationFactor, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromMode = getValueByPath(fromObject, ["mode"]); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromUpscaleFactor = getValueByPath(fromObject, ["upscaleFactor"]); + if (fromUpscaleFactor != null) { + setValueByPath( + toObject, + ["parameters", "upscaleConfig", "upscaleFactor"], + fromUpscaleFactor, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + countTokensConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromFps = getValueByPath(fromObject, ["fps"]); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromResolution = getValueByPath(fromObject, ["resolution"]); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath( + parentObject, + ["parameters", "pubsubTopic"], + fromPubsubTopic, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + const fromGenerateAudio = getValueByPath(fromObject, ["generateAudio"]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath( + parentObject, + ["parameters", "generateAudio"], + fromGenerateAudio, + ); + } + const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath( + parentObject, + ["instances[0]", "lastFrame"], + imageToVertex(fromLastFrame), + ); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + "compressionQuality", + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "compressionQuality"], + fromCompressionQuality, + ); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath( + toObject, + ["instances[0]", "video"], + videoToVertex(fromVideo), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromMldev(fromSafetyAttributes), + ); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromMldev(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromMldev(fromTunedModelInfo), + ); + } + const fromInputTokenLimit = getValueByPath(fromObject, ["inputTokenLimit"]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, ["outputTokenLimit"]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + "supportedGenerationMethods", + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["video", "uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["video", "encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["generatedSamples"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + "response", + "generateVideoResponse", + ]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromMldev(fromResponse), + ); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citations"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromVertex(fromCitationMetadata), + ); + } + const fromFinishMessage = getValueByPath(fromObject, ["finishMessage"]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ["finishMessage"], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromVertex(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ["statistics"]); + if (fromStatistics != null) { + setValueByPath( + toObject, + ["statistics"], + contentEmbeddingStatisticsFromVertex(fromStatistics), + ); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + "billableCharacterCount", + ]); + if (fromBillableCharacterCount != null) { + setValueByPath( + toObject, + ["billableCharacterCount"], + fromBillableCharacterCount, + ); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + "predictions[]", + "embeddings", + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath( + toObject, + ["metadata"], + embedContentMetadataFromVertex(fromMetadata), + ); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromVertex(fromSafetyAttributes), + ); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromVertex(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, ["deployedModelId"]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + "labels", + "google-vertex-llm-tuning-base-model-id", + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromVertex(fromTunedModelInfo), + ); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]); + if (fromTokensInfo != null) { + setValueByPath(toObject, ["tokensInfo"], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromVertex(fromResponse), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = "mcp_used/unknown"; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = + (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 + ? _a + : ""; + headers[GOOGLE_API_CLIENT_HEADER] = ( + existingHeader + ` ${MCP_LABEL}` + ).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return ( + object !== null && + typeof object === "object" && + object instanceof McpCallableTool + ); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for ( + var _d = true, + _e = ((e_1 = void 0), __asyncValues(listAllTools(mcpClient))), + _f; + (_f = await _e.next()), (_a = _f.done), !_a; + _d = true + ) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, + requestOptions, + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return ( + client !== null && + typeof client === "object" && + "listTools" in client && + typeof client.listTools === "function" + ); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error("No MCP clients provided"); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error("Live music is not supported for Vertex AI."); + } + console.warn( + "Live music generation is experimental and may change in future versions.", + ); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap$1(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if ( + !params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0 + ) { + throw new Error( + "Weighted prompts must be set and contain at least one entry.", + ); + } + const setWeightedPromptsParameters = + liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev( + setWeightedPromptsParameters, + ); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = + "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic( + this.apiClient, + this.auth, + this.webSocketFactory, + ); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error( + "The Live module does not support httpOptions at request-level in" + + " LiveConnectConfig yet. Please use the client-level httpOptions" + + " configuration instead.", + ); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const defaultHeaders = this.apiClient.getDefaultHeaders(); + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + setMcpUsageHeader(defaultHeaders); + } + const headers = mapToHeaders(defaultHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if ( + apiKey === null || apiKey === void 0 + ? void 0 + : apiKey.startsWith("auth_tokens/") + ) { + console.warn( + "Warning: Ephemeral token support is experimental and may change in future versions.", + ); + if (apiVersion !== "v1alpha") { + 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.", + ); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onopen) === null || _a === void 0 + ? void 0 + : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if ( + this.apiClient.isVertexAI() && + transformedModel.startsWith("publishers/") + ) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if ( + this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 + ? void 0 + : _c.responseModalities) === undefined + ) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ( + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.generationConfig + ) { + // Raise deprecation warning for 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).", + ); + } + const inputTools = + (_f = + (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== + null && _f !== void 0 + ? _f + : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex( + this.apiClient, + liveConnectParameters, + ); + } else { + clientMessage = liveConnectParametersToMldev( + this.apiClient, + liveConnectParameters, + ); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a) { + throw new Error( + `Failed to parse client content "turns", type: '${typeof params.turns}'`, + ); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if ( + typeof functionResponse !== "object" || + functionResponse === null || + !("name" in functionResponse) || + !("response" in functionResponse) + ) { + throw new Error( + `Could not parse function response, type '${typeof functionResponse}'.`, + ); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign( + Object.assign({}, defaultLiveSendClientContentParamerters), + params, + ); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToVertex(params), + }; + } else { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ( + (_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.disable + ) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = + config === null || config === void 0 ? void 0 : config.tools) !== null && + _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = + (_c = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _c === void 0 + ? void 0 + : _c.maximumRemoteCalls; + if ( + (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0 + ) { + 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:", + maxCalls, + ); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error( + "Automatic function calling with CallableTools and Tools is not yet supported.", + ); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents( + transformedParams.contents, + ); + const maxRemoteCalls = + (_c = + (_b = + (_a = transformedParams.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.tools) !== null && _e !== void 0 + ? _e + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if ( + apiResponse === null || apiResponse === void 0 + ? void 0 + : apiResponse.generatedImages + ) { + for (const generatedImage of apiResponse.generatedImages) { + if ( + generatedImage && + (generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) && + ((_a = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) === null || _a === void 0 + ? void 0 + : _a.contentType) === "Positive Prompt" + ) { + positivePromptSafetyAttributes = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign( + Object.assign({}, defaultConfig), + params === null || params === void 0 ? void 0 : params.config, + ); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ( + (_a = actualParams.config) === null || _a === void 0 + ? void 0 + : _a.filter + ) { + throw new Error( + "Filtering tuned models list for Vertex AI is not currently supported", + ); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager( + exports.PagedItem.PAGED_ITEM_MODELS, + (x) => this.listInternal(x), + await this.listInternal(actualParams), + actualParams, + ); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => + img.toReferenceImageAPI(), + ); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale", + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all( + tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + }), + ); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { + tools: transformedTools, + }), + }; + newParams.config.tools = transformedTools; + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + const headers = + (_c = + (_b = params.config.httpOptions) === null || _b === void 0 + ? void 0 + : _b.headers) !== null && _c !== void 0 + ? _c + : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign( + Object.assign({}, params.config.httpOptions), + { headers: newHeaders }, + ); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== + null && _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = + toolDeclaration.functionDeclarations) !== null && _c !== void 0 + ? _c + : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error( + `Duplicate tool declaration name: ${declaration.name}`, + ); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = + (_c = + (_b = + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await( + models.processParamsMaybeAddMcpUsage(params), + ); + const response = yield __await( + models.generateContentStreamInternal(transformedParams), + ); + const functionResponses = []; + const responseContents = []; + try { + for ( + var _f = true, + response_1 = ((e_1 = void 0), __asyncValues(response)), + response_1_1; + (response_1_1 = yield __await(response_1.next())), + (_c = response_1_1.done), + !_c; + _f = true + ) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if ( + chunk.candidates && + ((_a = chunk.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content) + ) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== + null && _b !== void 0 + ? _b + : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error( + "Function call name was not returned by the model.", + ); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error( + `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`, + ); + } else { + const responseParts = yield __await( + afcTools + .get(part.functionCall.name) + .callTool([part.functionCall]), + ); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = response_1.return)) + yield __await(_d.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat( + newContents, + ); + params.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for ( + var _d = true, + apiResponse_1 = __asyncValues(apiResponse), + apiResponse_1_1; + (apiResponse_1_1 = yield __await(apiResponse_1.next())), + (_a = apiResponse_1_1.done), + !_a; + _d = true + ) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) + yield __await(_b.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for ( + var _d = true, + apiResponse_2 = __asyncValues(apiResponse), + apiResponse_2_1; + (apiResponse_2_1 = yield __await(apiResponse_2.next())), + (_a = apiResponse_2_1.done), + !_a; + _d = true + ) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) + yield __await(_b.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex( + this.apiClient, + params, + ); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev(fromProactivity), + ); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + "newSessionExpireTime", + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath( + parentObject, + ["newSessionExpireTime"], + fromNewSessionExpireTime, + ); + } + const fromUses = getValueByPath(fromObject, ["uses"]); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + "liveConnectConstraints", + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath( + parentObject, + ["bidiGenerateContentSetup"], + liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints), + ); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + "lockAdditionalFields", + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createAuthTokenConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if ( + typeof value === "object" && + value != null && + Object.keys(value).length > 0 + ) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); // 1st layer + } + } + } + return fields.join(","); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if ( + typeof bidiGenerateContentSetupValue === "object" && + bidiGenerateContentSetupValue !== null && + "setup" in bidiGenerateContentSetupValue + ) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + // Valid inner setup found. + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if ( + Array.isArray( + config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields, + ) && + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields.length) === 0 + ) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; // If mask is empty, effectively no + // specific fields locked by bidi + } + } else if ( + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig", + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict["fieldMask"]; + } + } else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict["fieldMask"]; + } + } else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if ( + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "The client.tokens.create method is only supported by the Gemini Developer API.", + ); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ["textInput"]); + if (fromTextInput != null) { + setValueByPath(toObject, ["textInput"], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ["output"]); + if (fromOutput != null) { + setValueByPath(toObject, ["output"], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== undefined) { + throw new Error( + "vertexDatasetResource parameter is not supported in Gemini API.", + ); + } + const fromExamples = getValueByPath(fromObject, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["validationDataset"]) !== undefined) { + throw new Error( + "validationDataset parameter is not supported in Gemini API.", + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ["description"]) !== undefined) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath( + toObject, + ["tuningTask", "hyperparameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== undefined) { + throw new Error( + "exportLastCheckpointOnly parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["adapterSize"]) !== undefined) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject, ["batchSize"]); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "batchSize"], + fromBatchSize, + ); + } + const fromLearningRate = getValueByPath(fromObject, ["learningRate"]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "learningRate"], + fromLearningRate, + ); + } + return toObject; +} +function createTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["tuningTask", "trainingData"], + tuningDatasetToMldev(fromTrainingDataset), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromGcsUri, + ); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + if (getValueByPath(fromObject, ["examples"]) !== undefined) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + "validationDataset", + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec"], + tuningValidationDatasetToVertex(fromValidationDataset, toObject), + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath( + parentObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + "exportLastCheckpointOnly", + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "exportLastCheckpointOnly"], + fromExportLastCheckpointOnly, + ); + } + const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "adapterSize"], + fromAdapterSize, + ); + } + if (getValueByPath(fromObject, ["batchSize"]) !== undefined) { + throw new Error("batchSize parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["learningRate"]) !== undefined) { + throw new Error("learningRate parameter is not supported in Vertex AI."); + } + return toObject; +} +function createTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + tuningDatasetToVertex(fromTrainingDataset, toObject), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["tuningTask", "startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + "tuningTask", + "completeTime", + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["_self"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromMldev(fromTunedModel), + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromVertex(fromTunedModel), + ); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + "supervisedTuningSpec", + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec"], + fromSupervisedTuningSpec, + ); + } + const fromTuningDataStats = getValueByPath(fromObject, ["tuningDataStats"]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, ["encryptionSpec"]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + "partnerModelTuningSpec", + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath( + toObject, + ["partnerModelTuningSpec"], + fromPartnerModelTuningSpec, + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_TUNING_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + return await this.tuneInternal(params); + } else { + const operation = await this.tuneMldevInternal(params); + let tunedModelName = ""; + if ( + operation["metadata"] !== undefined && + operation["metadata"]["tunedModel"] !== undefined + ) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if ( + operation["name"] !== undefined && + operation["name"].includes("/operations/") + ) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createTuningJobParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = "x-goog-api-key"; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error("API key is missing. Please provide a valid API key."); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = "gl-node/"; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error( + `An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`, + ); + } + this.vertexai = + (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + "cross", + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = + GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = + GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.ReplayResponse = ReplayResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs new file mode 100644 index 0000000..58bfae9 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs @@ -0,0 +1,20302 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + baseUrlParams.geminiUrl; + baseUrlParams.vertexUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule {} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ""; + } else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if ( + !value || + (typeof value === "object" && Object.keys(value).length === 0) + ) { + return; + } + if (value === existingData) { + return; + } + if ( + typeof existingData === "object" && + typeof value === "object" && + existingData !== null && + value !== null + ) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === "_self") { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== "object" || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } else { + return undefined; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = + "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = + "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = + "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = + "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** Required. The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = + "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = + "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = + "URL_RETRIEVAL_STATUS_ERROR"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = + "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = + "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = + "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = + "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = + "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = + "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = + "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = + "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse {} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === "object" && obj !== null) { + return ( + "fileData" in obj || + "text" in obj || + "functionCall" in obj || + "functionResponse" in obj || + "inlineData" in obj || + "videoMetadata" in obj || + "codeExecutionResult" in obj || + "executableCode" in obj + ); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === "string") { + parts.push(createPartFromText(partOrString)); + } else if (_isPart(partOrString)) { + parts.push(partOrString); + } else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error("partOrString cannot be an empty array"); + } + for (const part of partOrString) { + if (typeof part === "string") { + parts.push(createPartFromText(part)); + } else if (_isPart(part)) { + parts.push(part); + } else { + throw new Error("element in PartUnion must be a Part object or string"); + } + } + } else { + throw new Error("partOrString must be a Part object, string, or array"); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: "user", + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: "model", + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback {} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata {} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning text from the first one.", + ); + } + let text = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning data from the first one.", + ); + } + let data = ""; + const nonDataParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "inlineData" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning function calls from the first one.", + ); + } + const functionCalls = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.functionCall) + .map((part) => part.functionCall) + .filter((functionCall) => functionCall !== undefined); + if ( + (functionCalls === null || functionCalls === void 0 + ? void 0 + : functionCalls.length) === 0 + ) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning executable code from the first one.", + ); + } + const executableCode = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.executableCode) + .map((part) => part.executableCode) + .filter((executableCode) => executableCode !== undefined); + if ( + (executableCode === null || executableCode === void 0 + ? void 0 + : executableCode.length) === 0 + ) { + return undefined; + } + return (_j = + executableCode === null || executableCode === void 0 + ? void 0 + : executableCode[0]) === null || _j === void 0 + ? void 0 + : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning code execution result from the first one.", + ); + } + const codeExecutionResult = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.codeExecutionResult) + .map((part) => part.codeExecutionResult) + .filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ( + (codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult.length) === 0 + ) { + return undefined; + } + return (_j = + codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult[0]) === null || _j === void 0 + ? void 0 + : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse {} +/** The output images response. */ +class GenerateImagesResponse {} +/** Response for the request to edit an image. */ +class EditImageResponse {} +class UpscaleImageResponse {} +class ListModelsResponse {} +class DeleteModelResponse {} +/** Response for counting tokens. */ +class CountTokensResponse {} +/** Response for computing tokens. */ +class ComputeTokensResponse {} +/** Response with generated videos. */ +class GenerateVideosResponse {} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse {} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse {} +class ListCachedContentsResponse {} +/** Response for the list files method. */ +class ListFilesResponse {} +/** Response for the create file method. */ +class CreateFileResponse {} +/** Response for the delete file method. */ +class DeleteFileResponse {} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse {} +/** Config for batches.list return value. */ +class ListBatchJobsResponse {} +/** Represents a single response in a replay. */ +class ReplayResponse {} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_RAW", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_MASK", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_CONTROL", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_STYLE", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_SUBJECT", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + fieldValue !== null + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse["name"]; + operation.metadata = apiResponse["metadata"]; + operation.done = apiResponse["done"]; + operation.error = apiResponse["error"]; + if (isVertexAI) { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response["videos"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo["gcsUri"], + videoBytes: generatedVideo["bytesBase64Encoded"] + ? tBytes$1(generatedVideo["bytesBase64Encoded"]) + : undefined, + mimeType: generatedVideo["mimeType"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } else { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response["generateVideoResponse"]; + const responseVideos = + generatedVideoResponse === null || generatedVideoResponse === void 0 + ? void 0 + : generatedVideoResponse["generatedSamples"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + const video = generatedVideo["video"]; + return { + video: { + uri: + video === null || video === void 0 + ? void 0 + : video["uri"], + videoBytes: ( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"] + ) + ? tBytes$1( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"], + ) + : undefined, + mimeType: generatedVideo["encoding"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse {} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if ( + this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0 + ) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (apiClient.isVertexAI()) { + if ( + model.startsWith("publishers/") || + model.startsWith("projects/") || + model.startsWith("models/") + ) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error( + `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`, + ); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("image/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("audio/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "parts" in origin && + Array.isArray(origin.parts) + ); +} +function _isFunctionCallPart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionCall" in origin + ); +} +function _isFunctionResponsePart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionResponse" in origin + ); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: "user", + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error( + "To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them", + ); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new 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 (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(Type).includes( + listWithoutNull[0].toUpperCase(), + ) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i of listWithoutNull) { + resultingSchema["anyOf"].push({ + type: Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error( + "type: null can not be the only possible type for the field.", + ); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema["type"] = Object.values(Type).includes( + fieldValue.toUpperCase(), + ) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error( + "multiSpeakerVoiceConfig is not supported in the live API.", + ); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema( + functionDeclaration.parameters, + ); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema( + functionDeclaration.response, + ); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName( + client, + resourceName, + resourcePrefix, + splitsAfterPrefix = 1, +) { + const shouldAppendPrefix = + !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith("projects/")) { + return resourceName; + } else if (resourceName.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName}`; + } else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "name" in origin + ); +} +function isGeneratedVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "video" in origin + ); +} +function isVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "uri" in origin + ); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === undefined) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"], + }; + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [functionDeclaration], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== "string" && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set."); + } else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error("One of `gcsUri` or `bigqueryUri` must be set."); + } + } else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error( + "Only one of `inlinedRequests` or `fileName` can be set.", + ); + } else if (!src.inlinedRequests && !src.fileName) { + throw new Error("One of `inlinedRequests` or `fileName` must be set."); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } else if (typeof src === "string") { + if (src.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: [src], // GCS URI is expected as an array + }; + } else if (src.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: src, + }; + } else if (src.startsWith("files/")) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString, + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString, + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = + /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$4(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$4(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$4(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$4(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$2(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$2(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$4(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev$1(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$2(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev$1(fromThinkingConfig), + ); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath( + toObject, + ["request", "model"], + tModel(apiClient, fromModel), + ); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["request", "generationConfig"], + generateContentConfigToMldev$1(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["format"]) !== undefined) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["bigqueryUri"]) !== undefined) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, ["inlinedRequests"]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject, ["dest"]) !== undefined) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["batch", "inputConfig"], + batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject, ["filter"]) !== undefined) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedRequests"]) !== undefined) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath( + toObject, + ["bigqueryDestination", "outputUri"], + fromBigqueryUri, + ); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedResponses"]) !== undefined) { + throw new Error( + "inlinedResponses parameter is not supported in Vertex AI.", + ); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ["dest"]); + if (parentObject !== undefined && fromDest != null) { + setValueByPath( + parentObject, + ["outputConfig"], + batchJobDestinationToVertex(tBatchJobDestination(fromDest)), + ); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["inputConfig"], + batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev$1(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$2(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateContentResponseFromMldev$1(fromResponse), + ); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + "inlinedResponses", + "inlinedResponses", + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + "metadata", + "displayName", + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["metadata", "createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, ["metadata", "endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["metadata", "updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigquerySource", + "inputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + "gcsDestination", + "outputUriPrefix", + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigqueryDestination", + "outputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["batchPredictionJobs"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = + response === null || response === void 0 + ? void 0 + : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = + (_a = requestParams["config"]) === null || _a === void 0 + ? void 0 + : _a["pageSize"]) !== null && _b !== void 0 + ? _b + : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if ( + ((_a = this.params["config"]) === null || _a === void 0 + ? void 0 + : _a["pageToken"]) !== undefined + ) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error( + "InlinedRequest[] is not supported in Vertex AI. Please use " + + "Google Cloud Storage URI or BigQuery URI instead.", + ); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = "genaiBatchJob_${timestampStr}"; + } + if ( + params.config.dest === undefined && + typeof params.src === "string" + ) { + if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } else if (params.src.startsWith("bq://")) { + params.config.dest = `${params.src}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source:" + params.src); + } + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_BATCH_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$3(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$3(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$3(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$3(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$3(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$1(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["kmsKeyName"]) !== undefined) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$2() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$2(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$2(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$2(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$2(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$2()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex$1(fromToolConfig), + ); + } + const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath( + parentObject, + ["encryption_spec", "kmsKeyName"], + fromKmsKeyName, + ); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_CACHED_CONTENTS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined.", + ); +} + +function __await(v) { + return this instanceof __await ? ((this.v = v), this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = Object.create( + (typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype, + )), + verb("next"), + verb("throw"), + verb("return", awaitReturn), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" ? __values(o) : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ value: v, done: d }); + }, reject); + } +} + +typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = + (_a = response.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (!part.thought && part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === "user") { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === "model") { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history), + ); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = + (_b = + (_a = response.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = + response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && + _c !== void 0 + ? _c + : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory( + inputContent, + modelOutput, + automaticFunctionCallingHistory, + ); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for ( + var _f = true, + streamResponse_1 = __asyncValues(streamResponse), + streamResponse_1_1; + (streamResponse_1_1 = yield __await(streamResponse_1.next())), + (_c = streamResponse_1_1.done), + !_c; + _f = true + ) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = + (_b = + (_a = chunk.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) + yield __await(_d.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }, + ); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if ( + modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined) + ) { + outputContents = modelOutput; + } else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: "model", + parts: [], + }); + } + if ( + automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0 + ) { + this.history.push( + ...extractCuratedHistory(automaticFunctionCallingHistory), + ); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = "Content-Type"; +const SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; +const USER_AGENT_HEADER = "User-Agent"; +const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; +const SDK_VERSION = "1.11.0"; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; +const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { + project: opts.project, + location: opts.location, + apiKey: opts.apiKey, + vertexai: opts.vertexai, + }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 + ? _a + : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 + ? _b + : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions( + initHttpOptions, + opts.httpOptions, + ); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if ( + this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== "global" + ) { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 + ? _a + : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined + ) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error("API version is not set."); + } + getBaseUrl() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined + ) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error("Base URL is not set."); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined + ) { + return this.clientOptions.httpOptions.headers; + } else { + throw new Error("Headers are not set."); + } + } + getRequestUrlInternal(httpOptions) { + if ( + !httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined + ) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== "") { + urlElement.push(path); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if ( + request.httpMethod === "GET" && + request.path.startsWith("publishers/google/models") + ) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error( + "Request body should be empty for GET request, but got non empty request body", + ); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === "object") { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign( + Object.assign({}, patchedHttpOptions[key]), + value, + ); + } else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit( + requestInit, + httpOptions, + abortSignal, + ) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if ( + httpOptions.timeout && + (httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.timeout) > 0 + ) { + const timeoutHandle = setTimeout( + () => abortController.abort(), + httpOptions.timeout, + ); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + const reader = + (_a = + response === null || response === void 0 + ? void 0 + : response.body) === null || _a === void 0 + ? void 0 + : _a.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse( + JSON.stringify(chunkJson["error"]), + ); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } catch (e) { + const error = e; + if (error.name === "ApiError") { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: + response === null || response === void 0 + ? void 0 + : response.headers, + status: + response === null || response === void 0 + ? void 0 + : response.status, + statusText: + response === null || response === void 0 + ? void 0 + : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } catch (e) { + throw new Error( + `exception parsing stream chunk ${processedChunkString}. ${e}`, + ); + } + } + } + } finally { + reader.releaseLock(); + } + }, + ); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = + LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append( + SERVER_TIMEOUT_HEADER, + String(Math.ceil(httpOptions.timeout / 1000)), + ); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = + (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== + null && _a !== void 0 + ? _a + : fileStat.type; + if (mimeType === undefined || mimeType === "") { + throw new Error( + "Can not determine mimeType. Please provide mimeType in the config.", + ); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } else { + httpOptions = { + apiVersion: "", + headers: { + "Content-Type": "application/json", + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`, + "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`, + }, + }; + } + const body = { + file: file, + }; + const httpResponse = await this.request({ + path: formatMap("upload/v1beta/files", body["_url"]), + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions, + }); + if ( + !httpResponse || + !(httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) + ) { + throw new Error( + "Server did not return an HttpResponse or the returned HttpResponse did not have headers.", + ); + } + const uploadUrl = + (_a = + httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) === null || _a === void 0 + ? void 0 + : _a["x-goog-upload-url"]; + if (uploadUrl === undefined) { + throw new Error( + "Failed to get upload url. Server did not return the x-google-upload-url in the headers", + ); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ( + (_a = response.headers.get("content-type")) === null || _a === void 0 + ? void 0 + : _a.includes("application/json") + ) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn( + "includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.", + ); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if ( + typeof parsedBody === "object" && + parsedBody !== null && + !Array.isArray(parsedBody) + ) { + currentBodyObject = parsedBody; + } else { + console.warn( + "includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.", + ); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } catch (e) { + console.warn( + "includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.", + ); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if ( + sourceValue && + typeof sourceValue === "object" && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === "object" && + !Array.isArray(targetValue) + ) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if ( + targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue + ) { + console.warn( + `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`, + ); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function crossError() { + // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports + return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either: + +*Enabling conditional exports for your project [recommended]* + +*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'. +`); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossDownloader { + async download(_params, _apiClient) { + throw crossError(); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; +class CrossUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + throw crossError(); + } else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + async stat(file) { + if (typeof file === "string") { + throw crossError(); + } else { + return getBlobStat(file); + } + } +} +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 ? void 0 : response.headers) === + null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class CrossWebSocketFactory { + create(_url, _headers, _callbacks) { + throw crossError(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listFilesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_FILES, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error( + "Vertex AI does not support uploading files. You can share files through a GCS bucket.", + ); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = listFilesParametersToMldev(params); + path = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createFileParametersToMldev(params); + path = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = getFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = deleteFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$2(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev$1(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev$1(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev$1(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev$1(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev$1(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev$1(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ["setup"]); + if (fromSetup != null) { + setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentToMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + const fromPlaybackControl = getValueByPath(fromObject, ["playbackControl"]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ["playbackControl"], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex$1(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$1(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$1(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$1(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$1(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$1()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ["transparent"]); + if (fromTransparent != null) { + setValueByPath(toObject, ["transparent"], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToVertex(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToVertex(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToVertex$1(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToVertex(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToVertex(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToVertex(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToVertex(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromMldev(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromMldev(fromOutputTranscription), + ); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$1(fromUrlContextMetadata), + ); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "responseTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "responseTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromMldev(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromMldev(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromMldev(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromMldev(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate), + ); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentFromMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, ["sourceMetadata"]); + if (fromSourceMetadata != null) { + setValueByPath( + toObject, + ["sourceMetadata"], + liveMusicSourceMetadataFromMldev(fromSourceMetadata), + ); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ["audioChunks"], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, ["filteredReason"]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ["filteredReason"], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveMusicServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveMusicServerContentFromMldev(fromServerContent), + ); + } + const fromFilteredPrompt = getValueByPath(fromObject, ["filteredPrompt"]); + if (fromFilteredPrompt != null) { + setValueByPath( + toObject, + ["filteredPrompt"], + liveMusicFilteredPromptFromMldev(fromFilteredPrompt), + ); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ["sessionId"]); + if (fromSessionId != null) { + setValueByPath(toObject, ["sessionId"], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromVertex(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromVertex(fromOutputTranscription), + ); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "candidatesTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "candidatesTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromVertex(fromSetupComplete), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromVertex(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromVertex(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromVertex(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromVertex(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath( + toObject, + ["goAway"], + liveServerGoAwayFromVertex(fromGoAway), + ); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$1(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$1(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["requests[]", "outputDimensionality"], + fromOutputDimensionality, + ); + } + if (getValueByPath(fromObject, ["mimeType"]) !== undefined) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["autoTruncate"]) !== undefined) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["requests[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToMldev(fromConfig, toObject), + ); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]); + if (fromModelForEmbedContent !== undefined) { + setValueByPath( + toObject, + ["requests[]", "model"], + tModel(apiClient, fromModelForEmbedContent), + ); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["negativePrompt"]) !== undefined) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + if (getValueByPath(fromObject, ["addWatermark"]) !== undefined) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["imageSize"]) !== undefined) { + throw new Error("imageSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["enhancePrompt"]) !== undefined) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["systemInstruction"]) !== undefined) { + throw new Error( + "systemInstruction parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["tools"]) !== undefined) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["generationConfig"]) !== undefined) { + throw new Error( + "generationConfig parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["fps"]) !== undefined) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + if (getValueByPath(fromObject, ["resolution"]) !== undefined) { + throw new Error("resolution parameter is not supported in Gemini API."); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + if (getValueByPath(fromObject, ["pubsubTopic"]) !== undefined) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + if (getValueByPath(fromObject, ["generateAudio"]) !== undefined) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["lastFrame"]) !== undefined) { + throw new Error("lastFrame parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["compressionQuality"]) !== undefined) { + throw new Error( + "compressionQuality parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToMldev(fromImage), + ); + } + if (getValueByPath(fromObject, ["video"]) !== undefined) { + throw new Error("video parameter is not supported in Gemini API."); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + "featureSelectionPreference", + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath( + toObject, + ["featureSelectionPreference"], + fromFeatureSelectionPreference, + ); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ["method"]); + if (fromMethod != null) { + setValueByPath(toObject, ["method"], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToVertex(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, ["routingConfig"]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + "modelSelectionConfig", + ]); + if (fromModelSelectionConfig != null) { + setValueByPath( + toObject, + ["modelConfig"], + modelSelectionConfigToVertex(fromModelSelectionConfig), + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex(fromToolConfig), + ); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToVertex(tSpeechConfig(fromSpeechConfig)), + ); + } + const fromAudioTimestamp = getValueByPath(fromObject, ["audioTimestamp"]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToVertex(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["parameters", "outputDimensionality"], + fromOutputDimensionality, + ); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath( + parentObject, + ["parameters", "autoTruncate"], + fromAutoTruncate, + ); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["instances[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromImageSize = getValueByPath(fromObject, ["imageSize"]); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath( + parentObject, + ["parameters", "sampleImageSize"], + fromImageSize, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + "segmentationClasses", + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + "enableControlImageComputation", + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath( + toObject, + ["computeControl"], + fromEnableControlImageComputation, + ); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, ["styleDescription"]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ["styleDescription"], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ["subjectType"]); + if (fromSubjectType != null) { + setValueByPath(toObject, ["subjectType"], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + "subjectDescription", + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, ["referenceImage"]); + if (fromReferenceImage != null) { + setValueByPath( + toObject, + ["referenceImage"], + imageToVertex(fromReferenceImage), + ); + } + const fromReferenceId = getValueByPath(fromObject, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, ["referenceType"]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, ["maskImageConfig"]); + if (fromMaskImageConfig != null) { + setValueByPath( + toObject, + ["maskImageConfig"], + maskReferenceConfigToVertex(fromMaskImageConfig), + ); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + "controlImageConfig", + ]); + if (fromControlImageConfig != null) { + setValueByPath( + toObject, + ["controlImageConfig"], + controlReferenceConfigToVertex(fromControlImageConfig), + ); + } + const fromStyleImageConfig = getValueByPath(fromObject, ["styleImageConfig"]); + if (fromStyleImageConfig != null) { + setValueByPath( + toObject, + ["styleImageConfig"], + styleReferenceConfigToVertex(fromStyleImageConfig), + ); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + "subjectImageConfig", + ]); + if (fromSubjectImageConfig != null) { + setValueByPath( + toObject, + ["subjectImageConfig"], + subjectReferenceConfigToVertex(fromSubjectImageConfig), + ); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromEditMode = getValueByPath(fromObject, ["editMode"]); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath( + parentObject, + ["parameters", "editConfig", "baseSteps"], + fromBaseSteps, + ); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, ["referenceImages"]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath( + toObject, + ["instances[0]", "referenceImages"], + transformedList, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + editImageConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + "enhanceInputImage", + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "enhanceInputImage"], + fromEnhanceInputImage, + ); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + "imagePreservationFactor", + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "imagePreservationFactor"], + fromImagePreservationFactor, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromMode = getValueByPath(fromObject, ["mode"]); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromUpscaleFactor = getValueByPath(fromObject, ["upscaleFactor"]); + if (fromUpscaleFactor != null) { + setValueByPath( + toObject, + ["parameters", "upscaleConfig", "upscaleFactor"], + fromUpscaleFactor, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + countTokensConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromFps = getValueByPath(fromObject, ["fps"]); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromResolution = getValueByPath(fromObject, ["resolution"]); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath( + parentObject, + ["parameters", "pubsubTopic"], + fromPubsubTopic, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + const fromGenerateAudio = getValueByPath(fromObject, ["generateAudio"]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath( + parentObject, + ["parameters", "generateAudio"], + fromGenerateAudio, + ); + } + const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath( + parentObject, + ["instances[0]", "lastFrame"], + imageToVertex(fromLastFrame), + ); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + "compressionQuality", + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "compressionQuality"], + fromCompressionQuality, + ); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath( + toObject, + ["instances[0]", "video"], + videoToVertex(fromVideo), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromMldev(fromSafetyAttributes), + ); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromMldev(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromMldev(fromTunedModelInfo), + ); + } + const fromInputTokenLimit = getValueByPath(fromObject, ["inputTokenLimit"]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, ["outputTokenLimit"]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + "supportedGenerationMethods", + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["video", "uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["video", "encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["generatedSamples"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + "response", + "generateVideoResponse", + ]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromMldev(fromResponse), + ); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citations"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromVertex(fromCitationMetadata), + ); + } + const fromFinishMessage = getValueByPath(fromObject, ["finishMessage"]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ["finishMessage"], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromVertex(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ["statistics"]); + if (fromStatistics != null) { + setValueByPath( + toObject, + ["statistics"], + contentEmbeddingStatisticsFromVertex(fromStatistics), + ); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + "billableCharacterCount", + ]); + if (fromBillableCharacterCount != null) { + setValueByPath( + toObject, + ["billableCharacterCount"], + fromBillableCharacterCount, + ); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + "predictions[]", + "embeddings", + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath( + toObject, + ["metadata"], + embedContentMetadataFromVertex(fromMetadata), + ); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromVertex(fromSafetyAttributes), + ); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromVertex(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, ["deployedModelId"]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + "labels", + "google-vertex-llm-tuning-base-model-id", + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromVertex(fromTunedModelInfo), + ); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]); + if (fromTokensInfo != null) { + setValueByPath(toObject, ["tokensInfo"], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromVertex(fromResponse), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = "mcp_used/unknown"; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = + (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 + ? _a + : ""; + headers[GOOGLE_API_CLIENT_HEADER] = ( + existingHeader + ` ${MCP_LABEL}` + ).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return ( + object !== null && + typeof object === "object" && + object instanceof McpCallableTool + ); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for ( + var _d = true, + _e = ((e_1 = void 0), __asyncValues(listAllTools(mcpClient))), + _f; + (_f = await _e.next()), (_a = _f.done), !_a; + _d = true + ) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, + requestOptions, + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return ( + client !== null && + typeof client === "object" && + "listTools" in client && + typeof client.listTools === "function" + ); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error("No MCP clients provided"); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error("Live music is not supported for Vertex AI."); + } + console.warn( + "Live music generation is experimental and may change in future versions.", + ); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap$1(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if ( + !params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0 + ) { + throw new Error( + "Weighted prompts must be set and contain at least one entry.", + ); + } + const setWeightedPromptsParameters = + liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev( + setWeightedPromptsParameters, + ); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = + "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic( + this.apiClient, + this.auth, + this.webSocketFactory, + ); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error( + "The Live module does not support httpOptions at request-level in" + + " LiveConnectConfig yet. Please use the client-level httpOptions" + + " configuration instead.", + ); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const defaultHeaders = this.apiClient.getDefaultHeaders(); + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + setMcpUsageHeader(defaultHeaders); + } + const headers = mapToHeaders(defaultHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if ( + apiKey === null || apiKey === void 0 + ? void 0 + : apiKey.startsWith("auth_tokens/") + ) { + console.warn( + "Warning: Ephemeral token support is experimental and may change in future versions.", + ); + if (apiVersion !== "v1alpha") { + 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.", + ); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onopen) === null || _a === void 0 + ? void 0 + : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if ( + this.apiClient.isVertexAI() && + transformedModel.startsWith("publishers/") + ) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if ( + this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 + ? void 0 + : _c.responseModalities) === undefined + ) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ( + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.generationConfig + ) { + // Raise deprecation warning for 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).", + ); + } + const inputTools = + (_f = + (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== + null && _f !== void 0 + ? _f + : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex( + this.apiClient, + liveConnectParameters, + ); + } else { + clientMessage = liveConnectParametersToMldev( + this.apiClient, + liveConnectParameters, + ); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a) { + throw new Error( + `Failed to parse client content "turns", type: '${typeof params.turns}'`, + ); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if ( + typeof functionResponse !== "object" || + functionResponse === null || + !("name" in functionResponse) || + !("response" in functionResponse) + ) { + throw new Error( + `Could not parse function response, type '${typeof functionResponse}'.`, + ); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign( + Object.assign({}, defaultLiveSendClientContentParamerters), + params, + ); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToVertex(params), + }; + } else { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ( + (_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.disable + ) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = + config === null || config === void 0 ? void 0 : config.tools) !== null && + _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = + (_c = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _c === void 0 + ? void 0 + : _c.maximumRemoteCalls; + if ( + (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0 + ) { + 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:", + maxCalls, + ); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error( + "Automatic function calling with CallableTools and Tools is not yet supported.", + ); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents( + transformedParams.contents, + ); + const maxRemoteCalls = + (_c = + (_b = + (_a = transformedParams.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.tools) !== null && _e !== void 0 + ? _e + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if ( + apiResponse === null || apiResponse === void 0 + ? void 0 + : apiResponse.generatedImages + ) { + for (const generatedImage of apiResponse.generatedImages) { + if ( + generatedImage && + (generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) && + ((_a = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) === null || _a === void 0 + ? void 0 + : _a.contentType) === "Positive Prompt" + ) { + positivePromptSafetyAttributes = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign( + Object.assign({}, defaultConfig), + params === null || params === void 0 ? void 0 : params.config, + ); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ( + (_a = actualParams.config) === null || _a === void 0 + ? void 0 + : _a.filter + ) { + throw new Error( + "Filtering tuned models list for Vertex AI is not currently supported", + ); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager( + PagedItem.PAGED_ITEM_MODELS, + (x) => this.listInternal(x), + await this.listInternal(actualParams), + actualParams, + ); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => + img.toReferenceImageAPI(), + ); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale", + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all( + tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + }), + ); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { + tools: transformedTools, + }), + }; + newParams.config.tools = transformedTools; + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + const headers = + (_c = + (_b = params.config.httpOptions) === null || _b === void 0 + ? void 0 + : _b.headers) !== null && _c !== void 0 + ? _c + : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign( + Object.assign({}, params.config.httpOptions), + { headers: newHeaders }, + ); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== + null && _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = + toolDeclaration.functionDeclarations) !== null && _c !== void 0 + ? _c + : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error( + `Duplicate tool declaration name: ${declaration.name}`, + ); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = + (_c = + (_b = + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await( + models.processParamsMaybeAddMcpUsage(params), + ); + const response = yield __await( + models.generateContentStreamInternal(transformedParams), + ); + const functionResponses = []; + const responseContents = []; + try { + for ( + var _f = true, + response_1 = ((e_1 = void 0), __asyncValues(response)), + response_1_1; + (response_1_1 = yield __await(response_1.next())), + (_c = response_1_1.done), + !_c; + _f = true + ) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if ( + chunk.candidates && + ((_a = chunk.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content) + ) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== + null && _b !== void 0 + ? _b + : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error( + "Function call name was not returned by the model.", + ); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error( + `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`, + ); + } else { + const responseParts = yield __await( + afcTools + .get(part.functionCall.name) + .callTool([part.functionCall]), + ); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = response_1.return)) + yield __await(_d.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat( + newContents, + ); + params.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for ( + var _d = true, + apiResponse_1 = __asyncValues(apiResponse), + apiResponse_1_1; + (apiResponse_1_1 = yield __await(apiResponse_1.next())), + (_a = apiResponse_1_1.done), + !_a; + _d = true + ) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) + yield __await(_b.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for ( + var _d = true, + apiResponse_2 = __asyncValues(apiResponse), + apiResponse_2_1; + (apiResponse_2_1 = yield __await(apiResponse_2.next())), + (_a = apiResponse_2_1.done), + !_a; + _d = true + ) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) + yield __await(_b.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex( + this.apiClient, + params, + ); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev(fromProactivity), + ); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + "newSessionExpireTime", + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath( + parentObject, + ["newSessionExpireTime"], + fromNewSessionExpireTime, + ); + } + const fromUses = getValueByPath(fromObject, ["uses"]); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + "liveConnectConstraints", + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath( + parentObject, + ["bidiGenerateContentSetup"], + liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints), + ); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + "lockAdditionalFields", + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createAuthTokenConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if ( + typeof value === "object" && + value != null && + Object.keys(value).length > 0 + ) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); // 1st layer + } + } + } + return fields.join(","); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if ( + typeof bidiGenerateContentSetupValue === "object" && + bidiGenerateContentSetupValue !== null && + "setup" in bidiGenerateContentSetupValue + ) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + // Valid inner setup found. + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if ( + Array.isArray( + config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields, + ) && + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields.length) === 0 + ) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; // If mask is empty, effectively no + // specific fields locked by bidi + } + } else if ( + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig", + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict["fieldMask"]; + } + } else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict["fieldMask"]; + } + } else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if ( + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "The client.tokens.create method is only supported by the Gemini Developer API.", + ); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ["textInput"]); + if (fromTextInput != null) { + setValueByPath(toObject, ["textInput"], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ["output"]); + if (fromOutput != null) { + setValueByPath(toObject, ["output"], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== undefined) { + throw new Error( + "vertexDatasetResource parameter is not supported in Gemini API.", + ); + } + const fromExamples = getValueByPath(fromObject, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["validationDataset"]) !== undefined) { + throw new Error( + "validationDataset parameter is not supported in Gemini API.", + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ["description"]) !== undefined) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath( + toObject, + ["tuningTask", "hyperparameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== undefined) { + throw new Error( + "exportLastCheckpointOnly parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["adapterSize"]) !== undefined) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject, ["batchSize"]); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "batchSize"], + fromBatchSize, + ); + } + const fromLearningRate = getValueByPath(fromObject, ["learningRate"]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "learningRate"], + fromLearningRate, + ); + } + return toObject; +} +function createTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["tuningTask", "trainingData"], + tuningDatasetToMldev(fromTrainingDataset), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromGcsUri, + ); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + if (getValueByPath(fromObject, ["examples"]) !== undefined) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + "validationDataset", + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec"], + tuningValidationDatasetToVertex(fromValidationDataset, toObject), + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath( + parentObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + "exportLastCheckpointOnly", + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "exportLastCheckpointOnly"], + fromExportLastCheckpointOnly, + ); + } + const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "adapterSize"], + fromAdapterSize, + ); + } + if (getValueByPath(fromObject, ["batchSize"]) !== undefined) { + throw new Error("batchSize parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["learningRate"]) !== undefined) { + throw new Error("learningRate parameter is not supported in Vertex AI."); + } + return toObject; +} +function createTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + tuningDatasetToVertex(fromTrainingDataset, toObject), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["tuningTask", "startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + "tuningTask", + "completeTime", + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["_self"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromMldev(fromTunedModel), + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromVertex(fromTunedModel), + ); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + "supervisedTuningSpec", + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec"], + fromSupervisedTuningSpec, + ); + } + const fromTuningDataStats = getValueByPath(fromObject, ["tuningDataStats"]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, ["encryptionSpec"]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + "partnerModelTuningSpec", + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath( + toObject, + ["partnerModelTuningSpec"], + fromPartnerModelTuningSpec, + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_TUNING_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + return await this.tuneInternal(params); + } else { + const operation = await this.tuneMldevInternal(params); + let tunedModelName = ""; + if ( + operation["metadata"] !== undefined && + operation["metadata"]["tunedModel"] !== undefined + ) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if ( + operation["name"] !== undefined && + operation["name"].includes("/operations/") + ) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createTuningJobParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = "x-goog-api-key"; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error("API key is missing. Please provide a valid API key."); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = "gl-node/"; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} + * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set, + * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error( + `An API Key must be set when running in an unspecified environment.\n + ${crossError().message}`, + ); + } + this.vertexai = + (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + "cross", + uploader: new CrossUploader(), + downloader: new CrossDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory()); + this.chats = new Chats(this.models, this.apiClient); + this.batches = new Batches(this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { + ActivityHandling, + AdapterSize, + ApiError, + ApiSpec, + AuthType, + Batches, + Behavior, + BlockedReason, + Caches, + Chat, + Chats, + ComputeTokensResponse, + ControlReferenceImage, + ControlReferenceType, + CountTokensResponse, + CreateFileResponse, + DeleteCachedContentResponse, + DeleteFileResponse, + DeleteModelResponse, + DynamicRetrievalConfigMode, + EditImageResponse, + EditMode, + EmbedContentResponse, + EndSensitivity, + Environment, + FeatureSelectionPreference, + FileSource, + FileState, + Files, + FinishReason, + FunctionCallingConfigMode, + FunctionResponse, + FunctionResponseScheduling, + GenerateContentResponse, + GenerateContentResponsePromptFeedback, + GenerateContentResponseUsageMetadata, + GenerateImagesResponse, + GenerateVideosOperation, + GenerateVideosResponse, + GoogleGenAI, + HarmBlockMethod, + HarmBlockThreshold, + HarmCategory, + HarmProbability, + HarmSeverity, + HttpResponse, + ImagePromptLanguage, + InlinedResponse, + JobState, + Language, + ListBatchJobsResponse, + ListCachedContentsResponse, + ListFilesResponse, + ListModelsResponse, + ListTuningJobsResponse, + Live, + LiveClientToolResponse, + LiveMusicPlaybackControl, + LiveMusicServerMessage, + LiveSendToolResponseParameters, + LiveServerMessage, + MaskReferenceImage, + MaskReferenceMode, + MediaModality, + MediaResolution, + Modality, + Mode, + Models, + Operations, + Outcome, + PagedItem, + Pager, + PersonGeneration, + RawReferenceImage, + ReplayResponse, + SafetyFilterLevel, + Scale, + Session, + StartSensitivity, + StyleReferenceImage, + SubjectReferenceImage, + SubjectReferenceType, + Tokens, + TrafficType, + TurnCoverage, + Type, + UpscaleImageResponse, + UrlRetrievalStatus, + VideoCompressionQuality, + createModelContent, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromText, + createPartFromUri, + createUserContent, + mcpToTool, + setDefaultBaseUrls, +}; +//# sourceMappingURL=index.mjs.map diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs.map b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs.map new file mode 100644 index 0000000..bd41eb9 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../src/_base_url.ts","../src/_common.ts","../src/_base_transformers.ts","../src/types.ts","../src/_transformers.ts","../src/converters/_batches_converters.ts","../src/pagers.ts","../src/batches.ts","../src/converters/_caches_converters.ts","../src/caches.ts","../src/chats.ts","../src/errors.ts","../src/_api_client.ts","../src/cross/_cross_error.ts","../src/cross/_cross_downloader.ts","../src/cross/_cross_uploader.ts","../src/cross/_cross_websocket.ts","../src/converters/_files_converters.ts","../src/files.ts","../src/converters/_live_converters.ts","../src/converters/_models_converters.ts","../src/mcp/_mcp.ts","../src/music.ts","../src/live.ts","../src/_afc.ts","../src/models.ts","../src/converters/_operations_converters.ts","../src/operations.ts","../src/converters/_tokens_converters.ts","../src/tokens.ts","../src/converters/_tunings_converters.ts","../src/tunings.ts","../src/web/_web_auth.ts","../src/client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** Required. The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */\n data?: Part[];\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Computer Use tool type. */\nexport declare interface ToolComputerUse {\n /** A list of predefined functions that the should not be prepopulated. */\n excludedPredefinedFunctions?: string[];\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** \n Tool to support the model interacting directly with the computer.\n If enabled, it automatically populates computer-use specific Function\n Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** Hyperparameters for Distillation. */\nexport declare interface DistillationHyperParameters {\n /** Optional. Adapter size for distillation. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Distillation. */\nexport declare interface DistillationSpec {\n /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseTeacherModel?: string;\n /** Optional. Hyperparameters for Distillation. */\n hyperParameters?: DistillationHyperParameters;\n /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */\n pipelineRootDirectory?: string;\n /** The student model that is being tuned, e.g., \"google/gemma-2b-1.1-it\". Deprecated. Use base_model instead. */\n studentModel?: string;\n /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */\n tunedTeacherModelSource?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Tuning Spec for Distillation. */\n distillationSpec?: DistillationSpec;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** Output only. Reserved for future use. */\n satisfiesPzi?: boolean;\n /** Output only. Reserved for future use. */\n satisfiesPzs?: boolean;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-1.0-pro-002\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (!part.thought && part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.11.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function crossError(): Error {\n // TODO(b/399934880): this message needs a link to a help page explaining how to enable conditional exports\n return new Error(`This feature requires the web or Node specific @google/genai implementation, you can fix this by either:\n\n*Enabling conditional exports for your project [recommended]*\n\n*Using a platform specific import* - Make sure your code imports either '@google/genai/web' or '@google/genai/node' instead of '@google/genai'.\n`);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport class CrossDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\nimport {crossError} from './_cross_error.js';\n\nexport class CrossWebSocketFactory implements WebSocketFactory {\n create(\n _url: string,\n _headers: Record,\n _callbacks: WebSocketCallbacks,\n ): Ws {\n throw crossError();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['data']) !== undefined) {\n throw new Error('data parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['imageSize']) !== undefined) {\n throw new Error('imageSize parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const defaultHeaders = this.apiClient.getDefaultHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(defaultHeaders);\n }\n const headers = mapToHeaders(defaultHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"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.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n '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).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToMldev(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToVertex(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n return await this.tuneInternal(params);\n } else {\n const operation = await this.tuneMldevInternal(params);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from './_api_client.js';\nimport {Batches} from './batches.js';\nimport {Caches} from './caches.js';\nimport {Chats} from './chats.js';\nimport {CrossDownloader} from './cross/_cross_downloader.js';\nimport {crossError} from './cross/_cross_error.js';\nimport {CrossUploader} from './cross/_cross_uploader.js';\nimport {CrossWebSocketFactory} from './cross/_cross_websocket.js';\nimport {Files} from './files.js';\nimport {Live} from './live.js';\nimport {Models} from './models.js';\nimport {Operations} from './operations.js';\nimport {Tokens} from './tokens.js';\nimport {Tunings} from './tunings.js';\nimport {HttpOptions} from './types.js';\nimport {WebAuth} from './web/_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * Google Gen AI SDK's configuration options.\n *\n * See {@link GoogleGenAI} for usage samples.\n */\nexport interface GoogleGenAIOptions {\n /**\n * Optional. Determines whether to use the Vertex AI or the Gemini API.\n *\n * @remarks\n * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used.\n * When false, the {@link https://ai.google.dev/api | Gemini API} will be used.\n *\n * If unset, default SDK behavior is to use the Gemini API service.\n */\n vertexai?: boolean;\n /**\n * Optional. The Google Cloud project ID for Vertex AI clients.\n *\n * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients.\n *\n * @remarks\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n location?: string;\n /**\n * The API Key, required for Gemini API clients.\n *\n * @remarks\n * Required on browser runtimes.\n */\n apiKey?: string;\n /**\n * Optional. The API version to use.\n *\n * @remarks\n * If unset, the default API version will be used.\n */\n apiVersion?: string;\n /**\n * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients.\n *\n * @remarks\n * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}.\n *\n * Only supported on Node runtimes, ignored on browser runtimes.\n *\n */\n googleAuthOptions?: GoogleAuthOptions;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n}\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API}\n * or the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be set,\n * when using Vertex AI {@link GoogleGenAIOptions.project} and {@link GoogleGenAIOptions.location} must also be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error(\n `An API Key must be set when running in an unspecified environment.\\n + ${crossError().message}`,\n );\n }\n this.vertexai = options.vertexai ?? false;\n this.apiKey = options.apiKey;\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'cross',\n uploader: new CrossUploader(),\n downloader: new CrossDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new CrossWebSocketFactory());\n this.chats = new Chats(this.models, this.apiClient);\n this.batches = new Batches(this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToVertex","common.formatMap","converters.batchJobFromVertex","converters.createBatchJobParametersToMldev","converters.batchJobFromMldev","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersToVertex","converters.createTuningJobParametersToMldev","converters.tuningOperationFromMldev"],"mappings":"AAAA;;;;AAIG;AAeH;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAwB,aAAa,CAAC,SAAS;AAC/C,IAAwB,aAAa,CAAC,SAAS;AACjD;;AC1CA;;;;AAIG;MAEU,UAAU,CAAA;AAAG;AAEV,SAAA,SAAS,CACvB,cAAsB,EACtB,QAAiC,EAAA;;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AAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;QAC1C,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;QAChD,IAAI,CAAC,UAAU,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC5C,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.cjs b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.cjs new file mode 100644 index 0000000..474e2dd --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.cjs @@ -0,0 +1,20797 @@ +"use strict"; + +var googleAuthLibrary = require("google-auth-library"); +var fs = require("fs"); +var node_stream = require("node:stream"); +var NodeWs = require("ws"); +var fs$1 = require("fs/promises"); + +function _interopNamespaceDefault(e) { + var n = Object.create(null); + if (e) { + Object.keys(e).forEach(function (k) { + if (k !== "default") { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty( + n, + k, + d.get + ? d + : { + enumerable: true, + get: function () { + return e[k]; + }, + }, + ); + } + }); + } + n.default = e; + return Object.freeze(n); +} + +var NodeWs__namespace = /*#__PURE__*/ _interopNamespaceDefault(NodeWs); +var fs__namespace = /*#__PURE__*/ _interopNamespaceDefault(fs$1); + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl( + httpOptions, + vertexai, + vertexBaseUrlFromEnv, + geminiBaseUrlFromEnv, +) { + var _a, _b; + if ( + !(httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.baseUrl) + ) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 + ? _a + : vertexBaseUrlFromEnv; + } else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 + ? _b + : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule {} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ""; + } else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if ( + !value || + (typeof value === "object" && Object.keys(value).length === 0) + ) { + return; + } + if (value === existingData) { + return; + } + if ( + typeof existingData === "object" && + typeof value === "object" && + existingData !== null && + value !== null + ) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === "_self") { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== "object" || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } else { + return undefined; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +exports.Outcome = void 0; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(exports.Outcome || (exports.Outcome = {})); +/** Required. Programming language of the `code`. */ +exports.Language = void 0; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(exports.Language || (exports.Language = {})); +/** Optional. The type of the data. */ +exports.Type = void 0; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(exports.Type || (exports.Type = {})); +/** Required. Harm category. */ +exports.HarmCategory = void 0; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = + "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = + "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(exports.HarmCategory || (exports.HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +exports.HarmBlockMethod = void 0; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = + "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(exports.HarmBlockMethod || (exports.HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +exports.HarmBlockThreshold = void 0; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = + "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(exports.HarmBlockThreshold || (exports.HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +exports.Mode = void 0; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(exports.Mode || (exports.Mode = {})); +/** Type of auth scheme. */ +exports.AuthType = void 0; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(exports.AuthType || (exports.AuthType = {})); +/** Required. The environment being operated. */ +exports.Environment = void 0; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(exports.Environment || (exports.Environment = {})); +/** The API spec that the external API implements. */ +exports.ApiSpec = void 0; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(exports.ApiSpec || (exports.ApiSpec = {})); +/** Status of the url retrieval. */ +exports.UrlRetrievalStatus = void 0; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = + "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = + "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = + "URL_RETRIEVAL_STATUS_ERROR"; +})(exports.UrlRetrievalStatus || (exports.UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +exports.FinishReason = void 0; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(exports.FinishReason || (exports.FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +exports.HarmProbability = void 0; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = + "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(exports.HarmProbability || (exports.HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +exports.HarmSeverity = void 0; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(exports.HarmSeverity || (exports.HarmSeverity = {})); +/** Output only. Blocked reason. */ +exports.BlockedReason = void 0; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(exports.BlockedReason || (exports.BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +exports.TrafficType = void 0; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(exports.TrafficType || (exports.TrafficType = {})); +/** Server content modalities. */ +exports.Modality = void 0; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(exports.Modality || (exports.Modality = {})); +/** The media resolution to use. */ +exports.MediaResolution = void 0; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = + "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(exports.MediaResolution || (exports.MediaResolution = {})); +/** Job state. */ +exports.JobState = void 0; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(exports.JobState || (exports.JobState = {})); +/** Optional. Adapter size for tuning. */ +exports.AdapterSize = void 0; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(exports.AdapterSize || (exports.AdapterSize = {})); +/** Options for feature selection preference. */ +exports.FeatureSelectionPreference = void 0; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = + "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})( + exports.FeatureSelectionPreference || + (exports.FeatureSelectionPreference = {}), +); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +exports.Behavior = void 0; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(exports.Behavior || (exports.Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +exports.DynamicRetrievalConfigMode = void 0; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})( + exports.DynamicRetrievalConfigMode || + (exports.DynamicRetrievalConfigMode = {}), +); +/** Config for the function calling config mode. */ +exports.FunctionCallingConfigMode = void 0; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})( + exports.FunctionCallingConfigMode || (exports.FunctionCallingConfigMode = {}), +); +/** Enum that controls the safety filter level for objectionable content. */ +exports.SafetyFilterLevel = void 0; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(exports.SafetyFilterLevel || (exports.SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +exports.PersonGeneration = void 0; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(exports.PersonGeneration || (exports.PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +exports.ImagePromptLanguage = void 0; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(exports.ImagePromptLanguage || (exports.ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +exports.MaskReferenceMode = void 0; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(exports.MaskReferenceMode || (exports.MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +exports.ControlReferenceType = void 0; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(exports.ControlReferenceType || (exports.ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +exports.SubjectReferenceType = void 0; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(exports.SubjectReferenceType || (exports.SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +exports.EditMode = void 0; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(exports.EditMode || (exports.EditMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +exports.VideoCompressionQuality = void 0; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(exports.VideoCompressionQuality || (exports.VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +exports.FileState = void 0; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(exports.FileState || (exports.FileState = {})); +/** Source of the File. */ +exports.FileSource = void 0; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(exports.FileSource || (exports.FileSource = {})); +/** Server content modalities. */ +exports.MediaModality = void 0; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(exports.MediaModality || (exports.MediaModality = {})); +/** Start of speech sensitivity. */ +exports.StartSensitivity = void 0; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = + "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(exports.StartSensitivity || (exports.StartSensitivity = {})); +/** End of speech sensitivity. */ +exports.EndSensitivity = void 0; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(exports.EndSensitivity || (exports.EndSensitivity = {})); +/** The different ways of handling user activity. */ +exports.ActivityHandling = void 0; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = + "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = + "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(exports.ActivityHandling || (exports.ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +exports.TurnCoverage = void 0; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(exports.TurnCoverage || (exports.TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +exports.FunctionResponseScheduling = void 0; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = + "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})( + exports.FunctionResponseScheduling || + (exports.FunctionResponseScheduling = {}), +); +/** Scale of the generated music. */ +exports.Scale = void 0; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(exports.Scale || (exports.Scale = {})); +/** The playback control signal to apply to the music generation. */ +exports.LiveMusicPlaybackControl = void 0; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = + "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(exports.LiveMusicPlaybackControl || (exports.LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse {} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === "object" && obj !== null) { + return ( + "fileData" in obj || + "text" in obj || + "functionCall" in obj || + "functionResponse" in obj || + "inlineData" in obj || + "videoMetadata" in obj || + "codeExecutionResult" in obj || + "executableCode" in obj + ); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === "string") { + parts.push(createPartFromText(partOrString)); + } else if (_isPart(partOrString)) { + parts.push(partOrString); + } else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error("partOrString cannot be an empty array"); + } + for (const part of partOrString) { + if (typeof part === "string") { + parts.push(createPartFromText(part)); + } else if (_isPart(part)) { + parts.push(part); + } else { + throw new Error("element in PartUnion must be a Part object or string"); + } + } + } else { + throw new Error("partOrString must be a Part object, string, or array"); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: "user", + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: "model", + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback {} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata {} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning text from the first one.", + ); + } + let text = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning data from the first one.", + ); + } + let data = ""; + const nonDataParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "inlineData" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning function calls from the first one.", + ); + } + const functionCalls = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.functionCall) + .map((part) => part.functionCall) + .filter((functionCall) => functionCall !== undefined); + if ( + (functionCalls === null || functionCalls === void 0 + ? void 0 + : functionCalls.length) === 0 + ) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning executable code from the first one.", + ); + } + const executableCode = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.executableCode) + .map((part) => part.executableCode) + .filter((executableCode) => executableCode !== undefined); + if ( + (executableCode === null || executableCode === void 0 + ? void 0 + : executableCode.length) === 0 + ) { + return undefined; + } + return (_j = + executableCode === null || executableCode === void 0 + ? void 0 + : executableCode[0]) === null || _j === void 0 + ? void 0 + : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning code execution result from the first one.", + ); + } + const codeExecutionResult = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.codeExecutionResult) + .map((part) => part.codeExecutionResult) + .filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ( + (codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult.length) === 0 + ) { + return undefined; + } + return (_j = + codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult[0]) === null || _j === void 0 + ? void 0 + : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse {} +/** The output images response. */ +class GenerateImagesResponse {} +/** Response for the request to edit an image. */ +class EditImageResponse {} +class UpscaleImageResponse {} +class ListModelsResponse {} +class DeleteModelResponse {} +/** Response for counting tokens. */ +class CountTokensResponse {} +/** Response for computing tokens. */ +class ComputeTokensResponse {} +/** Response with generated videos. */ +class GenerateVideosResponse {} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse {} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse {} +class ListCachedContentsResponse {} +/** Response for the list files method. */ +class ListFilesResponse {} +/** Response for the create file method. */ +class CreateFileResponse {} +/** Response for the delete file method. */ +class DeleteFileResponse {} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse {} +/** Config for batches.list return value. */ +class ListBatchJobsResponse {} +/** Represents a single response in a replay. */ +class ReplayResponse {} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_RAW", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_MASK", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_CONTROL", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_STYLE", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_SUBJECT", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + fieldValue !== null + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse["name"]; + operation.metadata = apiResponse["metadata"]; + operation.done = apiResponse["done"]; + operation.error = apiResponse["error"]; + if (isVertexAI) { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response["videos"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo["gcsUri"], + videoBytes: generatedVideo["bytesBase64Encoded"] + ? tBytes$1(generatedVideo["bytesBase64Encoded"]) + : undefined, + mimeType: generatedVideo["mimeType"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } else { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response["generateVideoResponse"]; + const responseVideos = + generatedVideoResponse === null || generatedVideoResponse === void 0 + ? void 0 + : generatedVideoResponse["generatedSamples"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + const video = generatedVideo["video"]; + return { + video: { + uri: + video === null || video === void 0 + ? void 0 + : video["uri"], + videoBytes: ( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"] + ) + ? tBytes$1( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"], + ) + : undefined, + mimeType: generatedVideo["encoding"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse {} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if ( + this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0 + ) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (apiClient.isVertexAI()) { + if ( + model.startsWith("publishers/") || + model.startsWith("projects/") || + model.startsWith("models/") + ) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error( + `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`, + ); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("image/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("audio/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "parts" in origin && + Array.isArray(origin.parts) + ); +} +function _isFunctionCallPart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionCall" in origin + ); +} +function _isFunctionResponsePart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionResponse" in origin + ); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: "user", + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error( + "To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them", + ); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new 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 (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(exports.Type).includes( + listWithoutNull[0].toUpperCase(), + ) + ? listWithoutNull[0].toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i of listWithoutNull) { + resultingSchema["anyOf"].push({ + type: Object.values(exports.Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error( + "type: null can not be the only possible type for the field.", + ); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema["type"] = Object.values(exports.Type).includes( + fieldValue.toUpperCase(), + ) + ? fieldValue.toUpperCase() + : exports.Type.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error( + "multiSpeakerVoiceConfig is not supported in the live API.", + ); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema( + functionDeclaration.parameters, + ); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema( + functionDeclaration.response, + ); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName( + client, + resourceName, + resourcePrefix, + splitsAfterPrefix = 1, +) { + const shouldAppendPrefix = + !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith("projects/")) { + return resourceName; + } else if (resourceName.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName}`; + } else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "name" in origin + ); +} +function isGeneratedVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "video" in origin + ); +} +function isVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "uri" in origin + ); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === undefined) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"], + }; + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [functionDeclaration], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== "string" && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set."); + } else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error("One of `gcsUri` or `bigqueryUri` must be set."); + } + } else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error( + "Only one of `inlinedRequests` or `fileName` can be set.", + ); + } else if (!src.inlinedRequests && !src.fileName) { + throw new Error("One of `inlinedRequests` or `fileName` must be set."); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } else if (typeof src === "string") { + if (src.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: [src], // GCS URI is expected as an array + }; + } else if (src.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: src, + }; + } else if (src.startsWith("files/")) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString, + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString, + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = + /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$4(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$4(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$4(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$4(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$2(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$2(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$4(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev$1(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$2(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev$1(fromThinkingConfig), + ); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath( + toObject, + ["request", "model"], + tModel(apiClient, fromModel), + ); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["request", "generationConfig"], + generateContentConfigToMldev$1(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["format"]) !== undefined) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["bigqueryUri"]) !== undefined) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, ["inlinedRequests"]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject, ["dest"]) !== undefined) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["batch", "inputConfig"], + batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject, ["filter"]) !== undefined) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedRequests"]) !== undefined) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath( + toObject, + ["bigqueryDestination", "outputUri"], + fromBigqueryUri, + ); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedResponses"]) !== undefined) { + throw new Error( + "inlinedResponses parameter is not supported in Vertex AI.", + ); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ["dest"]); + if (parentObject !== undefined && fromDest != null) { + setValueByPath( + parentObject, + ["outputConfig"], + batchJobDestinationToVertex(tBatchJobDestination(fromDest)), + ); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["inputConfig"], + batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev$1(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$2(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateContentResponseFromMldev$1(fromResponse), + ); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + "inlinedResponses", + "inlinedResponses", + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + "metadata", + "displayName", + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["metadata", "createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, ["metadata", "endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["metadata", "updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigquerySource", + "inputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + "gcsDestination", + "outputUriPrefix", + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigqueryDestination", + "outputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["batchPredictionJobs"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +exports.PagedItem = void 0; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(exports.PagedItem || (exports.PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = + response === null || response === void 0 + ? void 0 + : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = + (_a = requestParams["config"]) === null || _a === void 0 + ? void 0 + : _a["pageSize"]) !== null && _b !== void 0 + ? _b + : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if ( + ((_a = this.params["config"]) === null || _a === void 0 + ? void 0 + : _a["pageToken"]) !== undefined + ) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error( + "InlinedRequest[] is not supported in Vertex AI. Please use " + + "Google Cloud Storage URI or BigQuery URI instead.", + ); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = "genaiBatchJob_${timestampStr}"; + } + if ( + params.config.dest === undefined && + typeof params.src === "string" + ) { + if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } else if (params.src.startsWith("bq://")) { + params.config.dest = `${params.src}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source:" + params.src); + } + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_BATCH_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$3(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$3(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$3(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$3(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$3(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$1(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["kmsKeyName"]) !== undefined) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$2() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$2(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$2(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$2(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$2(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$2()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex$1(fromToolConfig), + ); + } + const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath( + parentObject, + ["encryption_spec", "kmsKeyName"], + fromKmsKeyName, + ); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_CACHED_CONTENTS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined.", + ); +} + +function __await(v) { + return this instanceof __await ? ((this.v = v), this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = Object.create( + (typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype, + )), + verb("next"), + verb("throw"), + verb("return", awaitReturn), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" ? __values(o) : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ value: v, done: d }); + }, reject); + } +} + +typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = + (_a = response.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (!part.thought && part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === "user") { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === "model") { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history), + ); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = + (_b = + (_a = response.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = + response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && + _c !== void 0 + ? _c + : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory( + inputContent, + modelOutput, + automaticFunctionCallingHistory, + ); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for ( + var _f = true, + streamResponse_1 = __asyncValues(streamResponse), + streamResponse_1_1; + (streamResponse_1_1 = yield __await(streamResponse_1.next())), + (_c = streamResponse_1_1.done), + !_c; + _f = true + ) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = + (_b = + (_a = chunk.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) + yield __await(_d.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }, + ); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if ( + modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined) + ) { + outputContents = modelOutput; + } else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: "model", + parts: [], + }); + } + if ( + automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0 + ) { + this.history.push( + ...extractCuratedHistory(automaticFunctionCallingHistory), + ); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listFilesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_FILES, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error( + "Vertex AI does not support uploading files. You can share files through a GCS bucket.", + ); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = listFilesParametersToMldev(params); + path = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createFileParametersToMldev(params); + path = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = getFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = deleteFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$2(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev$1(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev$1(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev$1(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev$1(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev$1(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev$1(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ["setup"]); + if (fromSetup != null) { + setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentToMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + const fromPlaybackControl = getValueByPath(fromObject, ["playbackControl"]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ["playbackControl"], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex$1(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$1(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$1(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$1(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$1(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$1()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ["transparent"]); + if (fromTransparent != null) { + setValueByPath(toObject, ["transparent"], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToVertex(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToVertex(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToVertex$1(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToVertex(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToVertex(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToVertex(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToVertex(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromMldev(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromMldev(fromOutputTranscription), + ); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$1(fromUrlContextMetadata), + ); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "responseTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "responseTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromMldev(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromMldev(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromMldev(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromMldev(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate), + ); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentFromMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, ["sourceMetadata"]); + if (fromSourceMetadata != null) { + setValueByPath( + toObject, + ["sourceMetadata"], + liveMusicSourceMetadataFromMldev(fromSourceMetadata), + ); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ["audioChunks"], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, ["filteredReason"]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ["filteredReason"], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveMusicServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveMusicServerContentFromMldev(fromServerContent), + ); + } + const fromFilteredPrompt = getValueByPath(fromObject, ["filteredPrompt"]); + if (fromFilteredPrompt != null) { + setValueByPath( + toObject, + ["filteredPrompt"], + liveMusicFilteredPromptFromMldev(fromFilteredPrompt), + ); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ["sessionId"]); + if (fromSessionId != null) { + setValueByPath(toObject, ["sessionId"], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromVertex(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromVertex(fromOutputTranscription), + ); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "candidatesTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "candidatesTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromVertex(fromSetupComplete), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromVertex(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromVertex(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromVertex(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromVertex(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath( + toObject, + ["goAway"], + liveServerGoAwayFromVertex(fromGoAway), + ); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$1(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$1(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["requests[]", "outputDimensionality"], + fromOutputDimensionality, + ); + } + if (getValueByPath(fromObject, ["mimeType"]) !== undefined) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["autoTruncate"]) !== undefined) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["requests[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToMldev(fromConfig, toObject), + ); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]); + if (fromModelForEmbedContent !== undefined) { + setValueByPath( + toObject, + ["requests[]", "model"], + tModel(apiClient, fromModelForEmbedContent), + ); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["negativePrompt"]) !== undefined) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + if (getValueByPath(fromObject, ["addWatermark"]) !== undefined) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["imageSize"]) !== undefined) { + throw new Error("imageSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["enhancePrompt"]) !== undefined) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["systemInstruction"]) !== undefined) { + throw new Error( + "systemInstruction parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["tools"]) !== undefined) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["generationConfig"]) !== undefined) { + throw new Error( + "generationConfig parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["fps"]) !== undefined) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + if (getValueByPath(fromObject, ["resolution"]) !== undefined) { + throw new Error("resolution parameter is not supported in Gemini API."); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + if (getValueByPath(fromObject, ["pubsubTopic"]) !== undefined) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + if (getValueByPath(fromObject, ["generateAudio"]) !== undefined) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["lastFrame"]) !== undefined) { + throw new Error("lastFrame parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["compressionQuality"]) !== undefined) { + throw new Error( + "compressionQuality parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToMldev(fromImage), + ); + } + if (getValueByPath(fromObject, ["video"]) !== undefined) { + throw new Error("video parameter is not supported in Gemini API."); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + "featureSelectionPreference", + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath( + toObject, + ["featureSelectionPreference"], + fromFeatureSelectionPreference, + ); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ["method"]); + if (fromMethod != null) { + setValueByPath(toObject, ["method"], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToVertex(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, ["routingConfig"]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + "modelSelectionConfig", + ]); + if (fromModelSelectionConfig != null) { + setValueByPath( + toObject, + ["modelConfig"], + modelSelectionConfigToVertex(fromModelSelectionConfig), + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex(fromToolConfig), + ); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToVertex(tSpeechConfig(fromSpeechConfig)), + ); + } + const fromAudioTimestamp = getValueByPath(fromObject, ["audioTimestamp"]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToVertex(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["parameters", "outputDimensionality"], + fromOutputDimensionality, + ); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath( + parentObject, + ["parameters", "autoTruncate"], + fromAutoTruncate, + ); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["instances[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromImageSize = getValueByPath(fromObject, ["imageSize"]); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath( + parentObject, + ["parameters", "sampleImageSize"], + fromImageSize, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + "segmentationClasses", + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + "enableControlImageComputation", + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath( + toObject, + ["computeControl"], + fromEnableControlImageComputation, + ); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, ["styleDescription"]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ["styleDescription"], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ["subjectType"]); + if (fromSubjectType != null) { + setValueByPath(toObject, ["subjectType"], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + "subjectDescription", + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, ["referenceImage"]); + if (fromReferenceImage != null) { + setValueByPath( + toObject, + ["referenceImage"], + imageToVertex(fromReferenceImage), + ); + } + const fromReferenceId = getValueByPath(fromObject, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, ["referenceType"]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, ["maskImageConfig"]); + if (fromMaskImageConfig != null) { + setValueByPath( + toObject, + ["maskImageConfig"], + maskReferenceConfigToVertex(fromMaskImageConfig), + ); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + "controlImageConfig", + ]); + if (fromControlImageConfig != null) { + setValueByPath( + toObject, + ["controlImageConfig"], + controlReferenceConfigToVertex(fromControlImageConfig), + ); + } + const fromStyleImageConfig = getValueByPath(fromObject, ["styleImageConfig"]); + if (fromStyleImageConfig != null) { + setValueByPath( + toObject, + ["styleImageConfig"], + styleReferenceConfigToVertex(fromStyleImageConfig), + ); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + "subjectImageConfig", + ]); + if (fromSubjectImageConfig != null) { + setValueByPath( + toObject, + ["subjectImageConfig"], + subjectReferenceConfigToVertex(fromSubjectImageConfig), + ); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromEditMode = getValueByPath(fromObject, ["editMode"]); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath( + parentObject, + ["parameters", "editConfig", "baseSteps"], + fromBaseSteps, + ); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, ["referenceImages"]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath( + toObject, + ["instances[0]", "referenceImages"], + transformedList, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + editImageConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + "enhanceInputImage", + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "enhanceInputImage"], + fromEnhanceInputImage, + ); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + "imagePreservationFactor", + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "imagePreservationFactor"], + fromImagePreservationFactor, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromMode = getValueByPath(fromObject, ["mode"]); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromUpscaleFactor = getValueByPath(fromObject, ["upscaleFactor"]); + if (fromUpscaleFactor != null) { + setValueByPath( + toObject, + ["parameters", "upscaleConfig", "upscaleFactor"], + fromUpscaleFactor, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + countTokensConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromFps = getValueByPath(fromObject, ["fps"]); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromResolution = getValueByPath(fromObject, ["resolution"]); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath( + parentObject, + ["parameters", "pubsubTopic"], + fromPubsubTopic, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + const fromGenerateAudio = getValueByPath(fromObject, ["generateAudio"]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath( + parentObject, + ["parameters", "generateAudio"], + fromGenerateAudio, + ); + } + const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath( + parentObject, + ["instances[0]", "lastFrame"], + imageToVertex(fromLastFrame), + ); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + "compressionQuality", + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "compressionQuality"], + fromCompressionQuality, + ); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath( + toObject, + ["instances[0]", "video"], + videoToVertex(fromVideo), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromMldev(fromSafetyAttributes), + ); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromMldev(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromMldev(fromTunedModelInfo), + ); + } + const fromInputTokenLimit = getValueByPath(fromObject, ["inputTokenLimit"]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, ["outputTokenLimit"]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + "supportedGenerationMethods", + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["video", "uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["video", "encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["generatedSamples"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + "response", + "generateVideoResponse", + ]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromMldev(fromResponse), + ); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citations"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromVertex(fromCitationMetadata), + ); + } + const fromFinishMessage = getValueByPath(fromObject, ["finishMessage"]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ["finishMessage"], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromVertex(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ["statistics"]); + if (fromStatistics != null) { + setValueByPath( + toObject, + ["statistics"], + contentEmbeddingStatisticsFromVertex(fromStatistics), + ); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + "billableCharacterCount", + ]); + if (fromBillableCharacterCount != null) { + setValueByPath( + toObject, + ["billableCharacterCount"], + fromBillableCharacterCount, + ); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + "predictions[]", + "embeddings", + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath( + toObject, + ["metadata"], + embedContentMetadataFromVertex(fromMetadata), + ); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromVertex(fromSafetyAttributes), + ); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromVertex(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, ["deployedModelId"]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + "labels", + "google-vertex-llm-tuning-base-model-id", + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromVertex(fromTunedModelInfo), + ); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]); + if (fromTokensInfo != null) { + setValueByPath(toObject, ["tokensInfo"], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromVertex(fromResponse), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = "Content-Type"; +const SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; +const USER_AGENT_HEADER = "User-Agent"; +const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; +const SDK_VERSION = "1.11.0"; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; +const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { + project: opts.project, + location: opts.location, + apiKey: opts.apiKey, + vertexai: opts.vertexai, + }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 + ? _a + : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 + ? _b + : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions( + initHttpOptions, + opts.httpOptions, + ); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if ( + this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== "global" + ) { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 + ? _a + : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined + ) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error("API version is not set."); + } + getBaseUrl() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined + ) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error("Base URL is not set."); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined + ) { + return this.clientOptions.httpOptions.headers; + } else { + throw new Error("Headers are not set."); + } + } + getRequestUrlInternal(httpOptions) { + if ( + !httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined + ) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== "") { + urlElement.push(path); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if ( + request.httpMethod === "GET" && + request.path.startsWith("publishers/google/models") + ) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error( + "Request body should be empty for GET request, but got non empty request body", + ); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === "object") { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign( + Object.assign({}, patchedHttpOptions[key]), + value, + ); + } else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit( + requestInit, + httpOptions, + abortSignal, + ) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if ( + httpOptions.timeout && + (httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.timeout) > 0 + ) { + const timeoutHandle = setTimeout( + () => abortController.abort(), + httpOptions.timeout, + ); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + const reader = + (_a = + response === null || response === void 0 + ? void 0 + : response.body) === null || _a === void 0 + ? void 0 + : _a.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse( + JSON.stringify(chunkJson["error"]), + ); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } catch (e) { + const error = e; + if (error.name === "ApiError") { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: + response === null || response === void 0 + ? void 0 + : response.headers, + status: + response === null || response === void 0 + ? void 0 + : response.status, + statusText: + response === null || response === void 0 + ? void 0 + : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } catch (e) { + throw new Error( + `exception parsing stream chunk ${processedChunkString}. ${e}`, + ); + } + } + } + } finally { + reader.releaseLock(); + } + }, + ); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = + LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append( + SERVER_TIMEOUT_HEADER, + String(Math.ceil(httpOptions.timeout / 1000)), + ); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = + (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== + null && _a !== void 0 + ? _a + : fileStat.type; + if (mimeType === undefined || mimeType === "") { + throw new Error( + "Can not determine mimeType. Please provide mimeType in the config.", + ); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } else { + httpOptions = { + apiVersion: "", + headers: { + "Content-Type": "application/json", + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`, + "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`, + }, + }; + } + const body = { + file: file, + }; + const httpResponse = await this.request({ + path: formatMap("upload/v1beta/files", body["_url"]), + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions, + }); + if ( + !httpResponse || + !(httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) + ) { + throw new Error( + "Server did not return an HttpResponse or the returned HttpResponse did not have headers.", + ); + } + const uploadUrl = + (_a = + httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) === null || _a === void 0 + ? void 0 + : _a["x-goog-upload-url"]; + if (uploadUrl === undefined) { + throw new Error( + "Failed to get upload url. Server did not return the x-google-upload-url in the headers", + ); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ( + (_a = response.headers.get("content-type")) === null || _a === void 0 + ? void 0 + : _a.includes("application/json") + ) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn( + "includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.", + ); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if ( + typeof parsedBody === "object" && + parsedBody !== null && + !Array.isArray(parsedBody) + ) { + currentBodyObject = parsedBody; + } else { + console.warn( + "includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.", + ); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } catch (e) { + console.warn( + "includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.", + ); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if ( + sourceValue && + typeof sourceValue === "object" && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === "object" && + !Array.isArray(targetValue) + ) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if ( + targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue + ) { + console.warn( + `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`, + ); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = "mcp_used/unknown"; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = + (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 + ? _a + : ""; + headers[GOOGLE_API_CLIENT_HEADER] = ( + existingHeader + ` ${MCP_LABEL}` + ).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return ( + object !== null && + typeof object === "object" && + object instanceof McpCallableTool + ); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for ( + var _d = true, + _e = ((e_1 = void 0), __asyncValues(listAllTools(mcpClient))), + _f; + (_f = await _e.next()), (_a = _f.done), !_a; + _d = true + ) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, + requestOptions, + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return ( + client !== null && + typeof client === "object" && + "listTools" in client && + typeof client.listTools === "function" + ); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error("No MCP clients provided"); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error("Live music is not supported for Vertex AI."); + } + console.warn( + "Live music generation is experimental and may change in future versions.", + ); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap$1(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if ( + !params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0 + ) { + throw new Error( + "Weighted prompts must be set and contain at least one entry.", + ); + } + const setWeightedPromptsParameters = + liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev( + setWeightedPromptsParameters, + ); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(exports.LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = + "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic( + this.apiClient, + this.auth, + this.webSocketFactory, + ); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error( + "The Live module does not support httpOptions at request-level in" + + " LiveConnectConfig yet. Please use the client-level httpOptions" + + " configuration instead.", + ); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const defaultHeaders = this.apiClient.getDefaultHeaders(); + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + setMcpUsageHeader(defaultHeaders); + } + const headers = mapToHeaders(defaultHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if ( + apiKey === null || apiKey === void 0 + ? void 0 + : apiKey.startsWith("auth_tokens/") + ) { + console.warn( + "Warning: Ephemeral token support is experimental and may change in future versions.", + ); + if (apiVersion !== "v1alpha") { + 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.", + ); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onopen) === null || _a === void 0 + ? void 0 + : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if ( + this.apiClient.isVertexAI() && + transformedModel.startsWith("publishers/") + ) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if ( + this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 + ? void 0 + : _c.responseModalities) === undefined + ) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [exports.Modality.AUDIO] }; + } else { + params.config.responseModalities = [exports.Modality.AUDIO]; + } + } + if ( + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.generationConfig + ) { + // Raise deprecation warning for 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).", + ); + } + const inputTools = + (_f = + (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== + null && _f !== void 0 + ? _f + : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex( + this.apiClient, + liveConnectParameters, + ); + } else { + clientMessage = liveConnectParametersToMldev( + this.apiClient, + liveConnectParameters, + ); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a) { + throw new Error( + `Failed to parse client content "turns", type: '${typeof params.turns}'`, + ); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if ( + typeof functionResponse !== "object" || + functionResponse === null || + !("name" in functionResponse) || + !("response" in functionResponse) + ) { + throw new Error( + `Could not parse function response, type '${typeof functionResponse}'.`, + ); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign( + Object.assign({}, defaultLiveSendClientContentParamerters), + params, + ); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToVertex(params), + }; + } else { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ( + (_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.disable + ) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = + config === null || config === void 0 ? void 0 : config.tools) !== null && + _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = + (_c = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _c === void 0 + ? void 0 + : _c.maximumRemoteCalls; + if ( + (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0 + ) { + 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:", + maxCalls, + ); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error( + "Automatic function calling with CallableTools and Tools is not yet supported.", + ); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents( + transformedParams.contents, + ); + const maxRemoteCalls = + (_c = + (_b = + (_a = transformedParams.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.tools) !== null && _e !== void 0 + ? _e + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if ( + apiResponse === null || apiResponse === void 0 + ? void 0 + : apiResponse.generatedImages + ) { + for (const generatedImage of apiResponse.generatedImages) { + if ( + generatedImage && + (generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) && + ((_a = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) === null || _a === void 0 + ? void 0 + : _a.contentType) === "Positive Prompt" + ) { + positivePromptSafetyAttributes = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign( + Object.assign({}, defaultConfig), + params === null || params === void 0 ? void 0 : params.config, + ); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ( + (_a = actualParams.config) === null || _a === void 0 + ? void 0 + : _a.filter + ) { + throw new Error( + "Filtering tuned models list for Vertex AI is not currently supported", + ); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager( + exports.PagedItem.PAGED_ITEM_MODELS, + (x) => this.listInternal(x), + await this.listInternal(actualParams), + actualParams, + ); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => + img.toReferenceImageAPI(), + ); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale", + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all( + tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + }), + ); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { + tools: transformedTools, + }), + }; + newParams.config.tools = transformedTools; + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + const headers = + (_c = + (_b = params.config.httpOptions) === null || _b === void 0 + ? void 0 + : _b.headers) !== null && _c !== void 0 + ? _c + : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign( + Object.assign({}, params.config.httpOptions), + { headers: newHeaders }, + ); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== + null && _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = + toolDeclaration.functionDeclarations) !== null && _c !== void 0 + ? _c + : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error( + `Duplicate tool declaration name: ${declaration.name}`, + ); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = + (_c = + (_b = + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await( + models.processParamsMaybeAddMcpUsage(params), + ); + const response = yield __await( + models.generateContentStreamInternal(transformedParams), + ); + const functionResponses = []; + const responseContents = []; + try { + for ( + var _f = true, + response_1 = ((e_1 = void 0), __asyncValues(response)), + response_1_1; + (response_1_1 = yield __await(response_1.next())), + (_c = response_1_1.done), + !_c; + _f = true + ) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if ( + chunk.candidates && + ((_a = chunk.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content) + ) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== + null && _b !== void 0 + ? _b + : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error( + "Function call name was not returned by the model.", + ); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error( + `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`, + ); + } else { + const responseParts = yield __await( + afcTools + .get(part.functionCall.name) + .callTool([part.functionCall]), + ); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = response_1.return)) + yield __await(_d.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat( + newContents, + ); + params.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for ( + var _d = true, + apiResponse_1 = __asyncValues(apiResponse), + apiResponse_1_1; + (apiResponse_1_1 = yield __await(apiResponse_1.next())), + (_a = apiResponse_1_1.done), + !_a; + _d = true + ) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) + yield __await(_b.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for ( + var _d = true, + apiResponse_2 = __asyncValues(apiResponse), + apiResponse_2_1; + (apiResponse_2_1 = yield __await(apiResponse_2.next())), + (_a = apiResponse_2_1.done), + !_a; + _d = true + ) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) + yield __await(_b.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex( + this.apiClient, + params, + ); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev(fromProactivity), + ); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + "newSessionExpireTime", + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath( + parentObject, + ["newSessionExpireTime"], + fromNewSessionExpireTime, + ); + } + const fromUses = getValueByPath(fromObject, ["uses"]); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + "liveConnectConstraints", + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath( + parentObject, + ["bidiGenerateContentSetup"], + liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints), + ); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + "lockAdditionalFields", + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createAuthTokenConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if ( + typeof value === "object" && + value != null && + Object.keys(value).length > 0 + ) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); // 1st layer + } + } + } + return fields.join(","); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if ( + typeof bidiGenerateContentSetupValue === "object" && + bidiGenerateContentSetupValue !== null && + "setup" in bidiGenerateContentSetupValue + ) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + // Valid inner setup found. + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if ( + Array.isArray( + config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields, + ) && + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields.length) === 0 + ) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; // If mask is empty, effectively no + // specific fields locked by bidi + } + } else if ( + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig", + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict["fieldMask"]; + } + } else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict["fieldMask"]; + } + } else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if ( + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "The client.tokens.create method is only supported by the Gemini Developer API.", + ); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = "x-goog-api-key"; +const REQUIRED_VERTEX_AI_SCOPE = + "https://www.googleapis.com/auth/cloud-platform"; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new googleAuthLibrary.GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error("Trying to set API key header but apiKey is not set"); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error( + "Trying to set google-auth headers but googleAuth is unset", + ); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } else if ( + (typeof authOptions.scopes === "string" && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0) + ) { + throw new Error( + `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`, + ); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = fs.createWriteStream(params.downloadPath); + node_stream.Readable.fromWeb(response.responseInternal.body).pipe( + writer, + ); + } else { + fs.writeFile( + params.downloadPath, + response, + { encoding: "base64" }, + (error) => { + if (error) { + throw new Error( + `Failed to write file to ${params.downloadPath}: ${error}`, + ); + } + }, + ); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: "GET", + queryParams: { + alt: "media", + }, + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else if (isGeneratedVideo(params.file)) { + const videoBytes = + (_c = params.file.video) === null || _c === void 0 + ? void 0 + : _c.videoBytes; + if (typeof videoBytes === "string") { + return videoBytes; + } else { + throw new Error( + "Failed to download generated video, Uri or videoBytes not found.", + ); + } + } else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === "string") { + return videoBytes; + } else { + throw new Error("Failed to download video, Uri or videoBytes not found."); + } + } else { + throw new Error("Unsupported file type"); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs__namespace.WebSocket(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(message) { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ["textInput"]); + if (fromTextInput != null) { + setValueByPath(toObject, ["textInput"], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ["output"]); + if (fromOutput != null) { + setValueByPath(toObject, ["output"], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== undefined) { + throw new Error( + "vertexDatasetResource parameter is not supported in Gemini API.", + ); + } + const fromExamples = getValueByPath(fromObject, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["validationDataset"]) !== undefined) { + throw new Error( + "validationDataset parameter is not supported in Gemini API.", + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ["description"]) !== undefined) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath( + toObject, + ["tuningTask", "hyperparameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== undefined) { + throw new Error( + "exportLastCheckpointOnly parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["adapterSize"]) !== undefined) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject, ["batchSize"]); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "batchSize"], + fromBatchSize, + ); + } + const fromLearningRate = getValueByPath(fromObject, ["learningRate"]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "learningRate"], + fromLearningRate, + ); + } + return toObject; +} +function createTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["tuningTask", "trainingData"], + tuningDatasetToMldev(fromTrainingDataset), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromGcsUri, + ); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + if (getValueByPath(fromObject, ["examples"]) !== undefined) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + "validationDataset", + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec"], + tuningValidationDatasetToVertex(fromValidationDataset, toObject), + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath( + parentObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + "exportLastCheckpointOnly", + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "exportLastCheckpointOnly"], + fromExportLastCheckpointOnly, + ); + } + const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "adapterSize"], + fromAdapterSize, + ); + } + if (getValueByPath(fromObject, ["batchSize"]) !== undefined) { + throw new Error("batchSize parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["learningRate"]) !== undefined) { + throw new Error("learningRate parameter is not supported in Vertex AI."); + } + return toObject; +} +function createTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + tuningDatasetToVertex(fromTrainingDataset, toObject), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["tuningTask", "startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + "tuningTask", + "completeTime", + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["_self"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromMldev(fromTunedModel), + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromVertex(fromTunedModel), + ); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + "supervisedTuningSpec", + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec"], + fromSupervisedTuningSpec, + ); + } + const fromTuningDataStats = getValueByPath(fromObject, ["tuningDataStats"]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, ["encryptionSpec"]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + "partnerModelTuningSpec", + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath( + toObject, + ["partnerModelTuningSpec"], + fromPartnerModelTuningSpec, + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager( + exports.PagedItem.PAGED_ITEM_TUNING_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + return await this.tuneInternal(params); + } else { + const operation = await this.tuneMldevInternal(params); + let tunedModelName = ""; + if ( + operation["metadata"] !== undefined && + operation["metadata"]["tunedModel"] !== undefined + ) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if ( + operation["name"] !== undefined && + operation["name"].includes("/operations/") + ) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: exports.JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createTuningJobParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 ? void 0 : response.headers) === + null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === "string") { + const originalStat = await fs__namespace.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf(".") + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 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", + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + let fileHandle; + try { + fileHandle = await fs__namespace.open(file, "r"); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read( + buffer, + 0, + chunkSize, + offset, + ); + if (bytesRead !== chunkSize) { + throw new Error( + `Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`, + ); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(bytesRead), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error( + "Failed to upload file: Upload status is not finalized.", + ); + } + return responseJson["file"]; + } finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = "gl-node/"; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error( + "Project/location and API key are mutually exclusive in the client initializer.", + ); + } + this.vertexai = + (_b = + (_a = options.vertexai) !== null && _a !== void 0 + ? _a + : getBooleanEnv("GOOGLE_GENAI_USE_VERTEXAI")) !== null && + _b !== void 0 + ? _b + : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv("GOOGLE_CLOUD_PROJECT"); + const envLocation = getEnv("GOOGLE_CLOUD_LOCATION"); + this.apiKey = + (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = + (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = + (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ( + (_f = options.googleAuthOptions) === null || _f === void 0 + ? void 0 + : _f.credentials + ) { + // Explicit credentials take precedence over implicit api_key. + console.debug( + "The user provided Google Cloud credentials will take precedence" + + " over the API key from the environment variable.", + ); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug( + "The user provided Vertex AI API key will take precedence over" + + " the project/location from the environment variables.", + ); + this.project = undefined; + this.location = undefined; + } else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug( + "The user provided project/location will take precedence over" + + " the API key from the environment variables.", + ); + this.apiKey = undefined; + } else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug( + "The project/location from the environment variables will take" + + " precedence over the API key from the environment variables.", + ); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl( + options.httpOptions, + options.vertexai, + getEnv("GOOGLE_VERTEX_BASE_URL"), + getEnv("GOOGLE_GEMINI_BASE_URL"), + ); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = + (_b = + (_a = process === null || process === void 0 ? void 0 : process.env) === + null || _a === void 0 + ? void 0 + : _a[env]) === null || _b === void 0 + ? void 0 + : _b.trim()) !== null && _c !== void 0 + ? _c + : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === "true"; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv("GOOGLE_API_KEY"); + const envGeminiApiKey = getEnv("GEMINI_API_KEY"); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn( + "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.", + ); + } + return envGoogleApiKey || envGeminiApiKey; +} + +exports.ApiError = ApiError; +exports.Batches = Batches; +exports.Caches = Caches; +exports.Chat = Chat; +exports.Chats = Chats; +exports.ComputeTokensResponse = ComputeTokensResponse; +exports.ControlReferenceImage = ControlReferenceImage; +exports.CountTokensResponse = CountTokensResponse; +exports.CreateFileResponse = CreateFileResponse; +exports.DeleteCachedContentResponse = DeleteCachedContentResponse; +exports.DeleteFileResponse = DeleteFileResponse; +exports.DeleteModelResponse = DeleteModelResponse; +exports.EditImageResponse = EditImageResponse; +exports.EmbedContentResponse = EmbedContentResponse; +exports.Files = Files; +exports.FunctionResponse = FunctionResponse; +exports.GenerateContentResponse = GenerateContentResponse; +exports.GenerateContentResponsePromptFeedback = + GenerateContentResponsePromptFeedback; +exports.GenerateContentResponseUsageMetadata = + GenerateContentResponseUsageMetadata; +exports.GenerateImagesResponse = GenerateImagesResponse; +exports.GenerateVideosOperation = GenerateVideosOperation; +exports.GenerateVideosResponse = GenerateVideosResponse; +exports.GoogleGenAI = GoogleGenAI; +exports.HttpResponse = HttpResponse; +exports.InlinedResponse = InlinedResponse; +exports.ListBatchJobsResponse = ListBatchJobsResponse; +exports.ListCachedContentsResponse = ListCachedContentsResponse; +exports.ListFilesResponse = ListFilesResponse; +exports.ListModelsResponse = ListModelsResponse; +exports.ListTuningJobsResponse = ListTuningJobsResponse; +exports.Live = Live; +exports.LiveClientToolResponse = LiveClientToolResponse; +exports.LiveMusicServerMessage = LiveMusicServerMessage; +exports.LiveSendToolResponseParameters = LiveSendToolResponseParameters; +exports.LiveServerMessage = LiveServerMessage; +exports.MaskReferenceImage = MaskReferenceImage; +exports.Models = Models; +exports.Operations = Operations; +exports.Pager = Pager; +exports.RawReferenceImage = RawReferenceImage; +exports.ReplayResponse = ReplayResponse; +exports.Session = Session; +exports.StyleReferenceImage = StyleReferenceImage; +exports.SubjectReferenceImage = SubjectReferenceImage; +exports.Tokens = Tokens; +exports.UpscaleImageResponse = UpscaleImageResponse; +exports.createModelContent = createModelContent; +exports.createPartFromBase64 = createPartFromBase64; +exports.createPartFromCodeExecutionResult = createPartFromCodeExecutionResult; +exports.createPartFromExecutableCode = createPartFromExecutableCode; +exports.createPartFromFunctionCall = createPartFromFunctionCall; +exports.createPartFromFunctionResponse = createPartFromFunctionResponse; +exports.createPartFromText = createPartFromText; +exports.createPartFromUri = createPartFromUri; +exports.createUserContent = createUserContent; +exports.mcpToTool = mcpToTool; +exports.setDefaultBaseUrls = setDefaultBaseUrls; +//# sourceMappingURL=index.cjs.map diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs new file mode 100644 index 0000000..25e3a81 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs @@ -0,0 +1,20795 @@ +import { GoogleAuth } from "google-auth-library"; +import { createWriteStream, writeFile } from "fs"; +import { Readable } from "node:stream"; +import * as NodeWs from "ws"; +import * as fs from "fs/promises"; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl( + httpOptions, + vertexai, + vertexBaseUrlFromEnv, + geminiBaseUrlFromEnv, +) { + var _a, _b; + if ( + !(httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.baseUrl) + ) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 + ? _a + : vertexBaseUrlFromEnv; + } else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 + ? _b + : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule {} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ""; + } else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if ( + !value || + (typeof value === "object" && Object.keys(value).length === 0) + ) { + return; + } + if (value === existingData) { + return; + } + if ( + typeof existingData === "object" && + typeof value === "object" && + existingData !== null && + value !== null + ) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === "_self") { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== "object" || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } else { + return undefined; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = + "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = + "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = + "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = + "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** Required. The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = + "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = + "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = + "URL_RETRIEVAL_STATUS_ERROR"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = + "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = + "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = + "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = + "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = + "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = + "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = + "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = + "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse {} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === "object" && obj !== null) { + return ( + "fileData" in obj || + "text" in obj || + "functionCall" in obj || + "functionResponse" in obj || + "inlineData" in obj || + "videoMetadata" in obj || + "codeExecutionResult" in obj || + "executableCode" in obj + ); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === "string") { + parts.push(createPartFromText(partOrString)); + } else if (_isPart(partOrString)) { + parts.push(partOrString); + } else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error("partOrString cannot be an empty array"); + } + for (const part of partOrString) { + if (typeof part === "string") { + parts.push(createPartFromText(part)); + } else if (_isPart(part)) { + parts.push(part); + } else { + throw new Error("element in PartUnion must be a Part object or string"); + } + } + } else { + throw new Error("partOrString must be a Part object, string, or array"); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: "user", + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: "model", + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback {} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata {} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning text from the first one.", + ); + } + let text = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning data from the first one.", + ); + } + let data = ""; + const nonDataParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "inlineData" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning function calls from the first one.", + ); + } + const functionCalls = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.functionCall) + .map((part) => part.functionCall) + .filter((functionCall) => functionCall !== undefined); + if ( + (functionCalls === null || functionCalls === void 0 + ? void 0 + : functionCalls.length) === 0 + ) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning executable code from the first one.", + ); + } + const executableCode = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.executableCode) + .map((part) => part.executableCode) + .filter((executableCode) => executableCode !== undefined); + if ( + (executableCode === null || executableCode === void 0 + ? void 0 + : executableCode.length) === 0 + ) { + return undefined; + } + return (_j = + executableCode === null || executableCode === void 0 + ? void 0 + : executableCode[0]) === null || _j === void 0 + ? void 0 + : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning code execution result from the first one.", + ); + } + const codeExecutionResult = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.codeExecutionResult) + .map((part) => part.codeExecutionResult) + .filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ( + (codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult.length) === 0 + ) { + return undefined; + } + return (_j = + codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult[0]) === null || _j === void 0 + ? void 0 + : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse {} +/** The output images response. */ +class GenerateImagesResponse {} +/** Response for the request to edit an image. */ +class EditImageResponse {} +class UpscaleImageResponse {} +class ListModelsResponse {} +class DeleteModelResponse {} +/** Response for counting tokens. */ +class CountTokensResponse {} +/** Response for computing tokens. */ +class ComputeTokensResponse {} +/** Response with generated videos. */ +class GenerateVideosResponse {} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse {} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse {} +class ListCachedContentsResponse {} +/** Response for the list files method. */ +class ListFilesResponse {} +/** Response for the create file method. */ +class CreateFileResponse {} +/** Response for the delete file method. */ +class DeleteFileResponse {} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse {} +/** Config for batches.list return value. */ +class ListBatchJobsResponse {} +/** Represents a single response in a replay. */ +class ReplayResponse {} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_RAW", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_MASK", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_CONTROL", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_STYLE", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_SUBJECT", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + fieldValue !== null + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse["name"]; + operation.metadata = apiResponse["metadata"]; + operation.done = apiResponse["done"]; + operation.error = apiResponse["error"]; + if (isVertexAI) { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response["videos"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo["gcsUri"], + videoBytes: generatedVideo["bytesBase64Encoded"] + ? tBytes$1(generatedVideo["bytesBase64Encoded"]) + : undefined, + mimeType: generatedVideo["mimeType"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } else { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response["generateVideoResponse"]; + const responseVideos = + generatedVideoResponse === null || generatedVideoResponse === void 0 + ? void 0 + : generatedVideoResponse["generatedSamples"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + const video = generatedVideo["video"]; + return { + video: { + uri: + video === null || video === void 0 + ? void 0 + : video["uri"], + videoBytes: ( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"] + ) + ? tBytes$1( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"], + ) + : undefined, + mimeType: generatedVideo["encoding"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse {} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if ( + this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0 + ) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (apiClient.isVertexAI()) { + if ( + model.startsWith("publishers/") || + model.startsWith("projects/") || + model.startsWith("models/") + ) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error( + `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`, + ); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("image/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("audio/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "parts" in origin && + Array.isArray(origin.parts) + ); +} +function _isFunctionCallPart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionCall" in origin + ); +} +function _isFunctionResponsePart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionResponse" in origin + ); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: "user", + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error( + "To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them", + ); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new 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 (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(Type).includes( + listWithoutNull[0].toUpperCase(), + ) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i of listWithoutNull) { + resultingSchema["anyOf"].push({ + type: Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error( + "type: null can not be the only possible type for the field.", + ); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema["type"] = Object.values(Type).includes( + fieldValue.toUpperCase(), + ) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error( + "multiSpeakerVoiceConfig is not supported in the live API.", + ); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema( + functionDeclaration.parameters, + ); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema( + functionDeclaration.response, + ); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName( + client, + resourceName, + resourcePrefix, + splitsAfterPrefix = 1, +) { + const shouldAppendPrefix = + !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith("projects/")) { + return resourceName; + } else if (resourceName.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName}`; + } else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "name" in origin + ); +} +function isGeneratedVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "video" in origin + ); +} +function isVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "uri" in origin + ); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === undefined) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"], + }; + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [functionDeclaration], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== "string" && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set."); + } else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error("One of `gcsUri` or `bigqueryUri` must be set."); + } + } else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error( + "Only one of `inlinedRequests` or `fileName` can be set.", + ); + } else if (!src.inlinedRequests && !src.fileName) { + throw new Error("One of `inlinedRequests` or `fileName` must be set."); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } else if (typeof src === "string") { + if (src.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: [src], // GCS URI is expected as an array + }; + } else if (src.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: src, + }; + } else if (src.startsWith("files/")) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString, + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString, + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = + /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$4(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$4(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$4(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$4(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$2(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$2(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$4(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev$1(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$2(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev$1(fromThinkingConfig), + ); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath( + toObject, + ["request", "model"], + tModel(apiClient, fromModel), + ); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["request", "generationConfig"], + generateContentConfigToMldev$1(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["format"]) !== undefined) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["bigqueryUri"]) !== undefined) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, ["inlinedRequests"]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject, ["dest"]) !== undefined) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["batch", "inputConfig"], + batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject, ["filter"]) !== undefined) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedRequests"]) !== undefined) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath( + toObject, + ["bigqueryDestination", "outputUri"], + fromBigqueryUri, + ); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedResponses"]) !== undefined) { + throw new Error( + "inlinedResponses parameter is not supported in Vertex AI.", + ); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ["dest"]); + if (parentObject !== undefined && fromDest != null) { + setValueByPath( + parentObject, + ["outputConfig"], + batchJobDestinationToVertex(tBatchJobDestination(fromDest)), + ); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["inputConfig"], + batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev$1(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$2(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateContentResponseFromMldev$1(fromResponse), + ); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + "inlinedResponses", + "inlinedResponses", + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + "metadata", + "displayName", + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["metadata", "createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, ["metadata", "endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["metadata", "updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigquerySource", + "inputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + "gcsDestination", + "outputUriPrefix", + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigqueryDestination", + "outputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["batchPredictionJobs"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = + response === null || response === void 0 + ? void 0 + : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = + (_a = requestParams["config"]) === null || _a === void 0 + ? void 0 + : _a["pageSize"]) !== null && _b !== void 0 + ? _b + : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if ( + ((_a = this.params["config"]) === null || _a === void 0 + ? void 0 + : _a["pageToken"]) !== undefined + ) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error( + "InlinedRequest[] is not supported in Vertex AI. Please use " + + "Google Cloud Storage URI or BigQuery URI instead.", + ); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = "genaiBatchJob_${timestampStr}"; + } + if ( + params.config.dest === undefined && + typeof params.src === "string" + ) { + if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } else if (params.src.startsWith("bq://")) { + params.config.dest = `${params.src}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source:" + params.src); + } + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_BATCH_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$3(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$3(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$3(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$3(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$3(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$1(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["kmsKeyName"]) !== undefined) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$2() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$2(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$2(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$2(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$2(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$2()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex$1(fromToolConfig), + ); + } + const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath( + parentObject, + ["encryption_spec", "kmsKeyName"], + fromKmsKeyName, + ); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_CACHED_CONTENTS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined.", + ); +} + +function __await(v) { + return this instanceof __await ? ((this.v = v), this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = Object.create( + (typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype, + )), + verb("next"), + verb("throw"), + verb("return", awaitReturn), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" ? __values(o) : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ value: v, done: d }); + }, reject); + } +} + +typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = + (_a = response.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (!part.thought && part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === "user") { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === "model") { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history), + ); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = + (_b = + (_a = response.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = + response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && + _c !== void 0 + ? _c + : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory( + inputContent, + modelOutput, + automaticFunctionCallingHistory, + ); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for ( + var _f = true, + streamResponse_1 = __asyncValues(streamResponse), + streamResponse_1_1; + (streamResponse_1_1 = yield __await(streamResponse_1.next())), + (_c = streamResponse_1_1.done), + !_c; + _f = true + ) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = + (_b = + (_a = chunk.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) + yield __await(_d.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }, + ); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if ( + modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined) + ) { + outputContents = modelOutput; + } else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: "model", + parts: [], + }); + } + if ( + automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0 + ) { + this.history.push( + ...extractCuratedHistory(automaticFunctionCallingHistory), + ); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listFilesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_FILES, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error( + "Vertex AI does not support uploading files. You can share files through a GCS bucket.", + ); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = listFilesParametersToMldev(params); + path = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createFileParametersToMldev(params); + path = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = getFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = deleteFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$2(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev$1(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev$1(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev$1(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev$1(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev$1(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev$1(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ["setup"]); + if (fromSetup != null) { + setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentToMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + const fromPlaybackControl = getValueByPath(fromObject, ["playbackControl"]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ["playbackControl"], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex$1(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$1(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$1(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$1(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$1(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$1()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ["transparent"]); + if (fromTransparent != null) { + setValueByPath(toObject, ["transparent"], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToVertex(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToVertex(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToVertex$1(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToVertex(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToVertex(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToVertex(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToVertex(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromMldev(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromMldev(fromOutputTranscription), + ); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$1(fromUrlContextMetadata), + ); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "responseTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "responseTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromMldev(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromMldev(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromMldev(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromMldev(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate), + ); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentFromMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, ["sourceMetadata"]); + if (fromSourceMetadata != null) { + setValueByPath( + toObject, + ["sourceMetadata"], + liveMusicSourceMetadataFromMldev(fromSourceMetadata), + ); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ["audioChunks"], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, ["filteredReason"]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ["filteredReason"], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveMusicServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveMusicServerContentFromMldev(fromServerContent), + ); + } + const fromFilteredPrompt = getValueByPath(fromObject, ["filteredPrompt"]); + if (fromFilteredPrompt != null) { + setValueByPath( + toObject, + ["filteredPrompt"], + liveMusicFilteredPromptFromMldev(fromFilteredPrompt), + ); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ["sessionId"]); + if (fromSessionId != null) { + setValueByPath(toObject, ["sessionId"], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromVertex(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromVertex(fromOutputTranscription), + ); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "candidatesTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "candidatesTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromVertex(fromSetupComplete), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromVertex(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromVertex(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromVertex(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromVertex(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath( + toObject, + ["goAway"], + liveServerGoAwayFromVertex(fromGoAway), + ); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$1(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$1(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["requests[]", "outputDimensionality"], + fromOutputDimensionality, + ); + } + if (getValueByPath(fromObject, ["mimeType"]) !== undefined) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["autoTruncate"]) !== undefined) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["requests[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToMldev(fromConfig, toObject), + ); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]); + if (fromModelForEmbedContent !== undefined) { + setValueByPath( + toObject, + ["requests[]", "model"], + tModel(apiClient, fromModelForEmbedContent), + ); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["negativePrompt"]) !== undefined) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + if (getValueByPath(fromObject, ["addWatermark"]) !== undefined) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["imageSize"]) !== undefined) { + throw new Error("imageSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["enhancePrompt"]) !== undefined) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["systemInstruction"]) !== undefined) { + throw new Error( + "systemInstruction parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["tools"]) !== undefined) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["generationConfig"]) !== undefined) { + throw new Error( + "generationConfig parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["fps"]) !== undefined) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + if (getValueByPath(fromObject, ["resolution"]) !== undefined) { + throw new Error("resolution parameter is not supported in Gemini API."); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + if (getValueByPath(fromObject, ["pubsubTopic"]) !== undefined) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + if (getValueByPath(fromObject, ["generateAudio"]) !== undefined) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["lastFrame"]) !== undefined) { + throw new Error("lastFrame parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["compressionQuality"]) !== undefined) { + throw new Error( + "compressionQuality parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToMldev(fromImage), + ); + } + if (getValueByPath(fromObject, ["video"]) !== undefined) { + throw new Error("video parameter is not supported in Gemini API."); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + "featureSelectionPreference", + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath( + toObject, + ["featureSelectionPreference"], + fromFeatureSelectionPreference, + ); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ["method"]); + if (fromMethod != null) { + setValueByPath(toObject, ["method"], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToVertex(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, ["routingConfig"]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + "modelSelectionConfig", + ]); + if (fromModelSelectionConfig != null) { + setValueByPath( + toObject, + ["modelConfig"], + modelSelectionConfigToVertex(fromModelSelectionConfig), + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex(fromToolConfig), + ); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToVertex(tSpeechConfig(fromSpeechConfig)), + ); + } + const fromAudioTimestamp = getValueByPath(fromObject, ["audioTimestamp"]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToVertex(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["parameters", "outputDimensionality"], + fromOutputDimensionality, + ); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath( + parentObject, + ["parameters", "autoTruncate"], + fromAutoTruncate, + ); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["instances[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromImageSize = getValueByPath(fromObject, ["imageSize"]); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath( + parentObject, + ["parameters", "sampleImageSize"], + fromImageSize, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + "segmentationClasses", + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + "enableControlImageComputation", + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath( + toObject, + ["computeControl"], + fromEnableControlImageComputation, + ); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, ["styleDescription"]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ["styleDescription"], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ["subjectType"]); + if (fromSubjectType != null) { + setValueByPath(toObject, ["subjectType"], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + "subjectDescription", + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, ["referenceImage"]); + if (fromReferenceImage != null) { + setValueByPath( + toObject, + ["referenceImage"], + imageToVertex(fromReferenceImage), + ); + } + const fromReferenceId = getValueByPath(fromObject, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, ["referenceType"]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, ["maskImageConfig"]); + if (fromMaskImageConfig != null) { + setValueByPath( + toObject, + ["maskImageConfig"], + maskReferenceConfigToVertex(fromMaskImageConfig), + ); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + "controlImageConfig", + ]); + if (fromControlImageConfig != null) { + setValueByPath( + toObject, + ["controlImageConfig"], + controlReferenceConfigToVertex(fromControlImageConfig), + ); + } + const fromStyleImageConfig = getValueByPath(fromObject, ["styleImageConfig"]); + if (fromStyleImageConfig != null) { + setValueByPath( + toObject, + ["styleImageConfig"], + styleReferenceConfigToVertex(fromStyleImageConfig), + ); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + "subjectImageConfig", + ]); + if (fromSubjectImageConfig != null) { + setValueByPath( + toObject, + ["subjectImageConfig"], + subjectReferenceConfigToVertex(fromSubjectImageConfig), + ); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromEditMode = getValueByPath(fromObject, ["editMode"]); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath( + parentObject, + ["parameters", "editConfig", "baseSteps"], + fromBaseSteps, + ); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, ["referenceImages"]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath( + toObject, + ["instances[0]", "referenceImages"], + transformedList, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + editImageConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + "enhanceInputImage", + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "enhanceInputImage"], + fromEnhanceInputImage, + ); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + "imagePreservationFactor", + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "imagePreservationFactor"], + fromImagePreservationFactor, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromMode = getValueByPath(fromObject, ["mode"]); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromUpscaleFactor = getValueByPath(fromObject, ["upscaleFactor"]); + if (fromUpscaleFactor != null) { + setValueByPath( + toObject, + ["parameters", "upscaleConfig", "upscaleFactor"], + fromUpscaleFactor, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + countTokensConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromFps = getValueByPath(fromObject, ["fps"]); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromResolution = getValueByPath(fromObject, ["resolution"]); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath( + parentObject, + ["parameters", "pubsubTopic"], + fromPubsubTopic, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + const fromGenerateAudio = getValueByPath(fromObject, ["generateAudio"]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath( + parentObject, + ["parameters", "generateAudio"], + fromGenerateAudio, + ); + } + const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath( + parentObject, + ["instances[0]", "lastFrame"], + imageToVertex(fromLastFrame), + ); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + "compressionQuality", + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "compressionQuality"], + fromCompressionQuality, + ); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath( + toObject, + ["instances[0]", "video"], + videoToVertex(fromVideo), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromMldev(fromSafetyAttributes), + ); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromMldev(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromMldev(fromTunedModelInfo), + ); + } + const fromInputTokenLimit = getValueByPath(fromObject, ["inputTokenLimit"]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, ["outputTokenLimit"]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + "supportedGenerationMethods", + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["video", "uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["video", "encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["generatedSamples"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + "response", + "generateVideoResponse", + ]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromMldev(fromResponse), + ); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citations"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromVertex(fromCitationMetadata), + ); + } + const fromFinishMessage = getValueByPath(fromObject, ["finishMessage"]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ["finishMessage"], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromVertex(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ["statistics"]); + if (fromStatistics != null) { + setValueByPath( + toObject, + ["statistics"], + contentEmbeddingStatisticsFromVertex(fromStatistics), + ); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + "billableCharacterCount", + ]); + if (fromBillableCharacterCount != null) { + setValueByPath( + toObject, + ["billableCharacterCount"], + fromBillableCharacterCount, + ); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + "predictions[]", + "embeddings", + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath( + toObject, + ["metadata"], + embedContentMetadataFromVertex(fromMetadata), + ); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromVertex(fromSafetyAttributes), + ); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromVertex(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, ["deployedModelId"]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + "labels", + "google-vertex-llm-tuning-base-model-id", + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromVertex(fromTunedModelInfo), + ); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]); + if (fromTokensInfo != null) { + setValueByPath(toObject, ["tokensInfo"], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromVertex(fromResponse), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = "Content-Type"; +const SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; +const USER_AGENT_HEADER = "User-Agent"; +const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; +const SDK_VERSION = "1.11.0"; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; +const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { + project: opts.project, + location: opts.location, + apiKey: opts.apiKey, + vertexai: opts.vertexai, + }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 + ? _a + : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 + ? _b + : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions( + initHttpOptions, + opts.httpOptions, + ); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if ( + this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== "global" + ) { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 + ? _a + : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined + ) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error("API version is not set."); + } + getBaseUrl() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined + ) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error("Base URL is not set."); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined + ) { + return this.clientOptions.httpOptions.headers; + } else { + throw new Error("Headers are not set."); + } + } + getRequestUrlInternal(httpOptions) { + if ( + !httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined + ) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== "") { + urlElement.push(path); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if ( + request.httpMethod === "GET" && + request.path.startsWith("publishers/google/models") + ) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error( + "Request body should be empty for GET request, but got non empty request body", + ); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === "object") { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign( + Object.assign({}, patchedHttpOptions[key]), + value, + ); + } else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit( + requestInit, + httpOptions, + abortSignal, + ) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if ( + httpOptions.timeout && + (httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.timeout) > 0 + ) { + const timeoutHandle = setTimeout( + () => abortController.abort(), + httpOptions.timeout, + ); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + const reader = + (_a = + response === null || response === void 0 + ? void 0 + : response.body) === null || _a === void 0 + ? void 0 + : _a.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse( + JSON.stringify(chunkJson["error"]), + ); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } catch (e) { + const error = e; + if (error.name === "ApiError") { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: + response === null || response === void 0 + ? void 0 + : response.headers, + status: + response === null || response === void 0 + ? void 0 + : response.status, + statusText: + response === null || response === void 0 + ? void 0 + : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } catch (e) { + throw new Error( + `exception parsing stream chunk ${processedChunkString}. ${e}`, + ); + } + } + } + } finally { + reader.releaseLock(); + } + }, + ); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = + LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append( + SERVER_TIMEOUT_HEADER, + String(Math.ceil(httpOptions.timeout / 1000)), + ); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = + (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== + null && _a !== void 0 + ? _a + : fileStat.type; + if (mimeType === undefined || mimeType === "") { + throw new Error( + "Can not determine mimeType. Please provide mimeType in the config.", + ); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } else { + httpOptions = { + apiVersion: "", + headers: { + "Content-Type": "application/json", + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`, + "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`, + }, + }; + } + const body = { + file: file, + }; + const httpResponse = await this.request({ + path: formatMap("upload/v1beta/files", body["_url"]), + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions, + }); + if ( + !httpResponse || + !(httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) + ) { + throw new Error( + "Server did not return an HttpResponse or the returned HttpResponse did not have headers.", + ); + } + const uploadUrl = + (_a = + httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) === null || _a === void 0 + ? void 0 + : _a["x-goog-upload-url"]; + if (uploadUrl === undefined) { + throw new Error( + "Failed to get upload url. Server did not return the x-google-upload-url in the headers", + ); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ( + (_a = response.headers.get("content-type")) === null || _a === void 0 + ? void 0 + : _a.includes("application/json") + ) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn( + "includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.", + ); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if ( + typeof parsedBody === "object" && + parsedBody !== null && + !Array.isArray(parsedBody) + ) { + currentBodyObject = parsedBody; + } else { + console.warn( + "includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.", + ); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } catch (e) { + console.warn( + "includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.", + ); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if ( + sourceValue && + typeof sourceValue === "object" && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === "object" && + !Array.isArray(targetValue) + ) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if ( + targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue + ) { + console.warn( + `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`, + ); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = "mcp_used/unknown"; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = + (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 + ? _a + : ""; + headers[GOOGLE_API_CLIENT_HEADER] = ( + existingHeader + ` ${MCP_LABEL}` + ).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return ( + object !== null && + typeof object === "object" && + object instanceof McpCallableTool + ); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for ( + var _d = true, + _e = ((e_1 = void 0), __asyncValues(listAllTools(mcpClient))), + _f; + (_f = await _e.next()), (_a = _f.done), !_a; + _d = true + ) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, + requestOptions, + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return ( + client !== null && + typeof client === "object" && + "listTools" in client && + typeof client.listTools === "function" + ); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error("No MCP clients provided"); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error("Live music is not supported for Vertex AI."); + } + console.warn( + "Live music generation is experimental and may change in future versions.", + ); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap$1(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if ( + !params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0 + ) { + throw new Error( + "Weighted prompts must be set and contain at least one entry.", + ); + } + const setWeightedPromptsParameters = + liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev( + setWeightedPromptsParameters, + ); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = + "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic( + this.apiClient, + this.auth, + this.webSocketFactory, + ); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error( + "The Live module does not support httpOptions at request-level in" + + " LiveConnectConfig yet. Please use the client-level httpOptions" + + " configuration instead.", + ); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const defaultHeaders = this.apiClient.getDefaultHeaders(); + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + setMcpUsageHeader(defaultHeaders); + } + const headers = mapToHeaders(defaultHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if ( + apiKey === null || apiKey === void 0 + ? void 0 + : apiKey.startsWith("auth_tokens/") + ) { + console.warn( + "Warning: Ephemeral token support is experimental and may change in future versions.", + ); + if (apiVersion !== "v1alpha") { + 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.", + ); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onopen) === null || _a === void 0 + ? void 0 + : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if ( + this.apiClient.isVertexAI() && + transformedModel.startsWith("publishers/") + ) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if ( + this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 + ? void 0 + : _c.responseModalities) === undefined + ) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ( + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.generationConfig + ) { + // Raise deprecation warning for 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).", + ); + } + const inputTools = + (_f = + (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== + null && _f !== void 0 + ? _f + : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex( + this.apiClient, + liveConnectParameters, + ); + } else { + clientMessage = liveConnectParametersToMldev( + this.apiClient, + liveConnectParameters, + ); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a) { + throw new Error( + `Failed to parse client content "turns", type: '${typeof params.turns}'`, + ); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if ( + typeof functionResponse !== "object" || + functionResponse === null || + !("name" in functionResponse) || + !("response" in functionResponse) + ) { + throw new Error( + `Could not parse function response, type '${typeof functionResponse}'.`, + ); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign( + Object.assign({}, defaultLiveSendClientContentParamerters), + params, + ); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToVertex(params), + }; + } else { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ( + (_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.disable + ) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = + config === null || config === void 0 ? void 0 : config.tools) !== null && + _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = + (_c = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _c === void 0 + ? void 0 + : _c.maximumRemoteCalls; + if ( + (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0 + ) { + 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:", + maxCalls, + ); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error( + "Automatic function calling with CallableTools and Tools is not yet supported.", + ); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents( + transformedParams.contents, + ); + const maxRemoteCalls = + (_c = + (_b = + (_a = transformedParams.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.tools) !== null && _e !== void 0 + ? _e + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if ( + apiResponse === null || apiResponse === void 0 + ? void 0 + : apiResponse.generatedImages + ) { + for (const generatedImage of apiResponse.generatedImages) { + if ( + generatedImage && + (generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) && + ((_a = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) === null || _a === void 0 + ? void 0 + : _a.contentType) === "Positive Prompt" + ) { + positivePromptSafetyAttributes = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign( + Object.assign({}, defaultConfig), + params === null || params === void 0 ? void 0 : params.config, + ); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ( + (_a = actualParams.config) === null || _a === void 0 + ? void 0 + : _a.filter + ) { + throw new Error( + "Filtering tuned models list for Vertex AI is not currently supported", + ); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager( + PagedItem.PAGED_ITEM_MODELS, + (x) => this.listInternal(x), + await this.listInternal(actualParams), + actualParams, + ); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => + img.toReferenceImageAPI(), + ); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale", + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all( + tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + }), + ); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { + tools: transformedTools, + }), + }; + newParams.config.tools = transformedTools; + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + const headers = + (_c = + (_b = params.config.httpOptions) === null || _b === void 0 + ? void 0 + : _b.headers) !== null && _c !== void 0 + ? _c + : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign( + Object.assign({}, params.config.httpOptions), + { headers: newHeaders }, + ); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== + null && _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = + toolDeclaration.functionDeclarations) !== null && _c !== void 0 + ? _c + : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error( + `Duplicate tool declaration name: ${declaration.name}`, + ); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = + (_c = + (_b = + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await( + models.processParamsMaybeAddMcpUsage(params), + ); + const response = yield __await( + models.generateContentStreamInternal(transformedParams), + ); + const functionResponses = []; + const responseContents = []; + try { + for ( + var _f = true, + response_1 = ((e_1 = void 0), __asyncValues(response)), + response_1_1; + (response_1_1 = yield __await(response_1.next())), + (_c = response_1_1.done), + !_c; + _f = true + ) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if ( + chunk.candidates && + ((_a = chunk.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content) + ) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== + null && _b !== void 0 + ? _b + : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error( + "Function call name was not returned by the model.", + ); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error( + `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`, + ); + } else { + const responseParts = yield __await( + afcTools + .get(part.functionCall.name) + .callTool([part.functionCall]), + ); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = response_1.return)) + yield __await(_d.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat( + newContents, + ); + params.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for ( + var _d = true, + apiResponse_1 = __asyncValues(apiResponse), + apiResponse_1_1; + (apiResponse_1_1 = yield __await(apiResponse_1.next())), + (_a = apiResponse_1_1.done), + !_a; + _d = true + ) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) + yield __await(_b.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for ( + var _d = true, + apiResponse_2 = __asyncValues(apiResponse), + apiResponse_2_1; + (apiResponse_2_1 = yield __await(apiResponse_2.next())), + (_a = apiResponse_2_1.done), + !_a; + _d = true + ) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) + yield __await(_b.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex( + this.apiClient, + params, + ); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev(fromProactivity), + ); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + "newSessionExpireTime", + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath( + parentObject, + ["newSessionExpireTime"], + fromNewSessionExpireTime, + ); + } + const fromUses = getValueByPath(fromObject, ["uses"]); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + "liveConnectConstraints", + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath( + parentObject, + ["bidiGenerateContentSetup"], + liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints), + ); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + "lockAdditionalFields", + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createAuthTokenConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if ( + typeof value === "object" && + value != null && + Object.keys(value).length > 0 + ) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); // 1st layer + } + } + } + return fields.join(","); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if ( + typeof bidiGenerateContentSetupValue === "object" && + bidiGenerateContentSetupValue !== null && + "setup" in bidiGenerateContentSetupValue + ) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + // Valid inner setup found. + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if ( + Array.isArray( + config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields, + ) && + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields.length) === 0 + ) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; // If mask is empty, effectively no + // specific fields locked by bidi + } + } else if ( + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig", + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict["fieldMask"]; + } + } else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict["fieldMask"]; + } + } else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if ( + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "The client.tokens.create method is only supported by the Gemini Developer API.", + ); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = "x-goog-api-key"; +const REQUIRED_VERTEX_AI_SCOPE = + "https://www.googleapis.com/auth/cloud-platform"; +class NodeAuth { + constructor(opts) { + if (opts.apiKey !== undefined) { + this.apiKey = opts.apiKey; + return; + } + const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions); + this.googleAuth = new GoogleAuth(vertexAuthOptions); + } + async addAuthHeaders(headers) { + if (this.apiKey !== undefined) { + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + this.addKeyHeader(headers); + return; + } + return this.addGoogleAuthHeaders(headers); + } + addKeyHeader(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey === undefined) { + // This should never happen, this method is only called + // when apiKey is set. + throw new Error("Trying to set API key header but apiKey is not set"); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } + async addGoogleAuthHeaders(headers) { + if (this.googleAuth === undefined) { + // This should never happen, addGoogleAuthHeaders should only be + // called when there is no apiKey set and in these cases googleAuth + // is set. + throw new Error( + "Trying to set google-auth headers but googleAuth is unset", + ); + } + const authHeaders = await this.googleAuth.getRequestHeaders(); + for (const key in authHeaders) { + if (headers.get(key) !== null) { + continue; + } + headers.append(key, authHeaders[key]); + } + } +} +function buildGoogleAuthOptions(googleAuthOptions) { + let authOptions; + if (!googleAuthOptions) { + authOptions = { + scopes: [REQUIRED_VERTEX_AI_SCOPE], + }; + return authOptions; + } else { + authOptions = googleAuthOptions; + if (!authOptions.scopes) { + authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE]; + return authOptions; + } else if ( + (typeof authOptions.scopes === "string" && + authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) || + (Array.isArray(authOptions.scopes) && + authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0) + ) { + throw new Error( + `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`, + ); + } + return authOptions; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeDownloader { + async download(params, apiClient) { + if (params.downloadPath) { + const response = await downloadFile(params, apiClient); + if (response instanceof HttpResponse) { + const writer = createWriteStream(params.downloadPath); + Readable.fromWeb(response.responseInternal.body).pipe(writer); + } else { + writeFile( + params.downloadPath, + response, + { encoding: "base64" }, + (error) => { + if (error) { + throw new Error( + `Failed to write file to ${params.downloadPath}: ${error}`, + ); + } + }, + ); + } + } + } +} +async function downloadFile(params, apiClient) { + var _a, _b, _c; + const name = tFileName(params.file); + if (name !== undefined) { + return await apiClient.request({ + path: `files/${name}:download`, + httpMethod: "GET", + queryParams: { + alt: "media", + }, + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else if (isGeneratedVideo(params.file)) { + const videoBytes = + (_c = params.file.video) === null || _c === void 0 + ? void 0 + : _c.videoBytes; + if (typeof videoBytes === "string") { + return videoBytes; + } else { + throw new Error( + "Failed to download generated video, Uri or videoBytes not found.", + ); + } + } else if (isVideo(params.file)) { + const videoBytes = params.file.videoBytes; + if (typeof videoBytes === "string") { + return videoBytes; + } else { + throw new Error("Failed to download video, Uri or videoBytes not found."); + } + } else { + throw new Error("Unsupported file type"); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeWebSocketFactory { + create(url, headers, callbacks) { + return new NodeWebSocket(url, headers, callbacks); + } +} +class NodeWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new NodeWs.WebSocket(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(message) { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ["textInput"]); + if (fromTextInput != null) { + setValueByPath(toObject, ["textInput"], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ["output"]); + if (fromOutput != null) { + setValueByPath(toObject, ["output"], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== undefined) { + throw new Error( + "vertexDatasetResource parameter is not supported in Gemini API.", + ); + } + const fromExamples = getValueByPath(fromObject, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["validationDataset"]) !== undefined) { + throw new Error( + "validationDataset parameter is not supported in Gemini API.", + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ["description"]) !== undefined) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath( + toObject, + ["tuningTask", "hyperparameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== undefined) { + throw new Error( + "exportLastCheckpointOnly parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["adapterSize"]) !== undefined) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject, ["batchSize"]); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "batchSize"], + fromBatchSize, + ); + } + const fromLearningRate = getValueByPath(fromObject, ["learningRate"]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "learningRate"], + fromLearningRate, + ); + } + return toObject; +} +function createTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["tuningTask", "trainingData"], + tuningDatasetToMldev(fromTrainingDataset), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromGcsUri, + ); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + if (getValueByPath(fromObject, ["examples"]) !== undefined) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + "validationDataset", + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec"], + tuningValidationDatasetToVertex(fromValidationDataset, toObject), + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath( + parentObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + "exportLastCheckpointOnly", + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "exportLastCheckpointOnly"], + fromExportLastCheckpointOnly, + ); + } + const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "adapterSize"], + fromAdapterSize, + ); + } + if (getValueByPath(fromObject, ["batchSize"]) !== undefined) { + throw new Error("batchSize parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["learningRate"]) !== undefined) { + throw new Error("learningRate parameter is not supported in Vertex AI."); + } + return toObject; +} +function createTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + tuningDatasetToVertex(fromTrainingDataset, toObject), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["tuningTask", "startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + "tuningTask", + "completeTime", + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["_self"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromMldev(fromTunedModel), + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromVertex(fromTunedModel), + ); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + "supervisedTuningSpec", + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec"], + fromSupervisedTuningSpec, + ); + } + const fromTuningDataStats = getValueByPath(fromObject, ["tuningDataStats"]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, ["encryptionSpec"]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + "partnerModelTuningSpec", + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath( + toObject, + ["partnerModelTuningSpec"], + fromPartnerModelTuningSpec, + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_TUNING_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + return await this.tuneInternal(params); + } else { + const operation = await this.tuneMldevInternal(params); + let tunedModelName = ""; + if ( + operation["metadata"] !== undefined && + operation["metadata"]["tunedModel"] !== undefined + ) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if ( + operation["name"] !== undefined && + operation["name"].includes("/operations/") + ) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createTuningJobParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 ? void 0 : response.headers) === + null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class NodeUploader { + async stat(file) { + const fileStat = { size: 0, type: undefined }; + if (typeof file === "string") { + const originalStat = await fs.stat(file); + fileStat.size = originalStat.size; + fileStat.type = this.inferMimeType(file); + return fileStat; + } else { + return await getBlobStat(file); + } + } + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + return await this.uploadFileFromPath(file, uploadUrl, apiClient); + } else { + return uploadBlob(file, uploadUrl, apiClient); + } + } + /** + * Infers the MIME type of a file based on its extension. + * + * @param filePath The path to the file. + * @returns The MIME type of the file, or undefined if it cannot be inferred. + */ + inferMimeType(filePath) { + // Get the file extension. + const fileExtension = filePath.slice(filePath.lastIndexOf(".") + 1); + // Create a map of file extensions to MIME types. + const mimeTypes = { + 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", + }; + // Look up the MIME type based on the file extension. + const mimeType = mimeTypes[fileExtension.toLowerCase()]; + // Return the MIME type. + return mimeType; + } + async uploadFileFromPath(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + let fileHandle; + try { + fileHandle = await fs.open(file, "r"); + if (!fileHandle) { + throw new Error(`Failed to open file`); + } + fileSize = (await fileHandle.stat()).size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + const buffer = new Uint8Array(chunkSize); + const { bytesRead: bytesRead } = await fileHandle.read( + buffer, + 0, + chunkSize, + offset, + ); + if (bytesRead !== chunkSize) { + throw new Error( + `Failed to read ${chunkSize} bytes from file at offset ${offset}. bytes actually read: ${bytesRead}`, + ); + } + const chunk = new Blob([buffer]); + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(bytesRead), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += bytesRead; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error( + "Failed to upload file: Upload status is not finalized.", + ); + } + return responseJson["file"]; + } finally { + // Ensure the file handle is always closed + if (fileHandle) { + await fileHandle.close(); + } + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = "gl-node/"; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a, _b, _c, _d, _e, _f; + // Validate explicitly set initializer values. + if ((options.project || options.location) && options.apiKey) { + throw new Error( + "Project/location and API key are mutually exclusive in the client initializer.", + ); + } + this.vertexai = + (_b = + (_a = options.vertexai) !== null && _a !== void 0 + ? _a + : getBooleanEnv("GOOGLE_GENAI_USE_VERTEXAI")) !== null && + _b !== void 0 + ? _b + : false; + const envApiKey = getApiKeyFromEnv(); + const envProject = getEnv("GOOGLE_CLOUD_PROJECT"); + const envLocation = getEnv("GOOGLE_CLOUD_LOCATION"); + this.apiKey = + (_c = options.apiKey) !== null && _c !== void 0 ? _c : envApiKey; + this.project = + (_d = options.project) !== null && _d !== void 0 ? _d : envProject; + this.location = + (_e = options.location) !== null && _e !== void 0 ? _e : envLocation; + // Handle when to use Vertex AI in express mode (api key) + if (options.vertexai) { + if ( + (_f = options.googleAuthOptions) === null || _f === void 0 + ? void 0 + : _f.credentials + ) { + // Explicit credentials take precedence over implicit api_key. + console.debug( + "The user provided Google Cloud credentials will take precedence" + + " over the API key from the environment variable.", + ); + this.apiKey = undefined; + } + // Explicit api_key and explicit project/location already handled above. + if ((envProject || envLocation) && options.apiKey) { + // Explicit api_key takes precedence over implicit project/location. + console.debug( + "The user provided Vertex AI API key will take precedence over" + + " the project/location from the environment variables.", + ); + this.project = undefined; + this.location = undefined; + } else if ((options.project || options.location) && envApiKey) { + // Explicit project/location takes precedence over implicit api_key. + console.debug( + "The user provided project/location will take precedence over" + + " the API key from the environment variables.", + ); + this.apiKey = undefined; + } else if ((envProject || envLocation) && envApiKey) { + // Implicit project/location takes precedence over implicit api_key. + console.debug( + "The project/location from the environment variables will take" + + " precedence over the API key from the environment variables.", + ); + this.apiKey = undefined; + } + } + const baseUrl = getBaseUrl( + options.httpOptions, + options.vertexai, + getEnv("GOOGLE_VERTEX_BASE_URL"), + getEnv("GOOGLE_GEMINI_BASE_URL"), + ); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new NodeAuth({ + apiKey: this.apiKey, + googleAuthOptions: options.googleAuthOptions, + }); + this.apiClient = new ApiClient({ + auth: auth, + project: this.project, + location: this.location, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version, + uploader: new NodeUploader(), + downloader: new NodeDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} +function getEnv(env) { + var _a, _b, _c; + return (_c = + (_b = + (_a = process === null || process === void 0 ? void 0 : process.env) === + null || _a === void 0 + ? void 0 + : _a[env]) === null || _b === void 0 + ? void 0 + : _b.trim()) !== null && _c !== void 0 + ? _c + : undefined; +} +function getBooleanEnv(env) { + return stringToBoolean(getEnv(env)); +} +function stringToBoolean(str) { + if (str === undefined) { + return false; + } + return str.toLowerCase() === "true"; +} +function getApiKeyFromEnv() { + const envGoogleApiKey = getEnv("GOOGLE_API_KEY"); + const envGeminiApiKey = getEnv("GEMINI_API_KEY"); + if (envGoogleApiKey && envGeminiApiKey) { + console.warn( + "Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.", + ); + } + return envGoogleApiKey || envGeminiApiKey; +} + +export { + ActivityHandling, + AdapterSize, + ApiError, + ApiSpec, + AuthType, + Batches, + Behavior, + BlockedReason, + Caches, + Chat, + Chats, + ComputeTokensResponse, + ControlReferenceImage, + ControlReferenceType, + CountTokensResponse, + CreateFileResponse, + DeleteCachedContentResponse, + DeleteFileResponse, + DeleteModelResponse, + DynamicRetrievalConfigMode, + EditImageResponse, + EditMode, + EmbedContentResponse, + EndSensitivity, + Environment, + FeatureSelectionPreference, + FileSource, + FileState, + Files, + FinishReason, + FunctionCallingConfigMode, + FunctionResponse, + FunctionResponseScheduling, + GenerateContentResponse, + GenerateContentResponsePromptFeedback, + GenerateContentResponseUsageMetadata, + GenerateImagesResponse, + GenerateVideosOperation, + GenerateVideosResponse, + GoogleGenAI, + HarmBlockMethod, + HarmBlockThreshold, + HarmCategory, + HarmProbability, + HarmSeverity, + HttpResponse, + ImagePromptLanguage, + InlinedResponse, + JobState, + Language, + ListBatchJobsResponse, + ListCachedContentsResponse, + ListFilesResponse, + ListModelsResponse, + ListTuningJobsResponse, + Live, + LiveClientToolResponse, + LiveMusicPlaybackControl, + LiveMusicServerMessage, + LiveSendToolResponseParameters, + LiveServerMessage, + MaskReferenceImage, + MaskReferenceMode, + MediaModality, + MediaResolution, + Modality, + Mode, + Models, + Operations, + Outcome, + PagedItem, + Pager, + PersonGeneration, + RawReferenceImage, + ReplayResponse, + SafetyFilterLevel, + Scale, + Session, + StartSensitivity, + StyleReferenceImage, + SubjectReferenceImage, + SubjectReferenceType, + Tokens, + TrafficType, + TurnCoverage, + Type, + UpscaleImageResponse, + UrlRetrievalStatus, + VideoCompressionQuality, + createModelContent, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromText, + createPartFromUri, + createUserContent, + mcpToTool, + setDefaultBaseUrls, +}; +//# sourceMappingURL=index.mjs.map diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs.map b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs.map new file mode 100644 index 0000000..ec4b7c9 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/node/_node_auth.ts","../../src/node/_node_downloader.ts","../../src/node/_node_websocket.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/cross/_cross_uploader.ts","../../src/node/_node_uploader.ts","../../src/node/node_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** Required. The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */\n data?: Part[];\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Computer Use tool type. */\nexport declare interface ToolComputerUse {\n /** A list of predefined functions that the should not be prepopulated. */\n excludedPredefinedFunctions?: string[];\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** \n Tool to support the model interacting directly with the computer.\n If enabled, it automatically populates computer-use specific Function\n Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** Hyperparameters for Distillation. */\nexport declare interface DistillationHyperParameters {\n /** Optional. Adapter size for distillation. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Distillation. */\nexport declare interface DistillationSpec {\n /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseTeacherModel?: string;\n /** Optional. Hyperparameters for Distillation. */\n hyperParameters?: DistillationHyperParameters;\n /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */\n pipelineRootDirectory?: string;\n /** The student model that is being tuned, e.g., \"google/gemma-2b-1.1-it\". Deprecated. Use base_model instead. */\n studentModel?: string;\n /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */\n tunedTeacherModelSource?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Tuning Spec for Distillation. */\n distillationSpec?: DistillationSpec;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** Output only. Reserved for future use. */\n satisfiesPzi?: boolean;\n /** Output only. Reserved for future use. */\n satisfiesPzs?: boolean;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-1.0-pro-002\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (!part.thought && part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['data']) !== undefined) {\n throw new Error('data parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['imageSize']) !== undefined) {\n throw new Error('imageSize parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.11.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const defaultHeaders = this.apiClient.getDefaultHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(defaultHeaders);\n }\n const headers = mapToHeaders(defaultHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"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.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n '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).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuth, GoogleAuthOptions} from 'google-auth-library';\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\nconst REQUIRED_VERTEX_AI_SCOPE =\n 'https://www.googleapis.com/auth/cloud-platform';\n\nexport interface NodeAuthOptions {\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. These are the authentication options provided by google-auth-library for Vertex AI users.\n * Complete list of authentication options are documented in the\n * GoogleAuthOptions interface:\n * https://github.com/googleapis/google-auth-library-nodejs/blob/main/src/auth/googleauth.ts.\n */\n googleAuthOptions?: GoogleAuthOptions;\n}\n\nexport class NodeAuth implements Auth {\n private readonly googleAuth?: GoogleAuth;\n private readonly apiKey?: string;\n\n constructor(opts: NodeAuthOptions) {\n if (opts.apiKey !== undefined) {\n this.apiKey = opts.apiKey;\n return;\n }\n const vertexAuthOptions = buildGoogleAuthOptions(opts.googleAuthOptions);\n this.googleAuth = new GoogleAuth(vertexAuthOptions);\n }\n\n async addAuthHeaders(headers: Headers): Promise {\n if (this.apiKey !== undefined) {\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n this.addKeyHeader(headers);\n return;\n }\n\n return this.addGoogleAuthHeaders(headers);\n }\n\n private addKeyHeader(headers: Headers) {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n if (this.apiKey === undefined) {\n // This should never happen, this method is only called\n // when apiKey is set.\n throw new Error('Trying to set API key header but apiKey is not set');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n\n private async addGoogleAuthHeaders(headers: Headers): Promise {\n if (this.googleAuth === undefined) {\n // This should never happen, addGoogleAuthHeaders should only be\n // called when there is no apiKey set and in these cases googleAuth\n // is set.\n throw new Error(\n 'Trying to set google-auth headers but googleAuth is unset',\n );\n }\n const authHeaders = await this.googleAuth.getRequestHeaders();\n for (const key in authHeaders) {\n if (headers.get(key) !== null) {\n continue;\n }\n headers.append(key, authHeaders[key]);\n }\n }\n}\n\nfunction buildGoogleAuthOptions(\n googleAuthOptions?: GoogleAuthOptions,\n): GoogleAuthOptions {\n let authOptions: GoogleAuthOptions;\n if (!googleAuthOptions) {\n authOptions = {\n scopes: [REQUIRED_VERTEX_AI_SCOPE],\n };\n return authOptions;\n } else {\n authOptions = googleAuthOptions;\n if (!authOptions.scopes) {\n authOptions.scopes = [REQUIRED_VERTEX_AI_SCOPE];\n return authOptions;\n } else if (\n (typeof authOptions.scopes === 'string' &&\n authOptions.scopes !== REQUIRED_VERTEX_AI_SCOPE) ||\n (Array.isArray(authOptions.scopes) &&\n authOptions.scopes.indexOf(REQUIRED_VERTEX_AI_SCOPE) < 0)\n ) {\n throw new Error(\n `Invalid auth scopes. Scopes must include: ${REQUIRED_VERTEX_AI_SCOPE}`,\n );\n }\n return authOptions;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {createWriteStream, writeFile} from 'fs';\nimport {Readable} from 'node:stream';\nimport type {ReadableStream} from 'node:stream/web';\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {isGeneratedVideo, isVideo, tFileName} from '../_transformers.js';\nimport {\n DownloadFileParameters,\n GeneratedVideo,\n HttpResponse,\n Video,\n} from '../types.js';\n\nexport class NodeDownloader implements Downloader {\n async download(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n ): Promise {\n if (params.downloadPath) {\n const response = await downloadFile(params, apiClient);\n if (response instanceof HttpResponse) {\n const writer = createWriteStream(params.downloadPath);\n Readable.fromWeb(\n response.responseInternal.body as ReadableStream,\n ).pipe(writer);\n } else {\n writeFile(\n params.downloadPath,\n response as string,\n {encoding: 'base64'},\n (error) => {\n if (error) {\n throw new Error(\n `Failed to write file to ${params.downloadPath}: ${error}`,\n );\n }\n },\n );\n }\n }\n }\n}\n\nasync function downloadFile(\n params: DownloadFileParameters,\n apiClient: ApiClient,\n): Promise {\n const name = tFileName(params.file);\n if (name !== undefined) {\n return await apiClient.request({\n path: `files/${name}:download`,\n httpMethod: 'GET',\n queryParams: {\n 'alt': 'media',\n },\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else if (isGeneratedVideo(params.file)) {\n const videoBytes = (params.file as GeneratedVideo).video?.videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error(\n 'Failed to download generated video, Uri or videoBytes not found.',\n );\n }\n } else if (isVideo(params.file)) {\n const videoBytes = (params.file as Video).videoBytes;\n if (typeof videoBytes === 'string') {\n return videoBytes;\n } else {\n throw new Error('Failed to download video, Uri or videoBytes not found.');\n }\n } else {\n throw new Error('Unsupported file type');\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as NodeWs from 'ws';\n\nimport {\n WebSocket,\n WebSocketCallbacks,\n WebSocketFactory,\n} from '../_websocket.js';\n\nexport class NodeWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): WebSocket {\n return new NodeWebSocket(url, headers, callbacks);\n }\n}\n\nexport class NodeWebSocket implements WebSocket {\n private ws?: NodeWs.WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new NodeWs.WebSocket(this.url, {headers: this.headers});\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToMldev(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToVertex(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n return await this.tuneInternal(params);\n } else {\n const operation = await this.tuneMldevInternal(params);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport * as fs from 'fs/promises';\n\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {\n DELAY_MULTIPLIER,\n INITIAL_RETRY_DELAY_MS,\n MAX_CHUNK_SIZE,\n MAX_RETRY_COUNT,\n X_GOOG_UPLOAD_STATUS_HEADER_FIELD,\n getBlobStat,\n sleep,\n uploadBlob,\n} from '../cross/_cross_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nexport class NodeUploader implements Uploader {\n async stat(file: string | Blob): Promise {\n const fileStat: FileStat = {size: 0, type: undefined};\n if (typeof file === 'string') {\n const originalStat = await fs.stat(file);\n fileStat.size = originalStat.size;\n fileStat.type = this.inferMimeType(file);\n return fileStat;\n } else {\n return await getBlobStat(file);\n }\n }\n\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n return await this.uploadFileFromPath(file, uploadUrl, apiClient);\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n /**\n * Infers the MIME type of a file based on its extension.\n *\n * @param filePath The path to the file.\n * @returns The MIME type of the file, or undefined if it cannot be inferred.\n */\n private inferMimeType(filePath: string): string | undefined {\n // Get the file extension.\n const fileExtension = filePath.slice(filePath.lastIndexOf('.') + 1);\n\n // Create a map of file extensions to MIME types.\n const mimeTypes: {[key: string]: string} = {\n 'aac': 'audio/aac',\n 'abw': 'application/x-abiword',\n 'arc': 'application/x-freearc',\n 'avi': 'video/x-msvideo',\n 'azw': 'application/vnd.amazon.ebook',\n 'bin': 'application/octet-stream',\n 'bmp': 'image/bmp',\n 'bz': 'application/x-bzip',\n 'bz2': 'application/x-bzip2',\n 'csh': 'application/x-csh',\n 'css': 'text/css',\n 'csv': 'text/csv',\n 'doc': 'application/msword',\n 'docx':\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'eot': 'application/vnd.ms-fontobject',\n 'epub': 'application/epub+zip',\n 'gz': 'application/gzip',\n 'gif': 'image/gif',\n 'htm': 'text/html',\n 'html': 'text/html',\n 'ico': 'image/vnd.microsoft.icon',\n 'ics': 'text/calendar',\n 'jar': 'application/java-archive',\n 'jpeg': 'image/jpeg',\n 'jpg': 'image/jpeg',\n 'js': 'text/javascript',\n 'json': 'application/json',\n 'jsonld': 'application/ld+json',\n 'kml': 'application/vnd.google-earth.kml+xml',\n 'kmz': 'application/vnd.google-earth.kmz+xml',\n 'mjs': 'text/javascript',\n 'mp3': 'audio/mpeg',\n 'mp4': 'video/mp4',\n 'mpeg': 'video/mpeg',\n 'mpkg': 'application/vnd.apple.installer+xml',\n 'odt': 'application/vnd.oasis.opendocument.text',\n 'oga': 'audio/ogg',\n 'ogv': 'video/ogg',\n 'ogx': 'application/ogg',\n 'opus': 'audio/opus',\n 'otf': 'font/otf',\n 'png': 'image/png',\n 'pdf': 'application/pdf',\n 'php': 'application/x-httpd-php',\n 'ppt': 'application/vnd.ms-powerpoint',\n 'pptx':\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'rar': 'application/vnd.rar',\n 'rtf': 'application/rtf',\n 'sh': 'application/x-sh',\n 'svg': 'image/svg+xml',\n 'swf': 'application/x-shockwave-flash',\n 'tar': 'application/x-tar',\n 'tif': 'image/tiff',\n 'tiff': 'image/tiff',\n 'ts': 'video/mp2t',\n 'ttf': 'font/ttf',\n 'txt': 'text/plain',\n 'vsd': 'application/vnd.visio',\n 'wav': 'audio/wav',\n 'weba': 'audio/webm',\n 'webm': 'video/webm',\n 'webp': 'image/webp',\n 'woff': 'font/woff',\n 'woff2': 'font/woff2',\n 'xhtml': 'application/xhtml+xml',\n 'xls': 'application/vnd.ms-excel',\n 'xlsx':\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'xml': 'application/xml',\n 'xul': 'application/vnd.mozilla.xul+xml',\n 'zip': 'application/zip',\n '3gp': 'video/3gpp',\n '3g2': 'video/3gpp2',\n '7z': 'application/x-7z-compressed',\n };\n\n // Look up the MIME type based on the file extension.\n const mimeType = mimeTypes[fileExtension.toLowerCase()];\n\n // Return the MIME type.\n return mimeType;\n }\n\n private async uploadFileFromPath(\n file: string,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n let fileHandle: fs.FileHandle | undefined;\n try {\n fileHandle = await fs.open(file, 'r');\n if (!fileHandle) {\n throw new Error(`Failed to open file`);\n }\n fileSize = (await fileHandle.stat()).size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n const buffer = new Uint8Array(chunkSize);\n const {bytesRead: bytesRead} = await fileHandle.read(\n buffer,\n 0,\n chunkSize,\n offset,\n );\n\n if (bytesRead !== chunkSize) {\n throw new Error(\n `Failed to read ${chunkSize} bytes from file at offset ${\n offset\n }. bytes actually read: ${bytesRead}`,\n );\n }\n\n const chunk = new Blob([buffer]);\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(bytesRead),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += bytesRead;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (\n response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active'\n ) {\n break;\n }\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error(\n 'Failed to upload file: Upload status is not finalized.',\n );\n }\n return responseJson['file'] as File;\n } finally {\n // Ensure the file handle is always closed\n if (fileHandle) {\n await fileHandle.close();\n }\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {GoogleAuthOptions} from 'google-auth-library';\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {NodeAuth} from '../node/_node_auth.js';\nimport {NodeDownloader} from '../node/_node_downloader.js';\nimport {NodeWebSocketFactory} from '../node/_node_websocket.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {NodeUploader} from './_node_uploader.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} must be set, or a {@link\n * GoogleGenAIOptions.apiKey} must be set when using Express Mode.\n *\n * Explicitly passed in values in {@link GoogleGenAIOptions} will always take\n * precedence over environment variables. If both project/location and api_key\n * exist in the environment variables, the project/location will be used.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly googleAuthOptions?: GoogleAuthOptions;\n private readonly project?: string;\n private readonly location?: string;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n // Validate explicitly set initializer values.\n if ((options.project || options.location) && options.apiKey) {\n throw new Error(\n 'Project/location and API key are mutually exclusive in the client initializer.',\n );\n }\n\n this.vertexai =\n options.vertexai ?? getBooleanEnv('GOOGLE_GENAI_USE_VERTEXAI') ?? false;\n const envApiKey = getApiKeyFromEnv();\n const envProject = getEnv('GOOGLE_CLOUD_PROJECT');\n const envLocation = getEnv('GOOGLE_CLOUD_LOCATION');\n\n this.apiKey = options.apiKey ?? envApiKey;\n this.project = options.project ?? envProject;\n this.location = options.location ?? envLocation;\n\n // Handle when to use Vertex AI in express mode (api key)\n if (options.vertexai) {\n if (options.googleAuthOptions?.credentials) {\n // Explicit credentials take precedence over implicit api_key.\n console.debug(\n 'The user provided Google Cloud credentials will take precedence' +\n ' over the API key from the environment variable.',\n );\n this.apiKey = undefined;\n }\n // Explicit api_key and explicit project/location already handled above.\n if ((envProject || envLocation) && options.apiKey) {\n // Explicit api_key takes precedence over implicit project/location.\n console.debug(\n 'The user provided Vertex AI API key will take precedence over' +\n ' the project/location from the environment variables.',\n );\n this.project = undefined;\n this.location = undefined;\n } else if ((options.project || options.location) && envApiKey) {\n // Explicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The user provided project/location will take precedence over' +\n ' the API key from the environment variables.',\n );\n this.apiKey = undefined;\n } else if ((envProject || envLocation) && envApiKey) {\n // Implicit project/location takes precedence over implicit api_key.\n console.debug(\n 'The project/location from the environment variables will take' +\n ' precedence over the API key from the environment variables.',\n );\n this.apiKey = undefined;\n }\n }\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n getEnv('GOOGLE_VERTEX_BASE_URL'),\n getEnv('GOOGLE_GEMINI_BASE_URL'),\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new NodeAuth({\n apiKey: this.apiKey,\n googleAuthOptions: options.googleAuthOptions,\n });\n this.apiClient = new ApiClient({\n auth: auth,\n project: this.project,\n location: this.location,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + process.version,\n uploader: new NodeUploader(),\n downloader: new NodeDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new NodeWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n\nfunction getEnv(env: string): string | undefined {\n return process?.env?.[env]?.trim() ?? undefined;\n}\n\nfunction getBooleanEnv(env: string): boolean {\n return stringToBoolean(getEnv(env));\n}\n\nfunction stringToBoolean(str?: string): boolean {\n if (str === undefined) {\n return false;\n }\n return str.toLowerCase() === 'true';\n}\n\nfunction getApiKeyFromEnv(): string | undefined {\n const envGoogleApiKey = getEnv('GOOGLE_API_KEY');\n const envGeminiApiKey = getEnv('GEMINI_API_KEY');\n if (envGoogleApiKey && envGeminiApiKey) {\n console.warn(\n 'Both GOOGLE_API_KEY and GEMINI_API_KEY are set. Using GOOGLE_API_KEY.',\n );\n }\n return envGoogleApiKey || envGeminiApiKey;\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToVertex","common.formatMap","converters.batchJobFromVertex","converters.createBatchJobParametersToMldev","converters.batchJobFromMldev","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersToVertex","converters.createTuningJobParametersToMldev","converters.tuningOperationFromMldev"],"mappings":";;;;;;AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AA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EA,SAAS,aAAa,CAAC,GAAW,EAAA;AAChC,IAAA,OAAO,eAAe,CAAC,MAAM,CAAC,GAAG,CAAC,CAAC;AACrC;AAEA,SAAS,eAAe,CAAC,GAAY,EAAA;IACnC,IAAI,GAAG,KAAK,SAAS,EAAE;AACrB,QAAA,OAAO,KAAK;AACb;AACD,IAAA,OAAO,GAAG,CAAC,WAAW,EAAE,KAAK,MAAM;AACrC;AAEA,SAAS,gBAAgB,GAAA;AACvB,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;AAChD,IAAA,MAAM,eAAe,GAAG,MAAM,CAAC,gBAAgB,CAAC;IAChD,IAAI,eAAe,IAAI,eAAe,EAAE;AACtC,QAAA,OAAO,CAAC,IAAI,CACV,uEAAuE,CACxE;AACF;IACD,OAAO,eAAe,IAAI,eAAe;AAC3C;;;;"} \ No newline at end of file diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/node/node.d.ts b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/node.d.ts new file mode 100644 index 0000000..b889f01 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/node/node.d.ts @@ -0,0 +1,7429 @@ +// @ts-ignore +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { GoogleAuthOptions } from "google-auth-library"; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd {} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION", +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart {} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO", +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH", +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig {} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH", +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule {} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: ( + params?: types.ListBatchJobsParameters, + ) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteBatchJobParameters, + ): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = + | BatchJobSource + | InlinedRequest[] + | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING", +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob }; + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: ( + params?: types.ListCachedContentsParameters, + ) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create( + params: types.CreateCachedContentParameters, + ): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteCachedContentParameters, + ): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update( + params: types.UpdateCachedContentParameters, + ): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor( + apiClient: ApiClient, + modelsModule: Models, + model: string, + config?: types.GenerateContentConfig, + history?: types.Content[], + ); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage( + params: types.SendMessageParameters, + ): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream( + params: types.SendMessageParameters, + ): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = + | Content + | Content[] + | PartUnion + | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH", +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent( + partOrString: PartListUnion | string, +): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64( + data: string, + mimeType: string, +): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult( + outcome: Outcome, + output: string, +): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode( + code: string, + language: Language, +): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall( + name: string, + args: Record, +): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse( + id: string, + name: string, + response: Record, +): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-1.0-pro-002". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent( + partOrString: PartListUnion | string, +): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse {} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse {} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse {} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +/** Hyperparameters for Distillation. */ +export declare interface DistillationHyperParameters { + /** Optional. Adapter size for distillation. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; +} + +/** Tuning Spec for Distillation. */ +export declare interface DistillationSpec { + /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseTeacherModel?: string; + /** Optional. Hyperparameters for Distillation. */ + hyperParameters?: DistillationHyperParameters; + /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */ + pipelineRootDirectory?: string; + /** The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use base_model instead. */ + studentModel?: string; + /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */ + tunedTeacherModelSource?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type DownloadableFileUnion = + | string + | File_2 + | GeneratedVideo + | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE", +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW", +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch {} + +/** Required. The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER", +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams {} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST", +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File }; + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED", +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED", +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL", +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */ + data?: Part[]; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT", +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation + implements Operation +{ + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: + | "UNKNOWN" + | "PRIORITIZE_QUALITY" + | "BALANCED" + | "PRIORITIZE_COST"; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, both {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} must be set, or a {@link + * GoogleGenAIOptions.apiKey} must be set when using Express Mode. + * + * Explicitly passed in values in {@link GoogleGenAIOptions} will always take + * precedence over environment variables. If both project/location and api_key + * exist in the environment variables, the project/location will be used. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly googleAuthOptions?; + private readonly project?; + private readonly location?; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY", +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF", +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT", +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH", +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH", +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: "GET" | "POST" | "PATCH" | "DELETE"; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image }; + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es", +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED", +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON", +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT", +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete {} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts( + params: types.LiveMusicSetWeightedPromptsParameters, + ): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig( + params: types.LiveMusicSetConfigParameters, + ): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC", +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool( + ...args: [...Client[], CallableToolConfig | Client] +): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT", +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH", +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO", +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: ( + params: types.GenerateContentParameters, + ) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: ( + params: types.GenerateContentParameters, + ) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: ( + params: types.GenerateImagesParameters, + ) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: ( + params: types.EditImageParameters, + ) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: ( + params: types.UpscaleImageParameters, + ) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: ( + params: types.GenerateVideosParameters, + ) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent( + params: types.EmbedContentParameters, + ): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete( + params: types.DeleteModelParameters, + ): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens( + params: types.CountTokensParameters, + ): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens( + params: types.ComputeTokensParameters, + ): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation( + parameters: types.OperationGetParameters< + types.GenerateVideosResponse, + types.GenerateVideosOperation + >, + ): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>( + parameters: types.OperationGetParameters, + ): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED", +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents", +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: ( + params: PagedItemConfig, + ) => Promise>; + protected idxInternal: number; + constructor( + name: PagedItem, + request: (params: PagedItemConfig) => Promise>, + response: PagedItemResponse, + params: PagedItemConfig, + ); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL", +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +export declare type ReferenceImage = + | RawReferenceImage + | MaskReferenceImage + | ControlReferenceImage + | StyleReferenceImage + | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + 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", +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR", +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls( + baseUrlParams: BaseUrlParameters, +): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW", +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT", +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** + Tool to support the model interacting directly with the computer. + If enabled, it automatically populates computer-use specific Function + Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution {} + +/** Computer Use tool type. */ +export declare interface ToolComputerUse { + /** A list of predefined functions that the should not be prepopulated. */ + excludedPredefinedFunctions?: string[]; + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT", +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Tuning Spec for Distillation. */ + distillationSpec?: DistillationSpec; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** Output only. Reserved for future use. */ + satisfiesPzi?: boolean; + /** Output only. Reserved for future use. */ + satisfiesPzs?: boolean; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: ( + params?: types.ListTuningJobsParameters, + ) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT", +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL", +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + Environment, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + DistillationHyperParameters, + DistillationSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParameters, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveSendRealtimeInputParameters, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion, + }; +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload( + file: string | Blob, + uploadUrl: string, + apiClient: ApiClient, + ): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext {} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS", +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create( + url: string, + headers: Record, + callbacks: WebSocketCallbacks, + ): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export {}; diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs new file mode 100644 index 0000000..06b788a --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs @@ -0,0 +1,20379 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +let _defaultBaseGeminiUrl = undefined; +let _defaultBaseVertexUrl = undefined; +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +function setDefaultBaseUrls(baseUrlParams) { + _defaultBaseGeminiUrl = baseUrlParams.geminiUrl; + _defaultBaseVertexUrl = baseUrlParams.vertexUrl; +} +/** + * Returns the default base URLs for the Gemini API and Vertex AI API. + */ +function getDefaultBaseUrls() { + return { + geminiUrl: _defaultBaseGeminiUrl, + vertexUrl: _defaultBaseVertexUrl, + }; +} +/** + * Returns the default base URL based on the following priority: + * 1. Base URLs set via HttpOptions. + * 2. Base URLs set via the latest call to setDefaultBaseUrls. + * 3. Base URLs set via environment variables. + */ +function getBaseUrl( + httpOptions, + vertexai, + vertexBaseUrlFromEnv, + geminiBaseUrlFromEnv, +) { + var _a, _b; + if ( + !(httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.baseUrl) + ) { + const defaultBaseUrls = getDefaultBaseUrls(); + if (vertexai) { + return (_a = defaultBaseUrls.vertexUrl) !== null && _a !== void 0 + ? _a + : vertexBaseUrlFromEnv; + } else { + return (_b = defaultBaseUrls.geminiUrl) !== null && _b !== void 0 + ? _b + : geminiBaseUrlFromEnv; + } + } + return httpOptions.baseUrl; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BaseModule {} +function formatMap(templateString, valueMap) { + // Use a regular expression to find all placeholders in the template string + const regex = /\{([^}]+)\}/g; + // Replace each placeholder with its corresponding value from the valueMap + return templateString.replace(regex, (match, key) => { + if (Object.prototype.hasOwnProperty.call(valueMap, key)) { + const value = valueMap[key]; + // Convert the value to a string if it's not a string already + return value !== undefined && value !== null ? String(value) : ""; + } else { + // Handle missing keys + throw new Error(`Key '${key}' not found in valueMap.`); + } + }); +} +function setValueByPath(data, keys, value) { + for (let i = 0; i < keys.length - 1; i++) { + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (!(keyName in data)) { + if (Array.isArray(value)) { + data[keyName] = Array.from({ length: value.length }, () => ({})); + } else { + throw new Error(`Value must be a list given an array path ${key}`); + } + } + if (Array.isArray(data[keyName])) { + const arrayData = data[keyName]; + if (Array.isArray(value)) { + for (let j = 0; j < arrayData.length; j++) { + const entry = arrayData[j]; + setValueByPath(entry, keys.slice(i + 1), value[j]); + } + } else { + for (const d of arrayData) { + setValueByPath(d, keys.slice(i + 1), value); + } + } + } + return; + } else if (key.endsWith("[0]")) { + const keyName = key.slice(0, -3); + if (!(keyName in data)) { + data[keyName] = [{}]; + } + const arrayData = data[keyName]; + setValueByPath(arrayData[0], keys.slice(i + 1), value); + return; + } + if (!data[key] || typeof data[key] !== "object") { + data[key] = {}; + } + data = data[key]; + } + const keyToSet = keys[keys.length - 1]; + const existingData = data[keyToSet]; + if (existingData !== undefined) { + if ( + !value || + (typeof value === "object" && Object.keys(value).length === 0) + ) { + return; + } + if (value === existingData) { + return; + } + if ( + typeof existingData === "object" && + typeof value === "object" && + existingData !== null && + value !== null + ) { + Object.assign(existingData, value); + } else { + throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`); + } + } else { + data[keyToSet] = value; + } +} +function getValueByPath(data, keys) { + try { + if (keys.length === 1 && keys[0] === "_self") { + return data; + } + for (let i = 0; i < keys.length; i++) { + if (typeof data !== "object" || data === null) { + return undefined; + } + const key = keys[i]; + if (key.endsWith("[]")) { + const keyName = key.slice(0, -2); + if (keyName in data) { + const arrayData = data[keyName]; + if (!Array.isArray(arrayData)) { + return undefined; + } + return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1))); + } else { + return undefined; + } + } else { + data = data[key]; + } + } + return data; + } catch (error) { + if (error instanceof TypeError) { + return undefined; + } + throw error; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tBytes$1(fromBytes) { + if (typeof fromBytes !== "string") { + throw new Error("fromImageBytes must be a string"); + } + // TODO(b/389133914): Remove dummy bytes converter. + return fromBytes; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +/** Required. Outcome of the code execution. */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "OUTCOME_UNSPECIFIED"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "OUTCOME_OK"; + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + Outcome["OUTCOME_FAILED"] = "OUTCOME_FAILED"; + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "OUTCOME_DEADLINE_EXCEEDED"; +})(Outcome || (Outcome = {})); +/** Required. Programming language of the `code`. */ +var Language; +(function (Language) { + /** + * Unspecified language. This value should not be used. + */ + Language["LANGUAGE_UNSPECIFIED"] = "LANGUAGE_UNSPECIFIED"; + /** + * Python >= 3.10, with numpy and simpy available. + */ + Language["PYTHON"] = "PYTHON"; +})(Language || (Language = {})); +/** Optional. The type of the data. */ +var Type; +(function (Type) { + /** + * Not specified, should not be used. + */ + Type["TYPE_UNSPECIFIED"] = "TYPE_UNSPECIFIED"; + /** + * OpenAPI string type + */ + Type["STRING"] = "STRING"; + /** + * OpenAPI number type + */ + Type["NUMBER"] = "NUMBER"; + /** + * OpenAPI integer type + */ + Type["INTEGER"] = "INTEGER"; + /** + * OpenAPI boolean type + */ + Type["BOOLEAN"] = "BOOLEAN"; + /** + * OpenAPI array type + */ + Type["ARRAY"] = "ARRAY"; + /** + * OpenAPI object type + */ + Type["OBJECT"] = "OBJECT"; + /** + * Null type + */ + Type["NULL"] = "NULL"; +})(Type || (Type = {})); +/** Required. Harm category. */ +var HarmCategory; +(function (HarmCategory) { + /** + * The harm category is unspecified. + */ + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + /** + * The harm category is hate speech. + */ + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + /** + * The harm category is dangerous content. + */ + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_DANGEROUS_CONTENT"; + /** + * The harm category is harassment. + */ + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + /** + * The harm category is sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = + "HARM_CATEGORY_CIVIC_INTEGRITY"; + /** + * The harm category is image hate. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HATE"] = "HARM_CATEGORY_IMAGE_HATE"; + /** + * The harm category is image dangerous content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"] = + "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT"; + /** + * The harm category is image harassment. + */ + HarmCategory["HARM_CATEGORY_IMAGE_HARASSMENT"] = + "HARM_CATEGORY_IMAGE_HARASSMENT"; + /** + * The harm category is image sexually explicit content. + */ + HarmCategory["HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"] = + "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT"; +})(HarmCategory || (HarmCategory = {})); +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +var HarmBlockMethod; +(function (HarmBlockMethod) { + /** + * The harm block method is unspecified. + */ + HarmBlockMethod["HARM_BLOCK_METHOD_UNSPECIFIED"] = + "HARM_BLOCK_METHOD_UNSPECIFIED"; + /** + * The harm block method uses both probability and severity scores. + */ + HarmBlockMethod["SEVERITY"] = "SEVERITY"; + /** + * The harm block method uses the probability score. + */ + HarmBlockMethod["PROBABILITY"] = "PROBABILITY"; +})(HarmBlockMethod || (HarmBlockMethod = {})); +/** Required. The harm block threshold. */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** + * Unspecified harm block threshold. + */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = + "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** + * Block low threshold and above (i.e. block more). + */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** + * Block medium threshold and above. + */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** + * Block only high threshold (i.e. block less). + */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** + * Block none. + */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; + /** + * Turn off the safety filter. + */ + HarmBlockThreshold["OFF"] = "OFF"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** The mode of the predictor to be used in dynamic retrieval. */ +var Mode; +(function (Mode) { + /** + * Always trigger retrieval. + */ + Mode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + Mode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(Mode || (Mode = {})); +/** Type of auth scheme. */ +var AuthType; +(function (AuthType) { + AuthType["AUTH_TYPE_UNSPECIFIED"] = "AUTH_TYPE_UNSPECIFIED"; + /** + * No Auth. + */ + AuthType["NO_AUTH"] = "NO_AUTH"; + /** + * API Key Auth. + */ + AuthType["API_KEY_AUTH"] = "API_KEY_AUTH"; + /** + * HTTP Basic Auth. + */ + AuthType["HTTP_BASIC_AUTH"] = "HTTP_BASIC_AUTH"; + /** + * Google Service Account Auth. + */ + AuthType["GOOGLE_SERVICE_ACCOUNT_AUTH"] = "GOOGLE_SERVICE_ACCOUNT_AUTH"; + /** + * OAuth auth. + */ + AuthType["OAUTH"] = "OAUTH"; + /** + * OpenID Connect (OIDC) Auth. + */ + AuthType["OIDC_AUTH"] = "OIDC_AUTH"; +})(AuthType || (AuthType = {})); +/** Required. The environment being operated. */ +var Environment; +(function (Environment) { + /** + * Defaults to browser. + */ + Environment["ENVIRONMENT_UNSPECIFIED"] = "ENVIRONMENT_UNSPECIFIED"; + /** + * Operates in a web browser. + */ + Environment["ENVIRONMENT_BROWSER"] = "ENVIRONMENT_BROWSER"; +})(Environment || (Environment = {})); +/** The API spec that the external API implements. */ +var ApiSpec; +(function (ApiSpec) { + /** + * Unspecified API spec. This value should not be used. + */ + ApiSpec["API_SPEC_UNSPECIFIED"] = "API_SPEC_UNSPECIFIED"; + /** + * Simple search API spec. + */ + ApiSpec["SIMPLE_SEARCH"] = "SIMPLE_SEARCH"; + /** + * Elastic search API spec. + */ + ApiSpec["ELASTIC_SEARCH"] = "ELASTIC_SEARCH"; +})(ApiSpec || (ApiSpec = {})); +/** Status of the url retrieval. */ +var UrlRetrievalStatus; +(function (UrlRetrievalStatus) { + /** + * Default value. This value is unused + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_UNSPECIFIED"] = + "URL_RETRIEVAL_STATUS_UNSPECIFIED"; + /** + * Url retrieval is successful. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_SUCCESS"] = + "URL_RETRIEVAL_STATUS_SUCCESS"; + /** + * Url retrieval is failed due to error. + */ + UrlRetrievalStatus["URL_RETRIEVAL_STATUS_ERROR"] = + "URL_RETRIEVAL_STATUS_ERROR"; +})(UrlRetrievalStatus || (UrlRetrievalStatus = {})); +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +var FinishReason; +(function (FinishReason) { + /** + * The finish reason is unspecified. + */ + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + FinishReason["STOP"] = "STOP"; + /** + * Token generation reached the configured maximum output tokens. + */ + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + FinishReason["SAFETY"] = "SAFETY"; + /** + * The token generation stopped because of potential recitation. + */ + FinishReason["RECITATION"] = "RECITATION"; + /** + * The token generation stopped because of using an unsupported language. + */ + FinishReason["LANGUAGE"] = "LANGUAGE"; + /** + * All other reasons that stopped the token generation. + */ + FinishReason["OTHER"] = "OTHER"; + /** + * Token generation stopped because the content contains forbidden terms. + */ + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Token generation stopped for potentially containing prohibited content. + */ + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + FinishReason["SPII"] = "SPII"; + /** + * The function call generated by the model is invalid. + */ + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + /** + * Token generation stopped because generated images have safety violations. + */ + FinishReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; + /** + * The tool call generated by the model is invalid. + */ + FinishReason["UNEXPECTED_TOOL_CALL"] = "UNEXPECTED_TOOL_CALL"; +})(FinishReason || (FinishReason = {})); +/** Output only. Harm probability levels in the content. */ +var HarmProbability; +(function (HarmProbability) { + /** + * Harm probability unspecified. + */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = + "HARM_PROBABILITY_UNSPECIFIED"; + /** + * Negligible level of harm. + */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** + * Low level of harm. + */ + HarmProbability["LOW"] = "LOW"; + /** + * Medium level of harm. + */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** + * High level of harm. + */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** Output only. Harm severity levels in the content. */ +var HarmSeverity; +(function (HarmSeverity) { + /** + * Harm severity unspecified. + */ + HarmSeverity["HARM_SEVERITY_UNSPECIFIED"] = "HARM_SEVERITY_UNSPECIFIED"; + /** + * Negligible level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_NEGLIGIBLE"] = "HARM_SEVERITY_NEGLIGIBLE"; + /** + * Low level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_LOW"] = "HARM_SEVERITY_LOW"; + /** + * Medium level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_MEDIUM"] = "HARM_SEVERITY_MEDIUM"; + /** + * High level of harm severity. + */ + HarmSeverity["HARM_SEVERITY_HIGH"] = "HARM_SEVERITY_HIGH"; +})(HarmSeverity || (HarmSeverity = {})); +/** Output only. Blocked reason. */ +var BlockedReason; +(function (BlockedReason) { + /** + * Unspecified blocked reason. + */ + BlockedReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + /** + * Candidates blocked due to safety. + */ + BlockedReason["SAFETY"] = "SAFETY"; + /** + * Candidates blocked due to other reason. + */ + BlockedReason["OTHER"] = "OTHER"; + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BlockedReason["BLOCKLIST"] = "BLOCKLIST"; + /** + * Candidates blocked due to prohibited content. + */ + BlockedReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + /** + * Candidates blocked due to unsafe image generation content. + */ + BlockedReason["IMAGE_SAFETY"] = "IMAGE_SAFETY"; +})(BlockedReason || (BlockedReason = {})); +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +var TrafficType; +(function (TrafficType) { + /** + * Unspecified request traffic type. + */ + TrafficType["TRAFFIC_TYPE_UNSPECIFIED"] = "TRAFFIC_TYPE_UNSPECIFIED"; + /** + * Type for Pay-As-You-Go traffic. + */ + TrafficType["ON_DEMAND"] = "ON_DEMAND"; + /** + * Type for Provisioned Throughput traffic. + */ + TrafficType["PROVISIONED_THROUGHPUT"] = "PROVISIONED_THROUGHPUT"; +})(TrafficType || (TrafficType = {})); +/** Server content modalities. */ +var Modality; +(function (Modality) { + /** + * The modality is unspecified. + */ + Modality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Indicates the model should return text + */ + Modality["TEXT"] = "TEXT"; + /** + * Indicates the model should return images. + */ + Modality["IMAGE"] = "IMAGE"; + /** + * Indicates the model should return audio. + */ + Modality["AUDIO"] = "AUDIO"; +})(Modality || (Modality = {})); +/** The media resolution to use. */ +var MediaResolution; +(function (MediaResolution) { + /** + * Media resolution has not been set + */ + MediaResolution["MEDIA_RESOLUTION_UNSPECIFIED"] = + "MEDIA_RESOLUTION_UNSPECIFIED"; + /** + * Media resolution set to low (64 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_LOW"] = "MEDIA_RESOLUTION_LOW"; + /** + * Media resolution set to medium (256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_MEDIUM"] = "MEDIA_RESOLUTION_MEDIUM"; + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MediaResolution["MEDIA_RESOLUTION_HIGH"] = "MEDIA_RESOLUTION_HIGH"; +})(MediaResolution || (MediaResolution = {})); +/** Job state. */ +var JobState; +(function (JobState) { + /** + * The job state is unspecified. + */ + JobState["JOB_STATE_UNSPECIFIED"] = "JOB_STATE_UNSPECIFIED"; + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JobState["JOB_STATE_QUEUED"] = "JOB_STATE_QUEUED"; + /** + * The service is preparing to run the job. + */ + JobState["JOB_STATE_PENDING"] = "JOB_STATE_PENDING"; + /** + * The job is in progress. + */ + JobState["JOB_STATE_RUNNING"] = "JOB_STATE_RUNNING"; + /** + * The job completed successfully. + */ + JobState["JOB_STATE_SUCCEEDED"] = "JOB_STATE_SUCCEEDED"; + /** + * The job failed. + */ + JobState["JOB_STATE_FAILED"] = "JOB_STATE_FAILED"; + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JobState["JOB_STATE_CANCELLING"] = "JOB_STATE_CANCELLING"; + /** + * The job has been cancelled. + */ + JobState["JOB_STATE_CANCELLED"] = "JOB_STATE_CANCELLED"; + /** + * The job has been stopped, and can be resumed. + */ + JobState["JOB_STATE_PAUSED"] = "JOB_STATE_PAUSED"; + /** + * The job has expired. + */ + JobState["JOB_STATE_EXPIRED"] = "JOB_STATE_EXPIRED"; + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JobState["JOB_STATE_UPDATING"] = "JOB_STATE_UPDATING"; + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JobState["JOB_STATE_PARTIALLY_SUCCEEDED"] = "JOB_STATE_PARTIALLY_SUCCEEDED"; +})(JobState || (JobState = {})); +/** Optional. Adapter size for tuning. */ +var AdapterSize; +(function (AdapterSize) { + /** + * Adapter size is unspecified. + */ + AdapterSize["ADAPTER_SIZE_UNSPECIFIED"] = "ADAPTER_SIZE_UNSPECIFIED"; + /** + * Adapter size 1. + */ + AdapterSize["ADAPTER_SIZE_ONE"] = "ADAPTER_SIZE_ONE"; + /** + * Adapter size 2. + */ + AdapterSize["ADAPTER_SIZE_TWO"] = "ADAPTER_SIZE_TWO"; + /** + * Adapter size 4. + */ + AdapterSize["ADAPTER_SIZE_FOUR"] = "ADAPTER_SIZE_FOUR"; + /** + * Adapter size 8. + */ + AdapterSize["ADAPTER_SIZE_EIGHT"] = "ADAPTER_SIZE_EIGHT"; + /** + * Adapter size 16. + */ + AdapterSize["ADAPTER_SIZE_SIXTEEN"] = "ADAPTER_SIZE_SIXTEEN"; + /** + * Adapter size 32. + */ + AdapterSize["ADAPTER_SIZE_THIRTY_TWO"] = "ADAPTER_SIZE_THIRTY_TWO"; +})(AdapterSize || (AdapterSize = {})); +/** Options for feature selection preference. */ +var FeatureSelectionPreference; +(function (FeatureSelectionPreference) { + FeatureSelectionPreference["FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"] = + "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED"; + FeatureSelectionPreference["PRIORITIZE_QUALITY"] = "PRIORITIZE_QUALITY"; + FeatureSelectionPreference["BALANCED"] = "BALANCED"; + FeatureSelectionPreference["PRIORITIZE_COST"] = "PRIORITIZE_COST"; +})(FeatureSelectionPreference || (FeatureSelectionPreference = {})); +/** Defines the function behavior. Defaults to `BLOCKING`. */ +var Behavior; +(function (Behavior) { + /** + * This value is unused. + */ + Behavior["UNSPECIFIED"] = "UNSPECIFIED"; + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + Behavior["BLOCKING"] = "BLOCKING"; + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + Behavior["NON_BLOCKING"] = "NON_BLOCKING"; +})(Behavior || (Behavior = {})); +/** Config for the dynamic retrieval config mode. */ +var DynamicRetrievalConfigMode; +(function (DynamicRetrievalConfigMode) { + /** + * Always trigger retrieval. + */ + DynamicRetrievalConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Run retrieval only when system decides it is necessary. + */ + DynamicRetrievalConfigMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalConfigMode || (DynamicRetrievalConfigMode = {})); +/** Config for the function calling config mode. */ +var FunctionCallingConfigMode; +(function (FunctionCallingConfigMode) { + /** + * The function calling config mode is unspecified. Should not be used. + */ + FunctionCallingConfigMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + FunctionCallingConfigMode["AUTO"] = "AUTO"; + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + FunctionCallingConfigMode["ANY"] = "ANY"; + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + FunctionCallingConfigMode["NONE"] = "NONE"; +})(FunctionCallingConfigMode || (FunctionCallingConfigMode = {})); +/** Enum that controls the safety filter level for objectionable content. */ +var SafetyFilterLevel; +(function (SafetyFilterLevel) { + SafetyFilterLevel["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + SafetyFilterLevel["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + SafetyFilterLevel["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + SafetyFilterLevel["BLOCK_NONE"] = "BLOCK_NONE"; +})(SafetyFilterLevel || (SafetyFilterLevel = {})); +/** Enum that controls the generation of people. */ +var PersonGeneration; +(function (PersonGeneration) { + /** + * Block generation of images of people. + */ + PersonGeneration["DONT_ALLOW"] = "DONT_ALLOW"; + /** + * Generate images of adults, but not children. + */ + PersonGeneration["ALLOW_ADULT"] = "ALLOW_ADULT"; + /** + * Generate images that include adults and children. + */ + PersonGeneration["ALLOW_ALL"] = "ALLOW_ALL"; +})(PersonGeneration || (PersonGeneration = {})); +/** Enum that specifies the language of the text in the prompt. */ +var ImagePromptLanguage; +(function (ImagePromptLanguage) { + /** + * Auto-detect the language. + */ + ImagePromptLanguage["auto"] = "auto"; + /** + * English + */ + ImagePromptLanguage["en"] = "en"; + /** + * Japanese + */ + ImagePromptLanguage["ja"] = "ja"; + /** + * Korean + */ + ImagePromptLanguage["ko"] = "ko"; + /** + * Hindi + */ + ImagePromptLanguage["hi"] = "hi"; + /** + * Chinese + */ + ImagePromptLanguage["zh"] = "zh"; + /** + * Portuguese + */ + ImagePromptLanguage["pt"] = "pt"; + /** + * Spanish + */ + ImagePromptLanguage["es"] = "es"; +})(ImagePromptLanguage || (ImagePromptLanguage = {})); +/** Enum representing the mask mode of a mask reference image. */ +var MaskReferenceMode; +(function (MaskReferenceMode) { + MaskReferenceMode["MASK_MODE_DEFAULT"] = "MASK_MODE_DEFAULT"; + MaskReferenceMode["MASK_MODE_USER_PROVIDED"] = "MASK_MODE_USER_PROVIDED"; + MaskReferenceMode["MASK_MODE_BACKGROUND"] = "MASK_MODE_BACKGROUND"; + MaskReferenceMode["MASK_MODE_FOREGROUND"] = "MASK_MODE_FOREGROUND"; + MaskReferenceMode["MASK_MODE_SEMANTIC"] = "MASK_MODE_SEMANTIC"; +})(MaskReferenceMode || (MaskReferenceMode = {})); +/** Enum representing the control type of a control reference image. */ +var ControlReferenceType; +(function (ControlReferenceType) { + ControlReferenceType["CONTROL_TYPE_DEFAULT"] = "CONTROL_TYPE_DEFAULT"; + ControlReferenceType["CONTROL_TYPE_CANNY"] = "CONTROL_TYPE_CANNY"; + ControlReferenceType["CONTROL_TYPE_SCRIBBLE"] = "CONTROL_TYPE_SCRIBBLE"; + ControlReferenceType["CONTROL_TYPE_FACE_MESH"] = "CONTROL_TYPE_FACE_MESH"; +})(ControlReferenceType || (ControlReferenceType = {})); +/** Enum representing the subject type of a subject reference image. */ +var SubjectReferenceType; +(function (SubjectReferenceType) { + SubjectReferenceType["SUBJECT_TYPE_DEFAULT"] = "SUBJECT_TYPE_DEFAULT"; + SubjectReferenceType["SUBJECT_TYPE_PERSON"] = "SUBJECT_TYPE_PERSON"; + SubjectReferenceType["SUBJECT_TYPE_ANIMAL"] = "SUBJECT_TYPE_ANIMAL"; + SubjectReferenceType["SUBJECT_TYPE_PRODUCT"] = "SUBJECT_TYPE_PRODUCT"; +})(SubjectReferenceType || (SubjectReferenceType = {})); +/** Enum representing the Imagen 3 Edit mode. */ +var EditMode; +(function (EditMode) { + EditMode["EDIT_MODE_DEFAULT"] = "EDIT_MODE_DEFAULT"; + EditMode["EDIT_MODE_INPAINT_REMOVAL"] = "EDIT_MODE_INPAINT_REMOVAL"; + EditMode["EDIT_MODE_INPAINT_INSERTION"] = "EDIT_MODE_INPAINT_INSERTION"; + EditMode["EDIT_MODE_OUTPAINT"] = "EDIT_MODE_OUTPAINT"; + EditMode["EDIT_MODE_CONTROLLED_EDITING"] = "EDIT_MODE_CONTROLLED_EDITING"; + EditMode["EDIT_MODE_STYLE"] = "EDIT_MODE_STYLE"; + EditMode["EDIT_MODE_BGSWAP"] = "EDIT_MODE_BGSWAP"; + EditMode["EDIT_MODE_PRODUCT_IMAGE"] = "EDIT_MODE_PRODUCT_IMAGE"; +})(EditMode || (EditMode = {})); +/** Enum that controls the compression quality of the generated videos. */ +var VideoCompressionQuality; +(function (VideoCompressionQuality) { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + VideoCompressionQuality["OPTIMIZED"] = "OPTIMIZED"; + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + VideoCompressionQuality["LOSSLESS"] = "LOSSLESS"; +})(VideoCompressionQuality || (VideoCompressionQuality = {})); +/** State for the lifecycle of a File. */ +var FileState; +(function (FileState) { + FileState["STATE_UNSPECIFIED"] = "STATE_UNSPECIFIED"; + FileState["PROCESSING"] = "PROCESSING"; + FileState["ACTIVE"] = "ACTIVE"; + FileState["FAILED"] = "FAILED"; +})(FileState || (FileState = {})); +/** Source of the File. */ +var FileSource; +(function (FileSource) { + FileSource["SOURCE_UNSPECIFIED"] = "SOURCE_UNSPECIFIED"; + FileSource["UPLOADED"] = "UPLOADED"; + FileSource["GENERATED"] = "GENERATED"; +})(FileSource || (FileSource = {})); +/** Server content modalities. */ +var MediaModality; +(function (MediaModality) { + /** + * The modality is unspecified. + */ + MediaModality["MODALITY_UNSPECIFIED"] = "MODALITY_UNSPECIFIED"; + /** + * Plain text. + */ + MediaModality["TEXT"] = "TEXT"; + /** + * Images. + */ + MediaModality["IMAGE"] = "IMAGE"; + /** + * Video. + */ + MediaModality["VIDEO"] = "VIDEO"; + /** + * Audio. + */ + MediaModality["AUDIO"] = "AUDIO"; + /** + * Document, e.g. PDF. + */ + MediaModality["DOCUMENT"] = "DOCUMENT"; +})(MediaModality || (MediaModality = {})); +/** Start of speech sensitivity. */ +var StartSensitivity; +(function (StartSensitivity) { + /** + * The default is START_SENSITIVITY_LOW. + */ + StartSensitivity["START_SENSITIVITY_UNSPECIFIED"] = + "START_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection will detect the start of speech more often. + */ + StartSensitivity["START_SENSITIVITY_HIGH"] = "START_SENSITIVITY_HIGH"; + /** + * Automatic detection will detect the start of speech less often. + */ + StartSensitivity["START_SENSITIVITY_LOW"] = "START_SENSITIVITY_LOW"; +})(StartSensitivity || (StartSensitivity = {})); +/** End of speech sensitivity. */ +var EndSensitivity; +(function (EndSensitivity) { + /** + * The default is END_SENSITIVITY_LOW. + */ + EndSensitivity["END_SENSITIVITY_UNSPECIFIED"] = "END_SENSITIVITY_UNSPECIFIED"; + /** + * Automatic detection ends speech more often. + */ + EndSensitivity["END_SENSITIVITY_HIGH"] = "END_SENSITIVITY_HIGH"; + /** + * Automatic detection ends speech less often. + */ + EndSensitivity["END_SENSITIVITY_LOW"] = "END_SENSITIVITY_LOW"; +})(EndSensitivity || (EndSensitivity = {})); +/** The different ways of handling user activity. */ +var ActivityHandling; +(function (ActivityHandling) { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ActivityHandling["ACTIVITY_HANDLING_UNSPECIFIED"] = + "ACTIVITY_HANDLING_UNSPECIFIED"; + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + ActivityHandling["START_OF_ACTIVITY_INTERRUPTS"] = + "START_OF_ACTIVITY_INTERRUPTS"; + /** + * The model's response will not be interrupted. + */ + ActivityHandling["NO_INTERRUPTION"] = "NO_INTERRUPTION"; +})(ActivityHandling || (ActivityHandling = {})); +/** Options about which input is included in the user's turn. */ +var TurnCoverage; +(function (TurnCoverage) { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TurnCoverage["TURN_COVERAGE_UNSPECIFIED"] = "TURN_COVERAGE_UNSPECIFIED"; + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TurnCoverage["TURN_INCLUDES_ONLY_ACTIVITY"] = "TURN_INCLUDES_ONLY_ACTIVITY"; + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TurnCoverage["TURN_INCLUDES_ALL_INPUT"] = "TURN_INCLUDES_ALL_INPUT"; +})(TurnCoverage || (TurnCoverage = {})); +/** Specifies how the response should be scheduled in the conversation. */ +var FunctionResponseScheduling; +(function (FunctionResponseScheduling) { + /** + * This value is unused. + */ + FunctionResponseScheduling["SCHEDULING_UNSPECIFIED"] = + "SCHEDULING_UNSPECIFIED"; + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + FunctionResponseScheduling["SILENT"] = "SILENT"; + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + FunctionResponseScheduling["WHEN_IDLE"] = "WHEN_IDLE"; + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + FunctionResponseScheduling["INTERRUPT"] = "INTERRUPT"; +})(FunctionResponseScheduling || (FunctionResponseScheduling = {})); +/** Scale of the generated music. */ +var Scale; +(function (Scale) { + /** + * Default value. This value is unused. + */ + Scale["SCALE_UNSPECIFIED"] = "SCALE_UNSPECIFIED"; + /** + * C major or A minor. + */ + Scale["C_MAJOR_A_MINOR"] = "C_MAJOR_A_MINOR"; + /** + * Db major or Bb minor. + */ + Scale["D_FLAT_MAJOR_B_FLAT_MINOR"] = "D_FLAT_MAJOR_B_FLAT_MINOR"; + /** + * D major or B minor. + */ + Scale["D_MAJOR_B_MINOR"] = "D_MAJOR_B_MINOR"; + /** + * Eb major or C minor + */ + Scale["E_FLAT_MAJOR_C_MINOR"] = "E_FLAT_MAJOR_C_MINOR"; + /** + * E major or Db minor. + */ + Scale["E_MAJOR_D_FLAT_MINOR"] = "E_MAJOR_D_FLAT_MINOR"; + /** + * F major or D minor. + */ + Scale["F_MAJOR_D_MINOR"] = "F_MAJOR_D_MINOR"; + /** + * Gb major or Eb minor. + */ + Scale["G_FLAT_MAJOR_E_FLAT_MINOR"] = "G_FLAT_MAJOR_E_FLAT_MINOR"; + /** + * G major or E minor. + */ + Scale["G_MAJOR_E_MINOR"] = "G_MAJOR_E_MINOR"; + /** + * Ab major or F minor. + */ + Scale["A_FLAT_MAJOR_F_MINOR"] = "A_FLAT_MAJOR_F_MINOR"; + /** + * A major or Gb minor. + */ + Scale["A_MAJOR_G_FLAT_MINOR"] = "A_MAJOR_G_FLAT_MINOR"; + /** + * Bb major or G minor. + */ + Scale["B_FLAT_MAJOR_G_MINOR"] = "B_FLAT_MAJOR_G_MINOR"; + /** + * B major or Ab minor. + */ + Scale["B_MAJOR_A_FLAT_MINOR"] = "B_MAJOR_A_FLAT_MINOR"; +})(Scale || (Scale = {})); +/** The playback control signal to apply to the music generation. */ +var LiveMusicPlaybackControl; +(function (LiveMusicPlaybackControl) { + /** + * This value is unused. + */ + LiveMusicPlaybackControl["PLAYBACK_CONTROL_UNSPECIFIED"] = + "PLAYBACK_CONTROL_UNSPECIFIED"; + /** + * Start generating the music. + */ + LiveMusicPlaybackControl["PLAY"] = "PLAY"; + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + LiveMusicPlaybackControl["PAUSE"] = "PAUSE"; + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + LiveMusicPlaybackControl["STOP"] = "STOP"; + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + LiveMusicPlaybackControl["RESET_CONTEXT"] = "RESET_CONTEXT"; +})(LiveMusicPlaybackControl || (LiveMusicPlaybackControl = {})); +/** A function response. */ +class FunctionResponse {} +/** + * Creates a `Part` object from a `URI` string. + */ +function createPartFromUri(uri, mimeType) { + return { + fileData: { + fileUri: uri, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from a `text` string. + */ +function createPartFromText(text) { + return { + text: text, + }; +} +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +function createPartFromFunctionCall(name, args) { + return { + functionCall: { + name: name, + args: args, + }, + }; +} +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +function createPartFromFunctionResponse(id, name, response) { + return { + functionResponse: { + id: id, + name: name, + response: response, + }, + }; +} +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +function createPartFromBase64(data, mimeType) { + return { + inlineData: { + data: data, + mimeType: mimeType, + }, + }; +} +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +function createPartFromCodeExecutionResult(outcome, output) { + return { + codeExecutionResult: { + outcome: outcome, + output: output, + }, + }; +} +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +function createPartFromExecutableCode(code, language) { + return { + executableCode: { + code: code, + language: language, + }, + }; +} +function _isPart(obj) { + if (typeof obj === "object" && obj !== null) { + return ( + "fileData" in obj || + "text" in obj || + "functionCall" in obj || + "functionResponse" in obj || + "inlineData" in obj || + "videoMetadata" in obj || + "codeExecutionResult" in obj || + "executableCode" in obj + ); + } + return false; +} +function _toParts(partOrString) { + const parts = []; + if (typeof partOrString === "string") { + parts.push(createPartFromText(partOrString)); + } else if (_isPart(partOrString)) { + parts.push(partOrString); + } else if (Array.isArray(partOrString)) { + if (partOrString.length === 0) { + throw new Error("partOrString cannot be an empty array"); + } + for (const part of partOrString) { + if (typeof part === "string") { + parts.push(createPartFromText(part)); + } else if (_isPart(part)) { + parts.push(part); + } else { + throw new Error("element in PartUnion must be a Part object or string"); + } + } + } else { + throw new Error("partOrString must be a Part object, string, or array"); + } + return parts; +} +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +function createUserContent(partOrString) { + return { + role: "user", + parts: _toParts(partOrString), + }; +} +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +function createModelContent(partOrString) { + return { + role: "model", + parts: _toParts(partOrString), + }; +} +/** A wrapper class for the http response. */ +class HttpResponse { + constructor(response) { + // Process the headers. + const headers = {}; + for (const pair of response.headers.entries()) { + headers[pair[0]] = pair[1]; + } + this.headers = headers; + // Keep the original response. + this.responseInternal = response; + } + json() { + return this.responseInternal.json(); + } +} +/** Content filter results for a prompt sent in the request. */ +class GenerateContentResponsePromptFeedback {} +/** Usage metadata about response(s). */ +class GenerateContentResponseUsageMetadata {} +/** Response message for PredictionService.GenerateContent. */ +class GenerateContentResponse { + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning text from the first one.", + ); + } + let text = ""; + let anyTextPartText = false; + const nonTextParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartText = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartText ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning data from the first one.", + ); + } + let data = ""; + const nonDataParts = []; + for (const part of (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 ? void 0 : _e[0]) === + null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) !== null && _h !== void 0 + ? _h + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "inlineData" && + (fieldValue !== null || fieldValue !== undefined) + ) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls() { + var _a, _b, _c, _d, _e, _f, _g, _h; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning function calls from the first one.", + ); + } + const functionCalls = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.functionCall) + .map((part) => part.functionCall) + .filter((functionCall) => functionCall !== undefined); + if ( + (functionCalls === null || functionCalls === void 0 + ? void 0 + : functionCalls.length) === 0 + ) { + return undefined; + } + return functionCalls; + } + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning executable code from the first one.", + ); + } + const executableCode = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.executableCode) + .map((part) => part.executableCode) + .filter((executableCode) => executableCode !== undefined); + if ( + (executableCode === null || executableCode === void 0 + ? void 0 + : executableCode.length) === 0 + ) { + return undefined; + } + return (_j = + executableCode === null || executableCode === void 0 + ? void 0 + : executableCode[0]) === null || _j === void 0 + ? void 0 + : _j.code; + } + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j; + if ( + ((_d = + (_c = + (_b = + (_a = this.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content) === null || _c === void 0 + ? void 0 + : _c.parts) === null || _d === void 0 + ? void 0 + : _d.length) === 0 + ) { + return undefined; + } + if (this.candidates && this.candidates.length > 1) { + console.warn( + "there are multiple candidates in the response, returning code execution result from the first one.", + ); + } + const codeExecutionResult = + (_h = + (_g = + (_f = + (_e = this.candidates) === null || _e === void 0 + ? void 0 + : _e[0]) === null || _f === void 0 + ? void 0 + : _f.content) === null || _g === void 0 + ? void 0 + : _g.parts) === null || _h === void 0 + ? void 0 + : _h + .filter((part) => part.codeExecutionResult) + .map((part) => part.codeExecutionResult) + .filter((codeExecutionResult) => codeExecutionResult !== undefined); + if ( + (codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult.length) === 0 + ) { + return undefined; + } + return (_j = + codeExecutionResult === null || codeExecutionResult === void 0 + ? void 0 + : codeExecutionResult[0]) === null || _j === void 0 + ? void 0 + : _j.output; + } +} +/** Response for the embed_content method. */ +class EmbedContentResponse {} +/** The output images response. */ +class GenerateImagesResponse {} +/** Response for the request to edit an image. */ +class EditImageResponse {} +class UpscaleImageResponse {} +class ListModelsResponse {} +class DeleteModelResponse {} +/** Response for counting tokens. */ +class CountTokensResponse {} +/** Response for computing tokens. */ +class ComputeTokensResponse {} +/** Response with generated videos. */ +class GenerateVideosResponse {} +/** Response for the list tuning jobs method. */ +class ListTuningJobsResponse {} +/** Empty response for caches.delete method. */ +class DeleteCachedContentResponse {} +class ListCachedContentsResponse {} +/** Response for the list files method. */ +class ListFilesResponse {} +/** Response for the create file method. */ +class CreateFileResponse {} +/** Response for the delete file method. */ +class DeleteFileResponse {} +/** Config for `inlined_responses` parameter. */ +class InlinedResponse {} +/** Config for batches.list return value. */ +class ListBatchJobsResponse {} +/** Represents a single response in a replay. */ +class ReplayResponse {} +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +class RawReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_RAW", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + }; + return referenceImageAPI; + } +} +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +class MaskReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_MASK", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + maskImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +class ControlReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_CONTROL", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + controlImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +class StyleReferenceImage { + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_STYLE", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + styleImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +class SubjectReferenceImage { + /* Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI() { + const referenceImageAPI = { + referenceType: "REFERENCE_TYPE_SUBJECT", + referenceImage: this.referenceImage, + referenceId: this.referenceId, + subjectImageConfig: this.config, + }; + return referenceImageAPI; + } +} +/** Response message for API call. */ +class LiveServerMessage { + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text() { + var _a, _b, _c; + let text = ""; + let anyTextPartFound = false; + const nonTextParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if ( + fieldName !== "text" && + fieldName !== "thought" && + fieldValue !== null + ) { + nonTextParts.push(fieldName); + } + } + if (typeof part.text === "string") { + if (typeof part.thought === "boolean" && part.thought) { + continue; + } + anyTextPartFound = true; + text += part.text; + } + } + if (nonTextParts.length > 0) { + console.warn( + `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`, + ); + } + // part.text === '' is different from part.text is null + return anyTextPartFound ? text : undefined; + } + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data() { + var _a, _b, _c; + let data = ""; + const nonDataParts = []; + for (const part of (_c = + (_b = + (_a = this.serverContent) === null || _a === void 0 + ? void 0 + : _a.modelTurn) === null || _b === void 0 + ? void 0 + : _b.parts) !== null && _c !== void 0 + ? _c + : []) { + for (const [fieldName, fieldValue] of Object.entries(part)) { + if (fieldName !== "inlineData" && fieldValue !== null) { + nonDataParts.push(fieldName); + } + } + if (part.inlineData && typeof part.inlineData.data === "string") { + data += atob(part.inlineData.data); + } + } + if (nonDataParts.length > 0) { + console.warn( + `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`, + ); + } + return data.length > 0 ? btoa(data) : undefined; + } +} +/** A video generation long-running operation. */ +class GenerateVideosOperation { + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ apiResponse, isVertexAI }) { + const operation = new GenerateVideosOperation(); + operation.name = apiResponse["name"]; + operation.metadata = apiResponse["metadata"]; + operation.done = apiResponse["done"]; + operation.error = apiResponse["error"]; + if (isVertexAI) { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const responseVideos = response["videos"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + return { + video: { + uri: generatedVideo["gcsUri"], + videoBytes: generatedVideo["bytesBase64Encoded"] + ? tBytes$1(generatedVideo["bytesBase64Encoded"]) + : undefined, + mimeType: generatedVideo["mimeType"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } else { + const response = apiResponse["response"]; + if (response) { + const operationResponse = new GenerateVideosResponse(); + const generatedVideoResponse = response["generateVideoResponse"]; + const responseVideos = + generatedVideoResponse === null || generatedVideoResponse === void 0 + ? void 0 + : generatedVideoResponse["generatedSamples"]; + operationResponse.generatedVideos = + responseVideos === null || responseVideos === void 0 + ? void 0 + : responseVideos.map((generatedVideo) => { + const video = generatedVideo["video"]; + return { + video: { + uri: + video === null || video === void 0 + ? void 0 + : video["uri"], + videoBytes: ( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"] + ) + ? tBytes$1( + video === null || video === void 0 + ? void 0 + : video["encodedVideo"], + ) + : undefined, + mimeType: generatedVideo["encoding"], + }, + }; + }); + operationResponse.raiMediaFilteredCount = + response["raiMediaFilteredCount"]; + operationResponse.raiMediaFilteredReasons = + response["raiMediaFilteredReasons"]; + operation.response = operationResponse; + } + } + return operation; + } +} +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +class LiveClientToolResponse {} +/** Parameters for sending tool responses to the live API. */ +class LiveSendToolResponseParameters { + constructor() { + /** Tool responses to send to the session. */ + this.functionResponses = []; + } +} +/** Response message for the LiveMusicClientMessage call. */ +class LiveMusicServerMessage { + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk() { + if ( + this.serverContent && + this.serverContent.audioChunks && + this.serverContent.audioChunks.length > 0 + ) { + return this.serverContent.audioChunks[0]; + } + return undefined; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function tModel(apiClient, model) { + if (!model || typeof model !== "string") { + throw new Error("model is required and must be a string"); + } + if (apiClient.isVertexAI()) { + if ( + model.startsWith("publishers/") || + model.startsWith("projects/") || + model.startsWith("models/") + ) { + return model; + } else if (model.indexOf("/") >= 0) { + const parts = model.split("/", 2); + return `publishers/${parts[0]}/models/${parts[1]}`; + } else { + return `publishers/google/models/${model}`; + } + } else { + if (model.startsWith("models/") || model.startsWith("tunedModels/")) { + return model; + } else { + return `models/${model}`; + } + } +} +function tCachesModel(apiClient, model) { + const transformedModel = tModel(apiClient, model); + if (!transformedModel) { + return ""; + } + if (transformedModel.startsWith("publishers/") && apiClient.isVertexAI()) { + // vertex caches only support model name start with projects. + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`; + } else if (transformedModel.startsWith("models/") && apiClient.isVertexAI()) { + return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`; + } else { + return transformedModel; + } +} +function tBlobs(blobs) { + if (Array.isArray(blobs)) { + return blobs.map((blob) => tBlob(blob)); + } else { + return [tBlob(blobs)]; + } +} +function tBlob(blob) { + if (typeof blob === "object" && blob !== null) { + return blob; + } + throw new Error( + `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`, + ); +} +function tImageBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("image/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tAudioBlob(blob) { + const transformedBlob = tBlob(blob); + if ( + transformedBlob.mimeType && + transformedBlob.mimeType.startsWith("audio/") + ) { + return transformedBlob; + } + throw new Error(`Unsupported mime type: ${transformedBlob.mimeType}`); +} +function tPart(origin) { + if (origin === null || origin === undefined) { + throw new Error("PartUnion is required"); + } + if (typeof origin === "object") { + return origin; + } + if (typeof origin === "string") { + return { text: origin }; + } + throw new Error(`Unsupported part type: ${typeof origin}`); +} +function tParts(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("PartListUnion is required"); + } + if (Array.isArray(origin)) { + return origin.map((item) => tPart(item)); + } + return [tPart(origin)]; +} +function _isContent(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "parts" in origin && + Array.isArray(origin.parts) + ); +} +function _isFunctionCallPart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionCall" in origin + ); +} +function _isFunctionResponsePart(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "functionResponse" in origin + ); +} +function tContent(origin) { + if (origin === null || origin === undefined) { + throw new Error("ContentUnion is required"); + } + if (_isContent(origin)) { + // _isContent is a utility function that checks if the + // origin is a Content. + return origin; + } + return { + role: "user", + parts: tParts(origin), + }; +} +function tContentsForEmbed(apiClient, origin) { + if (!origin) { + return []; + } + if (apiClient.isVertexAI() && Array.isArray(origin)) { + return origin.flatMap((item) => { + const content = tContent(item); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + }); + } else if (apiClient.isVertexAI()) { + const content = tContent(origin); + if ( + content.parts && + content.parts.length > 0 && + content.parts[0].text !== undefined + ) { + return [content.parts[0].text]; + } + return []; + } + if (Array.isArray(origin)) { + return origin.map((item) => tContent(item)); + } + return [tContent(origin)]; +} +function tContents(origin) { + if ( + origin === null || + origin === undefined || + (Array.isArray(origin) && origin.length === 0) + ) { + throw new Error("contents are required"); + } + if (!Array.isArray(origin)) { + // If it's not an array, it's a single content or a single PartUnion. + if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) { + throw new Error( + "To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them", + ); + } + return [tContent(origin)]; + } + const result = []; + const accumulatedParts = []; + const isContentArray = _isContent(origin[0]); + for (const item of origin) { + const isContent = _isContent(item); + if (isContent != isContentArray) { + throw new 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 (isContent) { + // `isContent` contains the result of _isContent, which is a utility + // function that checks if the item is a Content. + result.push(item); + } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) { + throw new 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 { + accumulatedParts.push(item); + } + } + if (!isContentArray) { + result.push({ role: "user", parts: tParts(accumulatedParts) }); + } + return result; +} +/* +Transform the type field from an array of types to an array of anyOf fields. +Example: + {type: ['STRING', 'NUMBER']} +will be transformed to + {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]} +*/ +function flattenTypeArrayToAnyOf(typeList, resultingSchema) { + if (typeList.includes("null")) { + resultingSchema["nullable"] = true; + } + const listWithoutNull = typeList.filter((type) => type !== "null"); + if (listWithoutNull.length === 1) { + resultingSchema["type"] = Object.values(Type).includes( + listWithoutNull[0].toUpperCase(), + ) + ? listWithoutNull[0].toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else { + resultingSchema["anyOf"] = []; + for (const i of listWithoutNull) { + resultingSchema["anyOf"].push({ + type: Object.values(Type).includes(i.toUpperCase()) + ? i.toUpperCase() + : Type.TYPE_UNSPECIFIED, + }); + } + } +} +function processJsonSchema(_jsonSchema) { + const genAISchema = {}; + const schemaFieldNames = ["items"]; + const listSchemaFieldNames = ["anyOf"]; + const dictSchemaFieldNames = ["properties"]; + if (_jsonSchema["type"] && _jsonSchema["anyOf"]) { + throw new Error("type and anyOf cannot be both populated."); + } + /* + This is to handle the nullable array or object. The _jsonSchema will + be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The + logic is to check if anyOf has 2 elements and one of the element is null, + if so, the anyOf field is unnecessary, so we need to get rid of the anyOf + field and make the schema nullable. Then use the other element as the new + _jsonSchema for processing. This is because the backend doesn't have a null + type. + This has to be checked before we process any other fields. + For example: + const objectNullable = z.object({ + nullableArray: z.array(z.string()).nullable(), + }); + Will have the raw _jsonSchema as: + { + type: 'OBJECT', + properties: { + nullableArray: { + anyOf: [ + {type: 'null'}, + { + type: 'array', + items: {type: 'string'}, + }, + ], + } + }, + required: [ 'nullableArray' ], + } + Will result in following schema compatible with Gemini API: + { + type: 'OBJECT', + properties: { + nullableArray: { + nullable: true, + type: 'ARRAY', + items: {type: 'string'}, + } + }, + required: [ 'nullableArray' ], + } + */ + const incomingAnyOf = _jsonSchema["anyOf"]; + if (incomingAnyOf != null && incomingAnyOf.length == 2) { + if (incomingAnyOf[0]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[1]; + } else if (incomingAnyOf[1]["type"] === "null") { + genAISchema["nullable"] = true; + _jsonSchema = incomingAnyOf[0]; + } + } + if (_jsonSchema["type"] instanceof Array) { + flattenTypeArrayToAnyOf(_jsonSchema["type"], genAISchema); + } + for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) { + // Skip if the fieldvalue is undefined or null. + if (fieldValue == null) { + continue; + } + if (fieldName == "type") { + if (fieldValue === "null") { + throw new Error( + "type: null can not be the only possible type for the field.", + ); + } + if (fieldValue instanceof Array) { + // we have already handled the type field with array of types in the + // beginning of this function. + continue; + } + genAISchema["type"] = Object.values(Type).includes( + fieldValue.toUpperCase(), + ) + ? fieldValue.toUpperCase() + : Type.TYPE_UNSPECIFIED; + } else if (schemaFieldNames.includes(fieldName)) { + genAISchema[fieldName] = processJsonSchema(fieldValue); + } else if (listSchemaFieldNames.includes(fieldName)) { + const listSchemaFieldValue = []; + for (const item of fieldValue) { + if (item["type"] == "null") { + genAISchema["nullable"] = true; + continue; + } + listSchemaFieldValue.push(processJsonSchema(item)); + } + genAISchema[fieldName] = listSchemaFieldValue; + } else if (dictSchemaFieldNames.includes(fieldName)) { + const dictSchemaFieldValue = {}; + for (const [key, value] of Object.entries(fieldValue)) { + dictSchemaFieldValue[key] = processJsonSchema(value); + } + genAISchema[fieldName] = dictSchemaFieldValue; + } else { + // additionalProperties is not included in JSONSchema, skipping it. + if (fieldName === "additionalProperties") { + continue; + } + genAISchema[fieldName] = fieldValue; + } + } + return genAISchema; +} +// we take the unknown in the schema field because we want enable user to pass +// the output of major schema declaration tools without casting. Tools such as +// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type +// or object, see details in +// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7 +// typebox can return unknown, see details in +// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35 +// Note: proper json schemas with the $schema field set never arrive to this +// transformer. Schemas with $schema are routed to the equivalent API json +// schema field. +function tSchema(schema) { + return processJsonSchema(schema); +} +function tSpeechConfig(speechConfig) { + if (typeof speechConfig === "object") { + return speechConfig; + } else if (typeof speechConfig === "string") { + return { + voiceConfig: { + prebuiltVoiceConfig: { + voiceName: speechConfig, + }, + }, + }; + } else { + throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`); + } +} +function tLiveSpeechConfig(speechConfig) { + if ("multiSpeakerVoiceConfig" in speechConfig) { + throw new Error( + "multiSpeakerVoiceConfig is not supported in the live API.", + ); + } + return speechConfig; +} +function tTool(tool) { + if (tool.functionDeclarations) { + for (const functionDeclaration of tool.functionDeclarations) { + if (functionDeclaration.parameters) { + if (!Object.keys(functionDeclaration.parameters).includes("$schema")) { + functionDeclaration.parameters = processJsonSchema( + functionDeclaration.parameters, + ); + } else { + if (!functionDeclaration.parametersJsonSchema) { + functionDeclaration.parametersJsonSchema = + functionDeclaration.parameters; + delete functionDeclaration.parameters; + } + } + } + if (functionDeclaration.response) { + if (!Object.keys(functionDeclaration.response).includes("$schema")) { + functionDeclaration.response = processJsonSchema( + functionDeclaration.response, + ); + } else { + if (!functionDeclaration.responseJsonSchema) { + functionDeclaration.responseJsonSchema = + functionDeclaration.response; + delete functionDeclaration.response; + } + } + } + } + } + return tool; +} +function tTools(tools) { + // Check if the incoming type is defined. + if (tools === undefined || tools === null) { + throw new Error("tools is required"); + } + if (!Array.isArray(tools)) { + throw new Error("tools is required and must be an array of Tools"); + } + const result = []; + for (const tool of tools) { + result.push(tool); + } + return result; +} +/** + * Prepends resource name with project, location, resource_prefix if needed. + * + * @param client The API client. + * @param resourceName The resource name. + * @param resourcePrefix The resource prefix. + * @param splitsAfterPrefix The number of splits after the prefix. + * @returns The completed resource name. + * + * Examples: + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/bar/locations/us-west1/cachedContents/123' + * ``` + * + * ``` + * resource_name = 'projects/foo/locations/us-central1/cachedContents/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = True + * client.project = 'bar' + * client.location = 'us-west1' + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns: 'projects/foo/locations/us-central1/cachedContents/123' + * ``` + * + * ``` + * resource_name = '123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * returns 'cachedContents/123' + * ``` + * + * ``` + * resource_name = 'some/wrong/cachedContents/resource/name/123' + * resource_prefix = 'cachedContents' + * splits_after_prefix = 1 + * client.vertexai = False + * # client.vertexai = True + * _resource_name(client, resource_name, resource_prefix, splits_after_prefix) + * -> 'some/wrong/resource/name/123' + * ``` + */ +function resourceName( + client, + resourceName, + resourcePrefix, + splitsAfterPrefix = 1, +) { + const shouldAppendPrefix = + !resourceName.startsWith(`${resourcePrefix}/`) && + resourceName.split("/").length === splitsAfterPrefix; + if (client.isVertexAI()) { + if (resourceName.startsWith("projects/")) { + return resourceName; + } else if (resourceName.startsWith("locations/")) { + return `projects/${client.getProject()}/${resourceName}`; + } else if (resourceName.startsWith(`${resourcePrefix}/`)) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`; + } else if (shouldAppendPrefix) { + return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`; + } else { + return resourceName; + } + } + if (shouldAppendPrefix) { + return `${resourcePrefix}/${resourceName}`; + } + return resourceName; +} +function tCachedContentName(apiClient, name) { + if (typeof name !== "string") { + throw new Error("name must be a string"); + } + return resourceName(apiClient, name, "cachedContents"); +} +function tTuningJobStatus(status) { + switch (status) { + 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 status; + } +} +function tBytes(fromImageBytes) { + return tBytes$1(fromImageBytes); +} +function _isFile(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "name" in origin + ); +} +function isGeneratedVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "video" in origin + ); +} +function isVideo(origin) { + return ( + origin !== null && + origin !== undefined && + typeof origin === "object" && + "uri" in origin + ); +} +function tFileName(fromName) { + var _a; + let name; + if (_isFile(fromName)) { + name = fromName.name; + } + if (isVideo(fromName)) { + name = fromName.uri; + if (name === undefined) { + return undefined; + } + } + if (isGeneratedVideo(fromName)) { + name = (_a = fromName.video) === null || _a === void 0 ? void 0 : _a.uri; + if (name === undefined) { + return undefined; + } + } + if (typeof fromName === "string") { + name = fromName; + } + if (name === undefined) { + throw new Error("Could not extract file name from the provided input."); + } + if (name.startsWith("https://")) { + const suffix = name.split("files/")[1]; + const match = suffix.match(/[a-z0-9]+/); + if (match === null) { + throw new Error(`Could not extract file name from URI ${name}`); + } + name = match[0]; + } else if (name.startsWith("files/")) { + name = name.split("files/")[1]; + } + return name; +} +function tModelsUrl(apiClient, baseModels) { + let res; + if (apiClient.isVertexAI()) { + res = baseModels ? "publishers/google/models" : "models"; + } else { + res = baseModels ? "models" : "tunedModels"; + } + return res; +} +function tExtractModels(response) { + for (const key of ["models", "tunedModels", "publisherModels"]) { + if (hasField(response, key)) { + return response[key]; + } + } + return []; +} +function hasField(data, fieldName) { + return data !== null && typeof data === "object" && fieldName in data; +} +function mcpToGeminiTool(mcpTool, config = {}) { + const mcpToolSchema = mcpTool; + const functionDeclaration = { + name: mcpToolSchema["name"], + description: mcpToolSchema["description"], + parametersJsonSchema: mcpToolSchema["inputSchema"], + }; + if (config.behavior) { + functionDeclaration["behavior"] = config.behavior; + } + const geminiTool = { + functionDeclarations: [functionDeclaration], + }; + return geminiTool; +} +/** + * Converts a list of MCP tools to a single Gemini tool with a list of function + * declarations. + */ +function mcpToolsToGeminiTool(mcpTools, config = {}) { + const functionDeclarations = []; + const toolNames = new Set(); + for (const mcpTool of mcpTools) { + const mcpToolName = mcpTool.name; + if (toolNames.has(mcpToolName)) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + toolNames.add(mcpToolName); + const geminiTool = mcpToGeminiTool(mcpTool, config); + if (geminiTool.functionDeclarations) { + functionDeclarations.push(...geminiTool.functionDeclarations); + } + } + return { functionDeclarations: functionDeclarations }; +} +// Transforms a source input into a BatchJobSource object with validation. +function tBatchJobSource(apiClient, src) { + if (typeof src !== "string" && !Array.isArray(src)) { + if (apiClient && apiClient.isVertexAI()) { + if (src.gcsUri && src.bigqueryUri) { + throw new Error("Only one of `gcsUri` or `bigqueryUri` can be set."); + } else if (!src.gcsUri && !src.bigqueryUri) { + throw new Error("One of `gcsUri` or `bigqueryUri` must be set."); + } + } else { + // Logic for non-Vertex AI client (inlined_requests, file_name) + if (src.inlinedRequests && src.fileName) { + throw new Error( + "Only one of `inlinedRequests` or `fileName` can be set.", + ); + } else if (!src.inlinedRequests && !src.fileName) { + throw new Error("One of `inlinedRequests` or `fileName` must be set."); + } + } + return src; + } + // If src is an array (list in Python) + else if (Array.isArray(src)) { + return { inlinedRequests: src }; + } else if (typeof src === "string") { + if (src.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: [src], // GCS URI is expected as an array + }; + } else if (src.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: src, + }; + } else if (src.startsWith("files/")) { + return { + fileName: src, + }; + } + } + throw new Error(`Unsupported source: ${src}`); +} +function tBatchJobDestination(dest) { + if (typeof dest !== "string") { + return dest; + } + const destString = dest; + if (destString.startsWith("gs://")) { + return { + format: "jsonl", + gcsUri: destString, + }; + } else if (destString.startsWith("bq://")) { + return { + format: "bigquery", + bigqueryUri: destString, + }; + } else { + throw new Error(`Unsupported destination: ${destString}`); + } +} +function tBatchJobName(apiClient, name) { + const nameString = name; + if (!apiClient.isVertexAI()) { + const mldevPattern = /batches\/[^/]+$/; + if (mldevPattern.test(nameString)) { + return nameString.split("/").pop(); + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } + } + const vertexPattern = + /^projects\/[^/]+\/locations\/[^/]+\/batchPredictionJobs\/[^/]+$/; + if (vertexPattern.test(nameString)) { + return nameString.split("/").pop(); + } else if (/^\d+$/.test(nameString)) { + return nameString; + } else { + throw new Error(`Invalid batch job name: ${nameString}.`); + } +} +function tJobState(state) { + const stateString = state; + if (stateString === "BATCH_STATE_UNSPECIFIED") { + return "JOB_STATE_UNSPECIFIED"; + } else if (stateString === "BATCH_STATE_PENDING") { + return "JOB_STATE_PENDING"; + } else if (stateString === "BATCH_STATE_SUCCEEDED") { + return "JOB_STATE_SUCCEEDED"; + } else if (stateString === "BATCH_STATE_FAILED") { + return "JOB_STATE_FAILED"; + } else if (stateString === "BATCH_STATE_CANCELLED") { + return "JOB_STATE_CANCELLED"; + } else { + return stateString; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$4(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$4(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$4(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$4(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$4(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$4(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$4(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$4(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev$1(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$4(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$4(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$4(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$4(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$4(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$4(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$4(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$4() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$4(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$4(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$4(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$4(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$4(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$4()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$4(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$2(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$2(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$2(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$2(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$3(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$3(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$3(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$3(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$3(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$3(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev$1(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$4(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev$1(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev$1(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$4(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$2(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$3(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev$1(fromThinkingConfig), + ); + } + return toObject; +} +function inlinedRequestToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath( + toObject, + ["request", "model"], + tModel(apiClient, fromModel), + ); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$4(item); + }); + } + setValueByPath(toObject, ["request", "contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["request", "generationConfig"], + generateContentConfigToMldev$1(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function batchJobSourceToMldev(apiClient, fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["format"]) !== undefined) { + throw new Error("format parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["bigqueryUri"]) !== undefined) { + throw new Error("bigqueryUri parameter is not supported in Gemini API."); + } + const fromFileName = getValueByPath(fromObject, ["fileName"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedRequests = getValueByPath(fromObject, ["inlinedRequests"]); + if (fromInlinedRequests != null) { + let transformedList = fromInlinedRequests; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedRequestToMldev(apiClient, item); + }); + } + setValueByPath(toObject, ["requests", "requests"], transformedList); + } + return toObject; +} +function createBatchJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["batch", "displayName"], fromDisplayName); + } + if (getValueByPath(fromObject, ["dest"]) !== undefined) { + throw new Error("dest parameter is not supported in Gemini API."); + } + return toObject; +} +function createBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["batch", "inputConfig"], + batchJobSourceToMldev(apiClient, tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + if (getValueByPath(fromObject, ["filter"]) !== undefined) { + throw new Error("filter parameter is not supported in Gemini API."); + } + return toObject; +} +function listBatchJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function batchJobSourceToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["instancesFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsSource", "uris"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigquerySource", "inputUri"], fromBigqueryUri); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedRequests"]) !== undefined) { + throw new Error("inlinedRequests parameter is not supported in Vertex AI."); + } + return toObject; +} +function batchJobDestinationToVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["predictionsFormat"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsDestination", "outputUriPrefix"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, ["bigqueryUri"]); + if (fromBigqueryUri != null) { + setValueByPath( + toObject, + ["bigqueryDestination", "outputUri"], + fromBigqueryUri, + ); + } + if (getValueByPath(fromObject, ["fileName"]) !== undefined) { + throw new Error("fileName parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["inlinedResponses"]) !== undefined) { + throw new Error( + "inlinedResponses parameter is not supported in Vertex AI.", + ); + } + return toObject; +} +function createBatchJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDest = getValueByPath(fromObject, ["dest"]); + if (parentObject !== undefined && fromDest != null) { + setValueByPath( + parentObject, + ["outputConfig"], + batchJobDestinationToVertex(tBatchJobDestination(fromDest)), + ); + } + return toObject; +} +function createBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tModel(apiClient, fromModel)); + } + const fromSrc = getValueByPath(fromObject, ["src"]); + if (fromSrc != null) { + setValueByPath( + toObject, + ["inputConfig"], + batchJobSourceToVertex(tBatchJobSource(apiClient, fromSrc)), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createBatchJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function cancelBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listBatchJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listBatchJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listBatchJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteBatchJobParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tBatchJobName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$2(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$2(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$2(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$2(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev$1(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev$2(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev$1(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$2(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev$1(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev$1(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function jobErrorFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function inlinedResponseFromMldev(fromObject) { + const toObject = {}; + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateContentResponseFromMldev$1(fromResponse), + ); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function batchJobDestinationFromMldev(fromObject) { + const toObject = {}; + const fromFileName = getValueByPath(fromObject, ["responsesFile"]); + if (fromFileName != null) { + setValueByPath(toObject, ["fileName"], fromFileName); + } + const fromInlinedResponses = getValueByPath(fromObject, [ + "inlinedResponses", + "inlinedResponses", + ]); + if (fromInlinedResponses != null) { + let transformedList = fromInlinedResponses; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return inlinedResponseFromMldev(item); + }); + } + setValueByPath(toObject, ["inlinedResponses"], transformedList); + } + return toObject; +} +function batchJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, [ + "metadata", + "displayName", + ]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["metadata", "state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["metadata", "createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromEndTime = getValueByPath(fromObject, ["metadata", "endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["metadata", "updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["metadata", "model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromDest = getValueByPath(fromObject, ["metadata", "output"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromMldev(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["operations"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromMldev(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromMldev(fromError)); + } + return toObject; +} +function jobErrorFromVertex(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + return toObject; +} +function batchJobSourceFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["instancesFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, ["gcsSource", "uris"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigquerySource", + "inputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobDestinationFromVertex(fromObject) { + const toObject = {}; + const fromFormat = getValueByPath(fromObject, ["predictionsFormat"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromGcsUri = getValueByPath(fromObject, [ + "gcsDestination", + "outputUriPrefix", + ]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromBigqueryUri = getValueByPath(fromObject, [ + "bigqueryDestination", + "outputUri", + ]); + if (fromBigqueryUri != null) { + setValueByPath(toObject, ["bigqueryUri"], fromBigqueryUri); + } + return toObject; +} +function batchJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tJobState(fromState)); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromSrc = getValueByPath(fromObject, ["inputConfig"]); + if (fromSrc != null) { + setValueByPath(toObject, ["src"], batchJobSourceFromVertex(fromSrc)); + } + const fromDest = getValueByPath(fromObject, ["outputConfig"]); + if (fromDest != null) { + setValueByPath(toObject, ["dest"], batchJobDestinationFromVertex(fromDest)); + } + return toObject; +} +function listBatchJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromBatchJobs = getValueByPath(fromObject, ["batchPredictionJobs"]); + if (fromBatchJobs != null) { + let transformedList = fromBatchJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return batchJobFromVertex(item); + }); + } + setValueByPath(toObject, ["batchJobs"], transformedList); + } + return toObject; +} +function deleteResourceJobFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], jobErrorFromVertex(fromError)); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +var PagedItem; +(function (PagedItem) { + PagedItem["PAGED_ITEM_BATCH_JOBS"] = "batchJobs"; + PagedItem["PAGED_ITEM_MODELS"] = "models"; + PagedItem["PAGED_ITEM_TUNING_JOBS"] = "tuningJobs"; + PagedItem["PAGED_ITEM_FILES"] = "files"; + PagedItem["PAGED_ITEM_CACHED_CONTENTS"] = "cachedContents"; +})(PagedItem || (PagedItem = {})); +/** + * Pager class for iterating through paginated results. + */ +class Pager { + constructor(name, request, response, params) { + this.pageInternal = []; + this.paramsInternal = {}; + this.requestInternal = request; + this.init(name, response, params); + } + init(name, response, params) { + var _a, _b; + this.nameInternal = name; + this.pageInternal = response[this.nameInternal] || []; + this.sdkHttpResponseInternal = + response === null || response === void 0 + ? void 0 + : response.sdkHttpResponse; + this.idxInternal = 0; + let requestParams = { config: {} }; + if (!params || Object.keys(params).length === 0) { + requestParams = { config: {} }; + } else if (typeof params === "object") { + requestParams = Object.assign({}, params); + } else { + requestParams = params; + } + if (requestParams["config"]) { + requestParams["config"]["pageToken"] = response["nextPageToken"]; + } + this.paramsInternal = requestParams; + this.pageInternalSize = + (_b = + (_a = requestParams["config"]) === null || _a === void 0 + ? void 0 + : _a["pageSize"]) !== null && _b !== void 0 + ? _b + : this.pageInternal.length; + } + initNextPage(response) { + this.init(this.nameInternal, response, this.paramsInternal); + } + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page() { + return this.pageInternal; + } + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name() { + return this.nameInternal; + } + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize() { + return this.pageInternalSize; + } + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse() { + return this.sdkHttpResponseInternal; + } + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params() { + return this.paramsInternal; + } + /** + * Returns the total number of items in the current page. + */ + get pageLength() { + return this.pageInternal.length; + } + /** + * Returns the item at the given index. + */ + getItem(index) { + return this.pageInternal[index]; + } + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator]() { + return { + next: async () => { + if (this.idxInternal >= this.pageLength) { + if (this.hasNextPage()) { + await this.nextPage(); + } else { + return { value: undefined, done: true }; + } + } + const item = this.getItem(this.idxInternal); + this.idxInternal += 1; + return { value: item, done: false }; + }, + return: async () => { + return { value: undefined, done: true }; + }, + }; + } + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + async nextPage() { + if (!this.hasNextPage()) { + throw new Error("No more pages to fetch."); + } + const response = await this.requestInternal(this.params); + this.initNextPage(response); + return this.page; + } + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage() { + var _a; + if ( + ((_a = this.params["config"]) === null || _a === void 0 + ? void 0 + : _a["pageToken"]) !== undefined + ) { + return true; + } + return false; + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Batches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + this.create = async (params) => { + if (this.apiClient.isVertexAI()) { + const timestamp = Date.now(); + const timestampStr = timestamp.toString(); + if (Array.isArray(params.src)) { + throw new Error( + "InlinedRequest[] is not supported in Vertex AI. Please use " + + "Google Cloud Storage URI or BigQuery URI instead.", + ); + } + params.config = params.config || {}; + if (params.config.displayName === undefined) { + params.config.displayName = "genaiBatchJob_${timestampStr}"; + } + if ( + params.config.dest === undefined && + typeof params.src === "string" + ) { + if (params.src.startsWith("gs://") && params.src.endsWith(".jsonl")) { + params.config.dest = `${params.src.slice(0, -6)}/dest`; + } else if (params.src.startsWith("bq://")) { + params.config.dest = `${params.src}_dest_${timestampStr}`; + } else { + throw new Error("Unsupported source:" + params.src); + } + } + } + return await this.createInternal(params); + }; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_BATCH_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + async createInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = createBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchGenerateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = batchJobFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + async cancel(params) { + var _a, _b, _c, _d; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = cancelBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + } else { + const body = cancelBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}:cancel", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + await this.apiClient.request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listBatchJobsParametersToVertex(params); + path = formatMap("batchPredictionJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromVertex(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listBatchJobsParametersToMldev(params); + path = formatMap("batches", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listBatchJobsResponseFromMldev(apiResponse); + const typedResp = new ListBatchJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteBatchJobParametersToVertex(this.apiClient, params); + path = formatMap("batchPredictionJobs/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = deleteBatchJobParametersToMldev(this.apiClient, params); + path = formatMap("batches/{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = deleteResourceJobFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$3(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$3(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$3(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$3(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$3(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$3(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$3(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$3(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$3(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$3(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$3(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$3(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$3(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$3(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$3(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$3() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$3(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$3(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$3(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$3(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$3(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$3()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$3(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$3(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$3(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$3(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev$1(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["kmsKeyName"]) !== undefined) { + throw new Error("kmsKeyName parameter is not supported in Gemini API."); + } + return toObject; +} +function createCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$2(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$2() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$2(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$2(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$2(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$2(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$2() { + const toObject = {}; + return toObject; +} +function toolToVertex$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$2(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$2(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$2(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$2()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex$1(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex$1(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex$1(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex$1(fromRetrievalConfig), + ); + } + return toObject; +} +function createCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (parentObject !== undefined && fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex$2(item); + }); + } + setValueByPath(parentObject, ["contents"], transformedList); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$2(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex$1(fromToolConfig), + ); + } + const fromKmsKeyName = getValueByPath(fromObject, ["kmsKeyName"]); + if (parentObject !== undefined && fromKmsKeyName != null) { + setValueByPath( + parentObject, + ["encryption_spec", "kmsKeyName"], + fromKmsKeyName, + ); + } + return toObject; +} +function createCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], tCachesModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function updateCachedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTtl = getValueByPath(fromObject, ["ttl"]); + if (parentObject !== undefined && fromTtl != null) { + setValueByPath(parentObject, ["ttl"], fromTtl); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + return toObject; +} +function updateCachedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath( + toObject, + ["_url", "name"], + tCachedContentName(apiClient, fromName), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateCachedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function listCachedContentsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listCachedContentsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listCachedContentsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function cachedContentFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromMldev() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromMldev(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} +function cachedContentFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (fromExpireTime != null) { + setValueByPath(toObject, ["expireTime"], fromExpireTime); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function deleteCachedContentResponseFromVertex() { + const toObject = {}; + return toObject; +} +function listCachedContentsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromCachedContents = getValueByPath(fromObject, ["cachedContents"]); + if (fromCachedContents != null) { + let transformedList = fromCachedContents; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return cachedContentFromVertex(item); + }); + } + setValueByPath(toObject, ["cachedContents"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Caches extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_CACHED_CONTENTS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + async create(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = createCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getCachedContentParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = getCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromVertex(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteCachedContentResponseFromMldev(); + const typedResp = new DeleteCachedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateCachedContentParametersToVertex( + this.apiClient, + params, + ); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateCachedContentParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = cachedContentFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listCachedContentsParametersToVertex(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromVertex(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listCachedContentsParametersToMldev(params); + path = formatMap("cachedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listCachedContentsResponseFromMldev(apiResponse); + const typedResp = new ListCachedContentsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, + m = s && o[s], + i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") + return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + }, + }; + throw new TypeError( + s ? "Object is not iterable." : "Symbol.iterator is not defined.", + ); +} + +function __await(v) { + return this instanceof __await ? ((this.v = v), this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), + i, + q = []; + return ( + (i = Object.create( + (typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype, + )), + verb("next"), + verb("throw"), + verb("return", awaitReturn), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i + ); + function awaitReturn(f) { + return function (v) { + return Promise.resolve(v).then(f, reject); + }; + } + function verb(n, f) { + if (g[n]) { + i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + if (f) i[n] = f(i[n]); + } + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await + ? Promise.resolve(r.value.v).then(fulfill, reject) + : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) + throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], + i; + return m + ? m.call(o) + : ((o = + typeof __values === "function" ? __values(o) : o[Symbol.iterator]()), + (i = {}), + verb("next"), + verb("throw"), + verb("return"), + (i[Symbol.asyncIterator] = function () { + return this; + }), + i); + function verb(n) { + i[n] = + o[n] && + function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v)), settle(resolve, reject, v.done, v.value); + }); + }; + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ value: v, done: d }); + }, reject); + } +} + +typeof SuppressedError === "function" + ? SuppressedError + : function (error, suppressed, message) { + var e = new Error(message); + return ( + (e.name = "SuppressedError"), + (e.error = error), + (e.suppressed = suppressed), + e + ); + }; + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns true if the response is valid, false otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates == undefined || response.candidates.length === 0) { + return false; + } + const content = + (_a = response.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content; + if (content === undefined) { + return false; + } + return isValidContent(content); +} +function isValidContent(content) { + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (!part.thought && part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} +/** + * Validates the history contains the correct roles. + * + * @throws Error if the history does not start with a user turn. + * @throws Error if the history contains an invalid role. + */ +function validateHistory(history) { + // Empty history is valid. + if (history.length === 0) { + return; + } + for (const content of history) { + if (content.role !== "user" && content.role !== "model") { + throw new Error(`Role must be user or model, but got ${content.role}.`); + } + } +} +/** + * Extracts the curated (valid) history from a comprehensive history. + * + * @remarks + * The model may sometimes generate invalid or empty contents(e.g., due to safty + * filters or recitation). Extracting valid turns from the history + * ensures that subsequent requests could be accpeted by the model. + */ +function extractCuratedHistory(comprehensiveHistory) { + if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) { + return []; + } + const curatedHistory = []; + const length = comprehensiveHistory.length; + let i = 0; + while (i < length) { + if (comprehensiveHistory[i].role === "user") { + curatedHistory.push(comprehensiveHistory[i]); + i++; + } else { + const modelOutput = []; + let isValid = true; + while (i < length && comprehensiveHistory[i].role === "model") { + modelOutput.push(comprehensiveHistory[i]); + if (isValid && !isValidContent(comprehensiveHistory[i])) { + isValid = false; + } + i++; + } + if (isValid) { + curatedHistory.push(...modelOutput); + } else { + // Remove the last user input when model content is invalid. + curatedHistory.pop(); + } + } + } + return curatedHistory; +} +/** + * A utility class to create a chat session. + */ +class Chats { + constructor(modelsModule, apiClient) { + this.modelsModule = modelsModule; + this.apiClient = apiClient; + } + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params) { + return new Chat( + this.apiClient, + this.modelsModule, + params.model, + params.config, + // Deep copy the history to avoid mutating the history outside of the + // chat session. + structuredClone(params.history), + ); + } +} +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +class Chat { + constructor(apiClient, modelsModule, model, config = {}, history = []) { + this.apiClient = apiClient; + this.modelsModule = modelsModule; + this.model = model; + this.config = config; + this.history = history; + // A promise to represent the current state of the message being sent to the + // model. + this.sendPromise = Promise.resolve(); + validateHistory(history); + } + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + async sendMessage(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const responsePromise = this.modelsModule.generateContent({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + this.sendPromise = (async () => { + var _a, _b, _c; + const response = await responsePromise; + const outputContent = + (_b = + (_a = response.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + // Because the AFC input contains the entire curated chat history in + // addition to the new user input, we need to truncate the AFC history + // to deduplicate the existing chat history. + const fullAutomaticFunctionCallingHistory = + response.automaticFunctionCallingHistory; + const index = this.getHistory(true).length; + let automaticFunctionCallingHistory = []; + if (fullAutomaticFunctionCallingHistory != null) { + automaticFunctionCallingHistory = + (_c = fullAutomaticFunctionCallingHistory.slice(index)) !== null && + _c !== void 0 + ? _c + : []; + } + const modelOutput = outputContent ? [outputContent] : []; + this.recordHistory( + inputContent, + modelOutput, + automaticFunctionCallingHistory, + ); + return; + })(); + await this.sendPromise.catch(() => { + // Resets sendPromise to avoid subsequent calls failing + this.sendPromise = Promise.resolve(); + }); + return responsePromise; + } + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + async sendMessageStream(params) { + var _a; + await this.sendPromise; + const inputContent = tContent(params.message); + const streamResponse = this.modelsModule.generateContentStream({ + model: this.model, + contents: this.getHistory(true).concat(inputContent), + config: (_a = params.config) !== null && _a !== void 0 ? _a : this.config, + }); + // Resolve the internal tracking of send completion promise - `sendPromise` + // for both success and failure response. The actual failure is still + // propagated by the `await streamResponse`. + this.sendPromise = streamResponse + .then(() => undefined) + .catch(() => undefined); + const response = await streamResponse; + const result = this.processStreamResponse(response, inputContent); + return result; + } + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated = false) { + const history = curated + ? extractCuratedHistory(this.history) + : this.history; + // Deep copy the history to avoid mutating the history outside of the + // chat session. + return structuredClone(history); + } + processStreamResponse(streamResponse, inputContent) { + var _a, _b; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + var _c, e_1, _d, _e; + const outputContent = []; + try { + for ( + var _f = true, + streamResponse_1 = __asyncValues(streamResponse), + streamResponse_1_1; + (streamResponse_1_1 = yield __await(streamResponse_1.next())), + (_c = streamResponse_1_1.done), + !_c; + _f = true + ) { + _e = streamResponse_1_1.value; + _f = false; + const chunk = _e; + if (isValidResponse(chunk)) { + const content = + (_b = + (_a = chunk.candidates) === null || _a === void 0 + ? void 0 + : _a[0]) === null || _b === void 0 + ? void 0 + : _b.content; + if (content !== undefined) { + outputContent.push(content); + } + } + yield yield __await(chunk); + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = streamResponse_1.return)) + yield __await(_d.call(streamResponse_1)); + } finally { + if (e_1) throw e_1.error; + } + } + this.recordHistory(inputContent, outputContent); + }, + ); + } + recordHistory(userInput, modelOutput, automaticFunctionCallingHistory) { + let outputContents = []; + if ( + modelOutput.length > 0 && + modelOutput.every((content) => content.role !== undefined) + ) { + outputContents = modelOutput; + } else { + // Appends an empty content when model returns empty response, so that the + // history is always alternating between user and model. + outputContents.push({ + role: "model", + parts: [], + }); + } + if ( + automaticFunctionCallingHistory && + automaticFunctionCallingHistory.length > 0 + ) { + this.history.push( + ...extractCuratedHistory(automaticFunctionCallingHistory), + ); + } else { + this.history.push(userInput); + } + this.history.push(...outputContents); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * API errors raised by the GenAI API. + */ +class ApiError extends Error { + constructor(options) { + super(options.message); + this.name = "ApiError"; + this.status = options.status; + Object.setPrototypeOf(this, ApiError.prototype); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function listFilesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + return toObject; +} +function listFilesParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listFilesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function fileStatusToMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusToMldev(fromError)); + } + return toObject; +} +function createFileParametersToMldev(fromObject) { + const toObject = {}; + const fromFile = getValueByPath(fromObject, ["file"]); + if (fromFile != null) { + setValueByPath(toObject, ["file"], fileToMldev(fromFile)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function deleteFileParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "file"], tFileName(fromName)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fileStatusFromMldev(fromObject) { + const toObject = {}; + const fromDetails = getValueByPath(fromObject, ["details"]); + if (fromDetails != null) { + setValueByPath(toObject, ["details"], fromDetails); + } + const fromMessage = getValueByPath(fromObject, ["message"]); + if (fromMessage != null) { + setValueByPath(toObject, ["message"], fromMessage); + } + const fromCode = getValueByPath(fromObject, ["code"]); + if (fromCode != null) { + setValueByPath(toObject, ["code"], fromCode); + } + return toObject; +} +function fileFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSizeBytes = getValueByPath(fromObject, ["sizeBytes"]); + if (fromSizeBytes != null) { + setValueByPath(toObject, ["sizeBytes"], fromSizeBytes); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromExpirationTime = getValueByPath(fromObject, ["expirationTime"]); + if (fromExpirationTime != null) { + setValueByPath(toObject, ["expirationTime"], fromExpirationTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromSha256Hash = getValueByPath(fromObject, ["sha256Hash"]); + if (fromSha256Hash != null) { + setValueByPath(toObject, ["sha256Hash"], fromSha256Hash); + } + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromDownloadUri = getValueByPath(fromObject, ["downloadUri"]); + if (fromDownloadUri != null) { + setValueByPath(toObject, ["downloadUri"], fromDownloadUri); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], fromState); + } + const fromSource = getValueByPath(fromObject, ["source"]); + if (fromSource != null) { + setValueByPath(toObject, ["source"], fromSource); + } + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath(toObject, ["videoMetadata"], fromVideoMetadata); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fileStatusFromMldev(fromError)); + } + return toObject; +} +function listFilesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromFiles = getValueByPath(fromObject, ["files"]); + if (fromFiles != null) { + let transformedList = fromFiles; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return fileFromMldev(item); + }); + } + setValueByPath(toObject, ["files"], transformedList); + } + return toObject; +} +function createFileResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + return toObject; +} +function deleteFileResponseFromMldev() { + const toObject = {}; + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Files extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_FILES, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + } + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + async upload(params) { + if (this.apiClient.isVertexAI()) { + throw new Error( + "Vertex AI does not support uploading files. You can share files through a GCS bucket.", + ); + } + return this.apiClient + .uploadFile(params.file, params.config) + .then((response) => { + const file = fileFromMldev(response); + return file; + }); + } + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + async download(params) { + await this.apiClient.downloadFile(params); + } + async listInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = listFilesParametersToMldev(params); + path = formatMap("files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listFilesResponseFromMldev(apiResponse); + const typedResp = new ListFilesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async createInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createFileParametersToMldev(params); + path = formatMap("upload/v1beta/files", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = createFileResponseFromMldev(apiResponse); + const typedResp = new CreateFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + async get(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = getFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = fileFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + async delete(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = deleteFileParametersToMldev(params); + path = formatMap("files/{file}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteFileResponseFromMldev(); + const typedResp = new DeleteFileResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$2(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$2(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$2(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$2(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$2(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$2(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev$2(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$2(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$2(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$2(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$2(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$2(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$2(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$2(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev$2(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$2(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$2(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$2(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$2(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$2(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$2(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$2() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$2(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$2(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$2(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$2(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$2(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$2()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$2(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev$1() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev$1(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev$1(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev$1(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev$1(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev$1(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev$1(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev$1(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev$1(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev$2(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev$2(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$2(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev$1(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev$1(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev$1(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev$1(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev$1(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev$1(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToMldev() { + const toObject = {}; + return toObject; +} +function activityEndToMldev() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToMldev(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToMldev()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToMldev()); + } + return toObject; +} +function weightedPromptToMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicSetWeightedPromptsParametersToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigToMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSetConfigParametersToMldev(fromObject) { + const toObject = {}; + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function liveMusicClientSetupToMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + return toObject; +} +function liveMusicClientContentToMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptToMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicClientMessageToMldev(fromObject) { + const toObject = {}; + const fromSetup = getValueByPath(fromObject, ["setup"]); + if (fromSetup != null) { + setValueByPath(toObject, ["setup"], liveMusicClientSetupToMldev(fromSetup)); + } + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentToMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigToMldev(fromMusicGenerationConfig), + ); + } + const fromPlaybackControl = getValueByPath(fromObject, ["playbackControl"]); + if (fromPlaybackControl != null) { + setValueByPath(toObject, ["playbackControl"], fromPlaybackControl); + } + return toObject; +} +function prebuiltVoiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex$1(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToVertex$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex$1() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex$1(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex$1(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex$1(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex$1(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex$1() { + const toObject = {}; + return toObject; +} +function toolToVertex$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex$1(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex$1(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex$1(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex$1()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToVertex(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + const fromTransparent = getValueByPath(fromObject, ["transparent"]); + if (fromTransparent != null) { + setValueByPath(toObject, ["transparent"], fromTransparent); + } + return toObject; +} +function audioTranscriptionConfigToVertex() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToVertex(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToVertex(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToVertex(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToVertex(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToVertex(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToVertex(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToVertex(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToVertex$1(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToVertex$1(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToVertex(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToVertex(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToVertex(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToVertex(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToVertex(fromProactivity), + ); + } + return toObject; +} +function liveConnectParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function activityStartToVertex() { + const toObject = {}; + return toObject; +} +function activityEndToVertex() { + const toObject = {}; + return toObject; +} +function liveSendRealtimeInputParametersToVertex(fromObject) { + const toObject = {}; + const fromMedia = getValueByPath(fromObject, ["media"]); + if (fromMedia != null) { + setValueByPath(toObject, ["mediaChunks"], tBlobs(fromMedia)); + } + const fromAudio = getValueByPath(fromObject, ["audio"]); + if (fromAudio != null) { + setValueByPath(toObject, ["audio"], tAudioBlob(fromAudio)); + } + const fromAudioStreamEnd = getValueByPath(fromObject, ["audioStreamEnd"]); + if (fromAudioStreamEnd != null) { + setValueByPath(toObject, ["audioStreamEnd"], fromAudioStreamEnd); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], tImageBlob(fromVideo)); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromActivityStart = getValueByPath(fromObject, ["activityStart"]); + if (fromActivityStart != null) { + setValueByPath(toObject, ["activityStart"], activityStartToVertex()); + } + const fromActivityEnd = getValueByPath(fromObject, ["activityEnd"]); + if (fromActivityEnd != null) { + setValueByPath(toObject, ["activityEnd"], activityEndToVertex()); + } + return toObject; +} +function liveServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function videoMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev$1(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev$1(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function urlMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev$1(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev$1(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function liveServerContentFromMldev(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromMldev$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromMldev(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromMldev(fromOutputTranscription), + ); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev$1(fromUrlContextMetadata), + ); + } + return toObject; +} +function functionCallFromMldev(fromObject) { + const toObject = {}; + const fromId = getValueByPath(fromObject, ["id"]); + if (fromId != null) { + setValueByPath(toObject, ["id"], fromId); + } + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromMldev(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromMldev(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromMldev(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromMldev(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromMldev(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "responseTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "responseTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromMldev(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + return toObject; +} +function liveServerGoAwayFromMldev(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromMldev(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromMldev(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromMldev(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromMldev(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromMldev(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath(toObject, ["goAway"], liveServerGoAwayFromMldev(fromGoAway)); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate), + ); + } + return toObject; +} +function liveMusicServerSetupCompleteFromMldev() { + const toObject = {}; + return toObject; +} +function weightedPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromWeight = getValueByPath(fromObject, ["weight"]); + if (fromWeight != null) { + setValueByPath(toObject, ["weight"], fromWeight); + } + return toObject; +} +function liveMusicClientContentFromMldev(fromObject) { + const toObject = {}; + const fromWeightedPrompts = getValueByPath(fromObject, ["weightedPrompts"]); + if (fromWeightedPrompts != null) { + let transformedList = fromWeightedPrompts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return weightedPromptFromMldev(item); + }); + } + setValueByPath(toObject, ["weightedPrompts"], transformedList); + } + return toObject; +} +function liveMusicGenerationConfigFromMldev(fromObject) { + const toObject = {}; + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromGuidance = getValueByPath(fromObject, ["guidance"]); + if (fromGuidance != null) { + setValueByPath(toObject, ["guidance"], fromGuidance); + } + const fromBpm = getValueByPath(fromObject, ["bpm"]); + if (fromBpm != null) { + setValueByPath(toObject, ["bpm"], fromBpm); + } + const fromDensity = getValueByPath(fromObject, ["density"]); + if (fromDensity != null) { + setValueByPath(toObject, ["density"], fromDensity); + } + const fromBrightness = getValueByPath(fromObject, ["brightness"]); + if (fromBrightness != null) { + setValueByPath(toObject, ["brightness"], fromBrightness); + } + const fromScale = getValueByPath(fromObject, ["scale"]); + if (fromScale != null) { + setValueByPath(toObject, ["scale"], fromScale); + } + const fromMuteBass = getValueByPath(fromObject, ["muteBass"]); + if (fromMuteBass != null) { + setValueByPath(toObject, ["muteBass"], fromMuteBass); + } + const fromMuteDrums = getValueByPath(fromObject, ["muteDrums"]); + if (fromMuteDrums != null) { + setValueByPath(toObject, ["muteDrums"], fromMuteDrums); + } + const fromOnlyBassAndDrums = getValueByPath(fromObject, ["onlyBassAndDrums"]); + if (fromOnlyBassAndDrums != null) { + setValueByPath(toObject, ["onlyBassAndDrums"], fromOnlyBassAndDrums); + } + return toObject; +} +function liveMusicSourceMetadataFromMldev(fromObject) { + const toObject = {}; + const fromClientContent = getValueByPath(fromObject, ["clientContent"]); + if (fromClientContent != null) { + setValueByPath( + toObject, + ["clientContent"], + liveMusicClientContentFromMldev(fromClientContent), + ); + } + const fromMusicGenerationConfig = getValueByPath(fromObject, [ + "musicGenerationConfig", + ]); + if (fromMusicGenerationConfig != null) { + setValueByPath( + toObject, + ["musicGenerationConfig"], + liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig), + ); + } + return toObject; +} +function audioChunkFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + const fromSourceMetadata = getValueByPath(fromObject, ["sourceMetadata"]); + if (fromSourceMetadata != null) { + setValueByPath( + toObject, + ["sourceMetadata"], + liveMusicSourceMetadataFromMldev(fromSourceMetadata), + ); + } + return toObject; +} +function liveMusicServerContentFromMldev(fromObject) { + const toObject = {}; + const fromAudioChunks = getValueByPath(fromObject, ["audioChunks"]); + if (fromAudioChunks != null) { + let transformedList = fromAudioChunks; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return audioChunkFromMldev(item); + }); + } + setValueByPath(toObject, ["audioChunks"], transformedList); + } + return toObject; +} +function liveMusicFilteredPromptFromMldev(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFilteredReason = getValueByPath(fromObject, ["filteredReason"]); + if (fromFilteredReason != null) { + setValueByPath(toObject, ["filteredReason"], fromFilteredReason); + } + return toObject; +} +function liveMusicServerMessageFromMldev(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveMusicServerSetupCompleteFromMldev(), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveMusicServerContentFromMldev(fromServerContent), + ); + } + const fromFilteredPrompt = getValueByPath(fromObject, ["filteredPrompt"]); + if (fromFilteredPrompt != null) { + setValueByPath( + toObject, + ["filteredPrompt"], + liveMusicFilteredPromptFromMldev(fromFilteredPrompt), + ); + } + return toObject; +} +function liveServerSetupCompleteFromVertex(fromObject) { + const toObject = {}; + const fromSessionId = getValueByPath(fromObject, ["sessionId"]); + if (fromSessionId != null) { + setValueByPath(toObject, ["sessionId"], fromSessionId); + } + return toObject; +} +function videoMetadataFromVertex$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex$1(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function transcriptionFromVertex(fromObject) { + const toObject = {}; + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + const fromFinished = getValueByPath(fromObject, ["finished"]); + if (fromFinished != null) { + setValueByPath(toObject, ["finished"], fromFinished); + } + return toObject; +} +function liveServerContentFromVertex(fromObject) { + const toObject = {}; + const fromModelTurn = getValueByPath(fromObject, ["modelTurn"]); + if (fromModelTurn != null) { + setValueByPath(toObject, ["modelTurn"], contentFromVertex$1(fromModelTurn)); + } + const fromTurnComplete = getValueByPath(fromObject, ["turnComplete"]); + if (fromTurnComplete != null) { + setValueByPath(toObject, ["turnComplete"], fromTurnComplete); + } + const fromInterrupted = getValueByPath(fromObject, ["interrupted"]); + if (fromInterrupted != null) { + setValueByPath(toObject, ["interrupted"], fromInterrupted); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromGenerationComplete = getValueByPath(fromObject, [ + "generationComplete", + ]); + if (fromGenerationComplete != null) { + setValueByPath(toObject, ["generationComplete"], fromGenerationComplete); + } + const fromInputTranscription = getValueByPath(fromObject, [ + "inputTranscription", + ]); + if (fromInputTranscription != null) { + setValueByPath( + toObject, + ["inputTranscription"], + transcriptionFromVertex(fromInputTranscription), + ); + } + const fromOutputTranscription = getValueByPath(fromObject, [ + "outputTranscription", + ]); + if (fromOutputTranscription != null) { + setValueByPath( + toObject, + ["outputTranscription"], + transcriptionFromVertex(fromOutputTranscription), + ); + } + return toObject; +} +function functionCallFromVertex(fromObject) { + const toObject = {}; + const fromArgs = getValueByPath(fromObject, ["args"]); + if (fromArgs != null) { + setValueByPath(toObject, ["args"], fromArgs); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} +function liveServerToolCallFromVertex(fromObject) { + const toObject = {}; + const fromFunctionCalls = getValueByPath(fromObject, ["functionCalls"]); + if (fromFunctionCalls != null) { + let transformedList = fromFunctionCalls; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionCallFromVertex(item); + }); + } + setValueByPath(toObject, ["functionCalls"], transformedList); + } + return toObject; +} +function liveServerToolCallCancellationFromVertex(fromObject) { + const toObject = {}; + const fromIds = getValueByPath(fromObject, ["ids"]); + if (fromIds != null) { + setValueByPath(toObject, ["ids"], fromIds); + } + return toObject; +} +function modalityTokenCountFromVertex(fromObject) { + const toObject = {}; + const fromModality = getValueByPath(fromObject, ["modality"]); + if (fromModality != null) { + setValueByPath(toObject, ["modality"], fromModality); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function usageMetadataFromVertex(fromObject) { + const toObject = {}; + const fromPromptTokenCount = getValueByPath(fromObject, ["promptTokenCount"]); + if (fromPromptTokenCount != null) { + setValueByPath(toObject, ["promptTokenCount"], fromPromptTokenCount); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + const fromResponseTokenCount = getValueByPath(fromObject, [ + "candidatesTokenCount", + ]); + if (fromResponseTokenCount != null) { + setValueByPath(toObject, ["responseTokenCount"], fromResponseTokenCount); + } + const fromToolUsePromptTokenCount = getValueByPath(fromObject, [ + "toolUsePromptTokenCount", + ]); + if (fromToolUsePromptTokenCount != null) { + setValueByPath( + toObject, + ["toolUsePromptTokenCount"], + fromToolUsePromptTokenCount, + ); + } + const fromThoughtsTokenCount = getValueByPath(fromObject, [ + "thoughtsTokenCount", + ]); + if (fromThoughtsTokenCount != null) { + setValueByPath(toObject, ["thoughtsTokenCount"], fromThoughtsTokenCount); + } + const fromTotalTokenCount = getValueByPath(fromObject, ["totalTokenCount"]); + if (fromTotalTokenCount != null) { + setValueByPath(toObject, ["totalTokenCount"], fromTotalTokenCount); + } + const fromPromptTokensDetails = getValueByPath(fromObject, [ + "promptTokensDetails", + ]); + if (fromPromptTokensDetails != null) { + let transformedList = fromPromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["promptTokensDetails"], transformedList); + } + const fromCacheTokensDetails = getValueByPath(fromObject, [ + "cacheTokensDetails", + ]); + if (fromCacheTokensDetails != null) { + let transformedList = fromCacheTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["cacheTokensDetails"], transformedList); + } + const fromResponseTokensDetails = getValueByPath(fromObject, [ + "candidatesTokensDetails", + ]); + if (fromResponseTokensDetails != null) { + let transformedList = fromResponseTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["responseTokensDetails"], transformedList); + } + const fromToolUsePromptTokensDetails = getValueByPath(fromObject, [ + "toolUsePromptTokensDetails", + ]); + if (fromToolUsePromptTokensDetails != null) { + let transformedList = fromToolUsePromptTokensDetails; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modalityTokenCountFromVertex(item); + }); + } + setValueByPath(toObject, ["toolUsePromptTokensDetails"], transformedList); + } + const fromTrafficType = getValueByPath(fromObject, ["trafficType"]); + if (fromTrafficType != null) { + setValueByPath(toObject, ["trafficType"], fromTrafficType); + } + return toObject; +} +function liveServerGoAwayFromVertex(fromObject) { + const toObject = {}; + const fromTimeLeft = getValueByPath(fromObject, ["timeLeft"]); + if (fromTimeLeft != null) { + setValueByPath(toObject, ["timeLeft"], fromTimeLeft); + } + return toObject; +} +function liveServerSessionResumptionUpdateFromVertex(fromObject) { + const toObject = {}; + const fromNewHandle = getValueByPath(fromObject, ["newHandle"]); + if (fromNewHandle != null) { + setValueByPath(toObject, ["newHandle"], fromNewHandle); + } + const fromResumable = getValueByPath(fromObject, ["resumable"]); + if (fromResumable != null) { + setValueByPath(toObject, ["resumable"], fromResumable); + } + const fromLastConsumedClientMessageIndex = getValueByPath(fromObject, [ + "lastConsumedClientMessageIndex", + ]); + if (fromLastConsumedClientMessageIndex != null) { + setValueByPath( + toObject, + ["lastConsumedClientMessageIndex"], + fromLastConsumedClientMessageIndex, + ); + } + return toObject; +} +function liveServerMessageFromVertex(fromObject) { + const toObject = {}; + const fromSetupComplete = getValueByPath(fromObject, ["setupComplete"]); + if (fromSetupComplete != null) { + setValueByPath( + toObject, + ["setupComplete"], + liveServerSetupCompleteFromVertex(fromSetupComplete), + ); + } + const fromServerContent = getValueByPath(fromObject, ["serverContent"]); + if (fromServerContent != null) { + setValueByPath( + toObject, + ["serverContent"], + liveServerContentFromVertex(fromServerContent), + ); + } + const fromToolCall = getValueByPath(fromObject, ["toolCall"]); + if (fromToolCall != null) { + setValueByPath( + toObject, + ["toolCall"], + liveServerToolCallFromVertex(fromToolCall), + ); + } + const fromToolCallCancellation = getValueByPath(fromObject, [ + "toolCallCancellation", + ]); + if (fromToolCallCancellation != null) { + setValueByPath( + toObject, + ["toolCallCancellation"], + liveServerToolCallCancellationFromVertex(fromToolCallCancellation), + ); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath( + toObject, + ["usageMetadata"], + usageMetadataFromVertex(fromUsageMetadata), + ); + } + const fromGoAway = getValueByPath(fromObject, ["goAway"]); + if (fromGoAway != null) { + setValueByPath( + toObject, + ["goAway"], + liveServerGoAwayFromVertex(fromGoAway), + ); + } + const fromSessionResumptionUpdate = getValueByPath(fromObject, [ + "sessionResumptionUpdate", + ]); + if (fromSessionResumptionUpdate != null) { + setValueByPath( + toObject, + ["sessionResumptionUpdate"], + liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function videoMetadataToMldev$1(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev$1(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev$1(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev$1(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev$1(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev$1(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev$1(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev$1(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToMldev(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function safetySettingToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["method"]) !== undefined) { + throw new Error("method parameter is not supported in Gemini API."); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToMldev$1(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev$1(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev$1(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev$1(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev$1(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev$1(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev$1(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev$1() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev$1(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev$1(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev$1(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev$1(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev$1(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev$1()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev$1(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToMldev(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToMldev(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToMldev(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToMldev(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToMldev(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev$1(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev$1(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev$1(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev$1(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev$1(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev$1(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToMldev(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToMldev$1(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToMldev(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + if (getValueByPath(fromObject, ["routingConfig"]) !== undefined) { + throw new Error("routingConfig parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["modelSelectionConfig"]) !== undefined) { + throw new Error( + "modelSelectionConfig parameter is not supported in Gemini API.", + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToMldev(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev$1(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToMldev(fromToolConfig), + ); + } + if (getValueByPath(fromObject, ["labels"]) !== undefined) { + throw new Error("labels parameter is not supported in Gemini API."); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToMldev$1(tSpeechConfig(fromSpeechConfig)), + ); + } + if (getValueByPath(fromObject, ["audioTimestamp"]) !== undefined) { + throw new Error("audioTimestamp parameter is not supported in Gemini API."); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToMldev(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["requests[]", "taskType"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["requests[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["requests[]", "outputDimensionality"], + fromOutputDimensionality, + ); + } + if (getValueByPath(fromObject, ["mimeType"]) !== undefined) { + throw new Error("mimeType parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["autoTruncate"]) !== undefined) { + throw new Error("autoTruncate parameter is not supported in Gemini API."); + } + return toObject; +} +function embedContentParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["requests[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToMldev(fromConfig, toObject), + ); + } + const fromModelForEmbedContent = getValueByPath(fromObject, ["model"]); + if (fromModelForEmbedContent !== undefined) { + setValueByPath( + toObject, + ["requests[]", "model"], + tModel(apiClient, fromModelForEmbedContent), + ); + } + return toObject; +} +function generateImagesConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["negativePrompt"]) !== undefined) { + throw new Error("negativePrompt parameter is not supported in Gemini API."); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + if (getValueByPath(fromObject, ["addWatermark"]) !== undefined) { + throw new Error("addWatermark parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["imageSize"]) !== undefined) { + throw new Error("imageSize parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["enhancePrompt"]) !== undefined) { + throw new Error("enhancePrompt parameter is not supported in Gemini API."); + } + return toObject; +} +function generateImagesParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["systemInstruction"]) !== undefined) { + throw new Error( + "systemInstruction parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["tools"]) !== undefined) { + throw new Error("tools parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["generationConfig"]) !== undefined) { + throw new Error( + "generationConfig parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function countTokensParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToMldev$1(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], countTokensConfigToMldev(fromConfig)); + } + return toObject; +} +function imageToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + if (getValueByPath(fromObject, ["outputGcsUri"]) !== undefined) { + throw new Error("outputGcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["fps"]) !== undefined) { + throw new Error("fps parameter is not supported in Gemini API."); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + if (getValueByPath(fromObject, ["seed"]) !== undefined) { + throw new Error("seed parameter is not supported in Gemini API."); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + if (getValueByPath(fromObject, ["resolution"]) !== undefined) { + throw new Error("resolution parameter is not supported in Gemini API."); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + if (getValueByPath(fromObject, ["pubsubTopic"]) !== undefined) { + throw new Error("pubsubTopic parameter is not supported in Gemini API."); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + if (getValueByPath(fromObject, ["generateAudio"]) !== undefined) { + throw new Error("generateAudio parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["lastFrame"]) !== undefined) { + throw new Error("lastFrame parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["compressionQuality"]) !== undefined) { + throw new Error( + "compressionQuality parameter is not supported in Gemini API.", + ); + } + return toObject; +} +function generateVideosParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToMldev(fromImage), + ); + } + if (getValueByPath(fromObject, ["video"]) !== undefined) { + throw new Error("video parameter is not supported in Gemini API."); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataToVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function schemaToVertex(fromObject) { + const toObject = {}; + const fromAnyOf = getValueByPath(fromObject, ["anyOf"]); + if (fromAnyOf != null) { + setValueByPath(toObject, ["anyOf"], fromAnyOf); + } + const fromDefault = getValueByPath(fromObject, ["default"]); + if (fromDefault != null) { + setValueByPath(toObject, ["default"], fromDefault); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromEnum = getValueByPath(fromObject, ["enum"]); + if (fromEnum != null) { + setValueByPath(toObject, ["enum"], fromEnum); + } + const fromExample = getValueByPath(fromObject, ["example"]); + if (fromExample != null) { + setValueByPath(toObject, ["example"], fromExample); + } + const fromFormat = getValueByPath(fromObject, ["format"]); + if (fromFormat != null) { + setValueByPath(toObject, ["format"], fromFormat); + } + const fromItems = getValueByPath(fromObject, ["items"]); + if (fromItems != null) { + setValueByPath(toObject, ["items"], fromItems); + } + const fromMaxItems = getValueByPath(fromObject, ["maxItems"]); + if (fromMaxItems != null) { + setValueByPath(toObject, ["maxItems"], fromMaxItems); + } + const fromMaxLength = getValueByPath(fromObject, ["maxLength"]); + if (fromMaxLength != null) { + setValueByPath(toObject, ["maxLength"], fromMaxLength); + } + const fromMaxProperties = getValueByPath(fromObject, ["maxProperties"]); + if (fromMaxProperties != null) { + setValueByPath(toObject, ["maxProperties"], fromMaxProperties); + } + const fromMaximum = getValueByPath(fromObject, ["maximum"]); + if (fromMaximum != null) { + setValueByPath(toObject, ["maximum"], fromMaximum); + } + const fromMinItems = getValueByPath(fromObject, ["minItems"]); + if (fromMinItems != null) { + setValueByPath(toObject, ["minItems"], fromMinItems); + } + const fromMinLength = getValueByPath(fromObject, ["minLength"]); + if (fromMinLength != null) { + setValueByPath(toObject, ["minLength"], fromMinLength); + } + const fromMinProperties = getValueByPath(fromObject, ["minProperties"]); + if (fromMinProperties != null) { + setValueByPath(toObject, ["minProperties"], fromMinProperties); + } + const fromMinimum = getValueByPath(fromObject, ["minimum"]); + if (fromMinimum != null) { + setValueByPath(toObject, ["minimum"], fromMinimum); + } + const fromNullable = getValueByPath(fromObject, ["nullable"]); + if (fromNullable != null) { + setValueByPath(toObject, ["nullable"], fromNullable); + } + const fromPattern = getValueByPath(fromObject, ["pattern"]); + if (fromPattern != null) { + setValueByPath(toObject, ["pattern"], fromPattern); + } + const fromProperties = getValueByPath(fromObject, ["properties"]); + if (fromProperties != null) { + setValueByPath(toObject, ["properties"], fromProperties); + } + const fromPropertyOrdering = getValueByPath(fromObject, ["propertyOrdering"]); + if (fromPropertyOrdering != null) { + setValueByPath(toObject, ["propertyOrdering"], fromPropertyOrdering); + } + const fromRequired = getValueByPath(fromObject, ["required"]); + if (fromRequired != null) { + setValueByPath(toObject, ["required"], fromRequired); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (fromTitle != null) { + setValueByPath(toObject, ["title"], fromTitle); + } + const fromType = getValueByPath(fromObject, ["type"]); + if (fromType != null) { + setValueByPath(toObject, ["type"], fromType); + } + return toObject; +} +function modelSelectionConfigToVertex(fromObject) { + const toObject = {}; + const fromFeatureSelectionPreference = getValueByPath(fromObject, [ + "featureSelectionPreference", + ]); + if (fromFeatureSelectionPreference != null) { + setValueByPath( + toObject, + ["featureSelectionPreference"], + fromFeatureSelectionPreference, + ); + } + return toObject; +} +function safetySettingToVertex(fromObject) { + const toObject = {}; + const fromMethod = getValueByPath(fromObject, ["method"]); + if (fromMethod != null) { + setValueByPath(toObject, ["method"], fromMethod); + } + const fromCategory = getValueByPath(fromObject, ["category"]); + if (fromCategory != null) { + setValueByPath(toObject, ["category"], fromCategory); + } + const fromThreshold = getValueByPath(fromObject, ["threshold"]); + if (fromThreshold != null) { + setValueByPath(toObject, ["threshold"], fromThreshold); + } + return toObject; +} +function functionDeclarationToVertex(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["behavior"]) !== undefined) { + throw new Error("behavior parameter is not supported in Vertex AI."); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToVertex(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToVertex(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToVertex(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToVertex(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function enterpriseWebSearchToVertex() { + const toObject = {}; + return toObject; +} +function apiKeyConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyString = getValueByPath(fromObject, ["apiKeyString"]); + if (fromApiKeyString != null) { + setValueByPath(toObject, ["apiKeyString"], fromApiKeyString); + } + return toObject; +} +function authConfigToVertex(fromObject) { + const toObject = {}; + const fromApiKeyConfig = getValueByPath(fromObject, ["apiKeyConfig"]); + if (fromApiKeyConfig != null) { + setValueByPath( + toObject, + ["apiKeyConfig"], + apiKeyConfigToVertex(fromApiKeyConfig), + ); + } + const fromAuthType = getValueByPath(fromObject, ["authType"]); + if (fromAuthType != null) { + setValueByPath(toObject, ["authType"], fromAuthType); + } + const fromGoogleServiceAccountConfig = getValueByPath(fromObject, [ + "googleServiceAccountConfig", + ]); + if (fromGoogleServiceAccountConfig != null) { + setValueByPath( + toObject, + ["googleServiceAccountConfig"], + fromGoogleServiceAccountConfig, + ); + } + const fromHttpBasicAuthConfig = getValueByPath(fromObject, [ + "httpBasicAuthConfig", + ]); + if (fromHttpBasicAuthConfig != null) { + setValueByPath(toObject, ["httpBasicAuthConfig"], fromHttpBasicAuthConfig); + } + const fromOauthConfig = getValueByPath(fromObject, ["oauthConfig"]); + if (fromOauthConfig != null) { + setValueByPath(toObject, ["oauthConfig"], fromOauthConfig); + } + const fromOidcConfig = getValueByPath(fromObject, ["oidcConfig"]); + if (fromOidcConfig != null) { + setValueByPath(toObject, ["oidcConfig"], fromOidcConfig); + } + return toObject; +} +function googleMapsToVertex(fromObject) { + const toObject = {}; + const fromAuthConfig = getValueByPath(fromObject, ["authConfig"]); + if (fromAuthConfig != null) { + setValueByPath( + toObject, + ["authConfig"], + authConfigToVertex(fromAuthConfig), + ); + } + return toObject; +} +function urlContextToVertex() { + const toObject = {}; + return toObject; +} +function toolToVertex(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToVertex(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + const fromRetrieval = getValueByPath(fromObject, ["retrieval"]); + if (fromRetrieval != null) { + setValueByPath(toObject, ["retrieval"], fromRetrieval); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToVertex(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToVertex(fromGoogleSearchRetrieval), + ); + } + const fromEnterpriseWebSearch = getValueByPath(fromObject, [ + "enterpriseWebSearch", + ]); + if (fromEnterpriseWebSearch != null) { + setValueByPath( + toObject, + ["enterpriseWebSearch"], + enterpriseWebSearchToVertex(), + ); + } + const fromGoogleMaps = getValueByPath(fromObject, ["googleMaps"]); + if (fromGoogleMaps != null) { + setValueByPath( + toObject, + ["googleMaps"], + googleMapsToVertex(fromGoogleMaps), + ); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToVertex()); + } + if (getValueByPath(fromObject, ["computerUse"]) !== undefined) { + throw new Error("computerUse parameter is not supported in Vertex AI."); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function functionCallingConfigToVertex(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromAllowedFunctionNames = getValueByPath(fromObject, [ + "allowedFunctionNames", + ]); + if (fromAllowedFunctionNames != null) { + setValueByPath( + toObject, + ["allowedFunctionNames"], + fromAllowedFunctionNames, + ); + } + return toObject; +} +function latLngToVertex(fromObject) { + const toObject = {}; + const fromLatitude = getValueByPath(fromObject, ["latitude"]); + if (fromLatitude != null) { + setValueByPath(toObject, ["latitude"], fromLatitude); + } + const fromLongitude = getValueByPath(fromObject, ["longitude"]); + if (fromLongitude != null) { + setValueByPath(toObject, ["longitude"], fromLongitude); + } + return toObject; +} +function retrievalConfigToVertex(fromObject) { + const toObject = {}; + const fromLatLng = getValueByPath(fromObject, ["latLng"]); + if (fromLatLng != null) { + setValueByPath(toObject, ["latLng"], latLngToVertex(fromLatLng)); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function toolConfigToVertex(fromObject) { + const toObject = {}; + const fromFunctionCallingConfig = getValueByPath(fromObject, [ + "functionCallingConfig", + ]); + if (fromFunctionCallingConfig != null) { + setValueByPath( + toObject, + ["functionCallingConfig"], + functionCallingConfigToVertex(fromFunctionCallingConfig), + ); + } + const fromRetrievalConfig = getValueByPath(fromObject, ["retrievalConfig"]); + if (fromRetrievalConfig != null) { + setValueByPath( + toObject, + ["retrievalConfig"], + retrievalConfigToVertex(fromRetrievalConfig), + ); + } + return toObject; +} +function prebuiltVoiceConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToVertex(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speechConfigToVertex(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToVertex(fromVoiceConfig), + ); + } + if (getValueByPath(fromObject, ["multiSpeakerVoiceConfig"]) !== undefined) { + throw new Error( + "multiSpeakerVoiceConfig parameter is not supported in Vertex AI.", + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function thinkingConfigToVertex(fromObject) { + const toObject = {}; + const fromIncludeThoughts = getValueByPath(fromObject, ["includeThoughts"]); + if (fromIncludeThoughts != null) { + setValueByPath(toObject, ["includeThoughts"], fromIncludeThoughts); + } + const fromThinkingBudget = getValueByPath(fromObject, ["thinkingBudget"]); + if (fromThinkingBudget != null) { + setValueByPath(toObject, ["thinkingBudget"], fromThinkingBudget); + } + return toObject; +} +function generateContentConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (fromTemperature != null) { + setValueByPath(toObject, ["temperature"], fromTemperature); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (fromTopP != null) { + setValueByPath(toObject, ["topP"], fromTopP); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (fromTopK != null) { + setValueByPath(toObject, ["topK"], fromTopK); + } + const fromCandidateCount = getValueByPath(fromObject, ["candidateCount"]); + if (fromCandidateCount != null) { + setValueByPath(toObject, ["candidateCount"], fromCandidateCount); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (fromMaxOutputTokens != null) { + setValueByPath(toObject, ["maxOutputTokens"], fromMaxOutputTokens); + } + const fromStopSequences = getValueByPath(fromObject, ["stopSequences"]); + if (fromStopSequences != null) { + setValueByPath(toObject, ["stopSequences"], fromStopSequences); + } + const fromResponseLogprobs = getValueByPath(fromObject, ["responseLogprobs"]); + if (fromResponseLogprobs != null) { + setValueByPath(toObject, ["responseLogprobs"], fromResponseLogprobs); + } + const fromLogprobs = getValueByPath(fromObject, ["logprobs"]); + if (fromLogprobs != null) { + setValueByPath(toObject, ["logprobs"], fromLogprobs); + } + const fromPresencePenalty = getValueByPath(fromObject, ["presencePenalty"]); + if (fromPresencePenalty != null) { + setValueByPath(toObject, ["presencePenalty"], fromPresencePenalty); + } + const fromFrequencyPenalty = getValueByPath(fromObject, ["frequencyPenalty"]); + if (fromFrequencyPenalty != null) { + setValueByPath(toObject, ["frequencyPenalty"], fromFrequencyPenalty); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (fromSeed != null) { + setValueByPath(toObject, ["seed"], fromSeed); + } + const fromResponseMimeType = getValueByPath(fromObject, ["responseMimeType"]); + if (fromResponseMimeType != null) { + setValueByPath(toObject, ["responseMimeType"], fromResponseMimeType); + } + const fromResponseSchema = getValueByPath(fromObject, ["responseSchema"]); + if (fromResponseSchema != null) { + setValueByPath( + toObject, + ["responseSchema"], + schemaToVertex(tSchema(fromResponseSchema)), + ); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + const fromRoutingConfig = getValueByPath(fromObject, ["routingConfig"]); + if (fromRoutingConfig != null) { + setValueByPath(toObject, ["routingConfig"], fromRoutingConfig); + } + const fromModelSelectionConfig = getValueByPath(fromObject, [ + "modelSelectionConfig", + ]); + if (fromModelSelectionConfig != null) { + setValueByPath( + toObject, + ["modelConfig"], + modelSelectionConfigToVertex(fromModelSelectionConfig), + ); + } + const fromSafetySettings = getValueByPath(fromObject, ["safetySettings"]); + if (parentObject !== undefined && fromSafetySettings != null) { + let transformedList = fromSafetySettings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return safetySettingToVertex(item); + }); + } + setValueByPath(parentObject, ["safetySettings"], transformedList); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(tTool(item)); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromToolConfig = getValueByPath(fromObject, ["toolConfig"]); + if (parentObject !== undefined && fromToolConfig != null) { + setValueByPath( + parentObject, + ["toolConfig"], + toolConfigToVertex(fromToolConfig), + ); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (parentObject !== undefined && fromLabels != null) { + setValueByPath(parentObject, ["labels"], fromLabels); + } + const fromCachedContent = getValueByPath(fromObject, ["cachedContent"]); + if (parentObject !== undefined && fromCachedContent != null) { + setValueByPath( + parentObject, + ["cachedContent"], + tCachedContentName(apiClient, fromCachedContent), + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (fromResponseModalities != null) { + setValueByPath(toObject, ["responseModalities"], fromResponseModalities); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (fromMediaResolution != null) { + setValueByPath(toObject, ["mediaResolution"], fromMediaResolution); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (fromSpeechConfig != null) { + setValueByPath( + toObject, + ["speechConfig"], + speechConfigToVertex(tSpeechConfig(fromSpeechConfig)), + ); + } + const fromAudioTimestamp = getValueByPath(fromObject, ["audioTimestamp"]); + if (fromAudioTimestamp != null) { + setValueByPath(toObject, ["audioTimestamp"], fromAudioTimestamp); + } + const fromThinkingConfig = getValueByPath(fromObject, ["thinkingConfig"]); + if (fromThinkingConfig != null) { + setValueByPath( + toObject, + ["thinkingConfig"], + thinkingConfigToVertex(fromThinkingConfig), + ); + } + return toObject; +} +function generateContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["generationConfig"], + generateContentConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function embedContentConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromTaskType = getValueByPath(fromObject, ["taskType"]); + if (parentObject !== undefined && fromTaskType != null) { + setValueByPath(parentObject, ["instances[]", "task_type"], fromTaskType); + } + const fromTitle = getValueByPath(fromObject, ["title"]); + if (parentObject !== undefined && fromTitle != null) { + setValueByPath(parentObject, ["instances[]", "title"], fromTitle); + } + const fromOutputDimensionality = getValueByPath(fromObject, [ + "outputDimensionality", + ]); + if (parentObject !== undefined && fromOutputDimensionality != null) { + setValueByPath( + parentObject, + ["parameters", "outputDimensionality"], + fromOutputDimensionality, + ); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (parentObject !== undefined && fromMimeType != null) { + setValueByPath(parentObject, ["instances[]", "mimeType"], fromMimeType); + } + const fromAutoTruncate = getValueByPath(fromObject, ["autoTruncate"]); + if (parentObject !== undefined && fromAutoTruncate != null) { + setValueByPath( + parentObject, + ["parameters", "autoTruncate"], + fromAutoTruncate, + ); + } + return toObject; +} +function embedContentParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + setValueByPath( + toObject, + ["instances[]", "content"], + tContentsForEmbed(apiClient, fromContents), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + embedContentConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function generateImagesConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromImageSize = getValueByPath(fromObject, ["imageSize"]); + if (parentObject !== undefined && fromImageSize != null) { + setValueByPath( + parentObject, + ["parameters", "sampleImageSize"], + fromImageSize, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + return toObject; +} +function generateImagesParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateImagesConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function imageToVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["imageBytes"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function maskReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromMaskMode = getValueByPath(fromObject, ["maskMode"]); + if (fromMaskMode != null) { + setValueByPath(toObject, ["maskMode"], fromMaskMode); + } + const fromSegmentationClasses = getValueByPath(fromObject, [ + "segmentationClasses", + ]); + if (fromSegmentationClasses != null) { + setValueByPath(toObject, ["maskClasses"], fromSegmentationClasses); + } + const fromMaskDilation = getValueByPath(fromObject, ["maskDilation"]); + if (fromMaskDilation != null) { + setValueByPath(toObject, ["dilation"], fromMaskDilation); + } + return toObject; +} +function controlReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromControlType = getValueByPath(fromObject, ["controlType"]); + if (fromControlType != null) { + setValueByPath(toObject, ["controlType"], fromControlType); + } + const fromEnableControlImageComputation = getValueByPath(fromObject, [ + "enableControlImageComputation", + ]); + if (fromEnableControlImageComputation != null) { + setValueByPath( + toObject, + ["computeControl"], + fromEnableControlImageComputation, + ); + } + return toObject; +} +function styleReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromStyleDescription = getValueByPath(fromObject, ["styleDescription"]); + if (fromStyleDescription != null) { + setValueByPath(toObject, ["styleDescription"], fromStyleDescription); + } + return toObject; +} +function subjectReferenceConfigToVertex(fromObject) { + const toObject = {}; + const fromSubjectType = getValueByPath(fromObject, ["subjectType"]); + if (fromSubjectType != null) { + setValueByPath(toObject, ["subjectType"], fromSubjectType); + } + const fromSubjectDescription = getValueByPath(fromObject, [ + "subjectDescription", + ]); + if (fromSubjectDescription != null) { + setValueByPath(toObject, ["subjectDescription"], fromSubjectDescription); + } + return toObject; +} +function referenceImageAPIInternalToVertex(fromObject) { + const toObject = {}; + const fromReferenceImage = getValueByPath(fromObject, ["referenceImage"]); + if (fromReferenceImage != null) { + setValueByPath( + toObject, + ["referenceImage"], + imageToVertex(fromReferenceImage), + ); + } + const fromReferenceId = getValueByPath(fromObject, ["referenceId"]); + if (fromReferenceId != null) { + setValueByPath(toObject, ["referenceId"], fromReferenceId); + } + const fromReferenceType = getValueByPath(fromObject, ["referenceType"]); + if (fromReferenceType != null) { + setValueByPath(toObject, ["referenceType"], fromReferenceType); + } + const fromMaskImageConfig = getValueByPath(fromObject, ["maskImageConfig"]); + if (fromMaskImageConfig != null) { + setValueByPath( + toObject, + ["maskImageConfig"], + maskReferenceConfigToVertex(fromMaskImageConfig), + ); + } + const fromControlImageConfig = getValueByPath(fromObject, [ + "controlImageConfig", + ]); + if (fromControlImageConfig != null) { + setValueByPath( + toObject, + ["controlImageConfig"], + controlReferenceConfigToVertex(fromControlImageConfig), + ); + } + const fromStyleImageConfig = getValueByPath(fromObject, ["styleImageConfig"]); + if (fromStyleImageConfig != null) { + setValueByPath( + toObject, + ["styleImageConfig"], + styleReferenceConfigToVertex(fromStyleImageConfig), + ); + } + const fromSubjectImageConfig = getValueByPath(fromObject, [ + "subjectImageConfig", + ]); + if (fromSubjectImageConfig != null) { + setValueByPath( + toObject, + ["subjectImageConfig"], + subjectReferenceConfigToVertex(fromSubjectImageConfig), + ); + } + return toObject; +} +function editImageConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromGuidanceScale = getValueByPath(fromObject, ["guidanceScale"]); + if (parentObject !== undefined && fromGuidanceScale != null) { + setValueByPath( + parentObject, + ["parameters", "guidanceScale"], + fromGuidanceScale, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromSafetyFilterLevel = getValueByPath(fromObject, [ + "safetyFilterLevel", + ]); + if (parentObject !== undefined && fromSafetyFilterLevel != null) { + setValueByPath( + parentObject, + ["parameters", "safetySetting"], + fromSafetyFilterLevel, + ); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromIncludeSafetyAttributes = getValueByPath(fromObject, [ + "includeSafetyAttributes", + ]); + if (parentObject !== undefined && fromIncludeSafetyAttributes != null) { + setValueByPath( + parentObject, + ["parameters", "includeSafetyAttributes"], + fromIncludeSafetyAttributes, + ); + } + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromLanguage = getValueByPath(fromObject, ["language"]); + if (parentObject !== undefined && fromLanguage != null) { + setValueByPath(parentObject, ["parameters", "language"], fromLanguage); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromAddWatermark = getValueByPath(fromObject, ["addWatermark"]); + if (parentObject !== undefined && fromAddWatermark != null) { + setValueByPath( + parentObject, + ["parameters", "addWatermark"], + fromAddWatermark, + ); + } + const fromEditMode = getValueByPath(fromObject, ["editMode"]); + if (parentObject !== undefined && fromEditMode != null) { + setValueByPath(parentObject, ["parameters", "editMode"], fromEditMode); + } + const fromBaseSteps = getValueByPath(fromObject, ["baseSteps"]); + if (parentObject !== undefined && fromBaseSteps != null) { + setValueByPath( + parentObject, + ["parameters", "editConfig", "baseSteps"], + fromBaseSteps, + ); + } + return toObject; +} +function editImageParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromReferenceImages = getValueByPath(fromObject, ["referenceImages"]); + if (fromReferenceImages != null) { + let transformedList = fromReferenceImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return referenceImageAPIInternalToVertex(item); + }); + } + setValueByPath( + toObject, + ["instances[0]", "referenceImages"], + transformedList, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + editImageConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function upscaleImageAPIConfigInternalToVertex(fromObject, parentObject) { + const toObject = {}; + const fromIncludeRaiReason = getValueByPath(fromObject, ["includeRaiReason"]); + if (parentObject !== undefined && fromIncludeRaiReason != null) { + setValueByPath( + parentObject, + ["parameters", "includeRaiReason"], + fromIncludeRaiReason, + ); + } + const fromOutputMimeType = getValueByPath(fromObject, ["outputMimeType"]); + if (parentObject !== undefined && fromOutputMimeType != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "mimeType"], + fromOutputMimeType, + ); + } + const fromOutputCompressionQuality = getValueByPath(fromObject, [ + "outputCompressionQuality", + ]); + if (parentObject !== undefined && fromOutputCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "outputOptions", "compressionQuality"], + fromOutputCompressionQuality, + ); + } + const fromEnhanceInputImage = getValueByPath(fromObject, [ + "enhanceInputImage", + ]); + if (parentObject !== undefined && fromEnhanceInputImage != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "enhanceInputImage"], + fromEnhanceInputImage, + ); + } + const fromImagePreservationFactor = getValueByPath(fromObject, [ + "imagePreservationFactor", + ]); + if (parentObject !== undefined && fromImagePreservationFactor != null) { + setValueByPath( + parentObject, + ["parameters", "upscaleConfig", "imagePreservationFactor"], + fromImagePreservationFactor, + ); + } + const fromNumberOfImages = getValueByPath(fromObject, ["numberOfImages"]); + if (parentObject !== undefined && fromNumberOfImages != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfImages, + ); + } + const fromMode = getValueByPath(fromObject, ["mode"]); + if (parentObject !== undefined && fromMode != null) { + setValueByPath(parentObject, ["parameters", "mode"], fromMode); + } + return toObject; +} +function upscaleImageAPIParametersInternalToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromUpscaleFactor = getValueByPath(fromObject, ["upscaleFactor"]); + if (fromUpscaleFactor != null) { + setValueByPath( + toObject, + ["parameters", "upscaleConfig", "upscaleFactor"], + fromUpscaleFactor, + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + upscaleImageAPIConfigInternalToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function getModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listModelsConfigToVertex(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + const fromQueryBase = getValueByPath(fromObject, ["queryBase"]); + if (parentObject !== undefined && fromQueryBase != null) { + setValueByPath( + parentObject, + ["_url", "models_url"], + tModelsUrl(apiClient, fromQueryBase), + ); + } + return toObject; +} +function listModelsParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listModelsConfigToVertex(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function updateModelConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (parentObject !== undefined && fromDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (parentObject !== undefined && fromDefaultCheckpointId != null) { + setValueByPath( + parentObject, + ["defaultCheckpointId"], + fromDefaultCheckpointId, + ); + } + return toObject; +} +function updateModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + updateModelConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function deleteModelParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "name"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function countTokensConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["systemInstruction"], + contentToVertex(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = fromTools; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToVertex(item); + }); + } + setValueByPath(parentObject, ["tools"], transformedList); + } + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath(parentObject, ["generationConfig"], fromGenerationConfig); + } + return toObject; +} +function countTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + countTokensConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function computeTokensParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromContents = getValueByPath(fromObject, ["contents"]); + if (fromContents != null) { + let transformedList = tContents(fromContents); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentToVertex(item); + }); + } + setValueByPath(toObject, ["contents"], transformedList); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function videoToVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["gcsUri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["videoBytes"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["bytesBase64Encoded"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generateVideosConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromNumberOfVideos = getValueByPath(fromObject, ["numberOfVideos"]); + if (parentObject !== undefined && fromNumberOfVideos != null) { + setValueByPath( + parentObject, + ["parameters", "sampleCount"], + fromNumberOfVideos, + ); + } + const fromOutputGcsUri = getValueByPath(fromObject, ["outputGcsUri"]); + if (parentObject !== undefined && fromOutputGcsUri != null) { + setValueByPath( + parentObject, + ["parameters", "storageUri"], + fromOutputGcsUri, + ); + } + const fromFps = getValueByPath(fromObject, ["fps"]); + if (parentObject !== undefined && fromFps != null) { + setValueByPath(parentObject, ["parameters", "fps"], fromFps); + } + const fromDurationSeconds = getValueByPath(fromObject, ["durationSeconds"]); + if (parentObject !== undefined && fromDurationSeconds != null) { + setValueByPath( + parentObject, + ["parameters", "durationSeconds"], + fromDurationSeconds, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath(parentObject, ["parameters", "seed"], fromSeed); + } + const fromAspectRatio = getValueByPath(fromObject, ["aspectRatio"]); + if (parentObject !== undefined && fromAspectRatio != null) { + setValueByPath( + parentObject, + ["parameters", "aspectRatio"], + fromAspectRatio, + ); + } + const fromResolution = getValueByPath(fromObject, ["resolution"]); + if (parentObject !== undefined && fromResolution != null) { + setValueByPath(parentObject, ["parameters", "resolution"], fromResolution); + } + const fromPersonGeneration = getValueByPath(fromObject, ["personGeneration"]); + if (parentObject !== undefined && fromPersonGeneration != null) { + setValueByPath( + parentObject, + ["parameters", "personGeneration"], + fromPersonGeneration, + ); + } + const fromPubsubTopic = getValueByPath(fromObject, ["pubsubTopic"]); + if (parentObject !== undefined && fromPubsubTopic != null) { + setValueByPath( + parentObject, + ["parameters", "pubsubTopic"], + fromPubsubTopic, + ); + } + const fromNegativePrompt = getValueByPath(fromObject, ["negativePrompt"]); + if (parentObject !== undefined && fromNegativePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "negativePrompt"], + fromNegativePrompt, + ); + } + const fromEnhancePrompt = getValueByPath(fromObject, ["enhancePrompt"]); + if (parentObject !== undefined && fromEnhancePrompt != null) { + setValueByPath( + parentObject, + ["parameters", "enhancePrompt"], + fromEnhancePrompt, + ); + } + const fromGenerateAudio = getValueByPath(fromObject, ["generateAudio"]); + if (parentObject !== undefined && fromGenerateAudio != null) { + setValueByPath( + parentObject, + ["parameters", "generateAudio"], + fromGenerateAudio, + ); + } + const fromLastFrame = getValueByPath(fromObject, ["lastFrame"]); + if (parentObject !== undefined && fromLastFrame != null) { + setValueByPath( + parentObject, + ["instances[0]", "lastFrame"], + imageToVertex(fromLastFrame), + ); + } + const fromCompressionQuality = getValueByPath(fromObject, [ + "compressionQuality", + ]); + if (parentObject !== undefined && fromCompressionQuality != null) { + setValueByPath( + parentObject, + ["parameters", "compressionQuality"], + fromCompressionQuality, + ); + } + return toObject; +} +function generateVideosParametersToVertex(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["_url", "model"], tModel(apiClient, fromModel)); + } + const fromPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromPrompt != null) { + setValueByPath(toObject, ["instances[0]", "prompt"], fromPrompt); + } + const fromImage = getValueByPath(fromObject, ["image"]); + if (fromImage != null) { + setValueByPath( + toObject, + ["instances[0]", "image"], + imageToVertex(fromImage), + ); + } + const fromVideo = getValueByPath(fromObject, ["video"]); + if (fromVideo != null) { + setValueByPath( + toObject, + ["instances[0]", "video"], + videoToVertex(fromVideo), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + generateVideosConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function videoMetadataFromMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromMldev(fromObject) { + const toObject = {}; + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromMldev(fromObject) { + const toObject = {}; + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromMldev(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citationSources"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromMldev(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromMldev(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromMldev(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromMldev(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromMldev(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromMldev(fromCitationMetadata), + ); + } + const fromTokenCount = getValueByPath(fromObject, ["tokenCount"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromMldev(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromMldev(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingFromMldev(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + return toObject; +} +function embedContentMetadataFromMldev() { + const toObject = {}; + return toObject; +} +function embedContentResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, ["embeddings"]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromMldev(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], embedContentMetadataFromMldev()); + } + return toObject; +} +function imageFromMldev(fromObject) { + const toObject = {}; + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromMldev(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromMldev(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromMldev(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromMldev(fromSafetyAttributes), + ); + } + return toObject; +} +function generateImagesResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromMldev(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function tunedModelInfoFromMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function modelFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["version"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromMldev(fromTunedModelInfo), + ); + } + const fromInputTokenLimit = getValueByPath(fromObject, ["inputTokenLimit"]); + if (fromInputTokenLimit != null) { + setValueByPath(toObject, ["inputTokenLimit"], fromInputTokenLimit); + } + const fromOutputTokenLimit = getValueByPath(fromObject, ["outputTokenLimit"]); + if (fromOutputTokenLimit != null) { + setValueByPath(toObject, ["outputTokenLimit"], fromOutputTokenLimit); + } + const fromSupportedActions = getValueByPath(fromObject, [ + "supportedGenerationMethods", + ]); + if (fromSupportedActions != null) { + setValueByPath(toObject, ["supportedActions"], fromSupportedActions); + } + return toObject; +} +function listModelsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromMldev(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromMldev() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + const fromCachedContentTokenCount = getValueByPath(fromObject, [ + "cachedContentTokenCount", + ]); + if (fromCachedContentTokenCount != null) { + setValueByPath( + toObject, + ["cachedContentTokenCount"], + fromCachedContentTokenCount, + ); + } + return toObject; +} +function videoFromMldev(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["video", "uri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["video", "encodedVideo"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["encoding"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromMldev(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromMldev(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromMldev(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["generatedSamples"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromMldev(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, [ + "response", + "generateVideoResponse", + ]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromMldev(fromResponse), + ); + } + return toObject; +} +function videoMetadataFromVertex(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataFromVertex(fromObject) { + const toObject = {}; + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partFromVertex(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataFromVertex(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobFromVertex(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataFromVertex(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentFromVertex(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partFromVertex(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function citationMetadataFromVertex(fromObject) { + const toObject = {}; + const fromCitations = getValueByPath(fromObject, ["citations"]); + if (fromCitations != null) { + setValueByPath(toObject, ["citations"], fromCitations); + } + return toObject; +} +function urlMetadataFromVertex(fromObject) { + const toObject = {}; + const fromRetrievedUrl = getValueByPath(fromObject, ["retrievedUrl"]); + if (fromRetrievedUrl != null) { + setValueByPath(toObject, ["retrievedUrl"], fromRetrievedUrl); + } + const fromUrlRetrievalStatus = getValueByPath(fromObject, [ + "urlRetrievalStatus", + ]); + if (fromUrlRetrievalStatus != null) { + setValueByPath(toObject, ["urlRetrievalStatus"], fromUrlRetrievalStatus); + } + return toObject; +} +function urlContextMetadataFromVertex(fromObject) { + const toObject = {}; + const fromUrlMetadata = getValueByPath(fromObject, ["urlMetadata"]); + if (fromUrlMetadata != null) { + let transformedList = fromUrlMetadata; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return urlMetadataFromVertex(item); + }); + } + setValueByPath(toObject, ["urlMetadata"], transformedList); + } + return toObject; +} +function candidateFromVertex(fromObject) { + const toObject = {}; + const fromContent = getValueByPath(fromObject, ["content"]); + if (fromContent != null) { + setValueByPath(toObject, ["content"], contentFromVertex(fromContent)); + } + const fromCitationMetadata = getValueByPath(fromObject, ["citationMetadata"]); + if (fromCitationMetadata != null) { + setValueByPath( + toObject, + ["citationMetadata"], + citationMetadataFromVertex(fromCitationMetadata), + ); + } + const fromFinishMessage = getValueByPath(fromObject, ["finishMessage"]); + if (fromFinishMessage != null) { + setValueByPath(toObject, ["finishMessage"], fromFinishMessage); + } + const fromFinishReason = getValueByPath(fromObject, ["finishReason"]); + if (fromFinishReason != null) { + setValueByPath(toObject, ["finishReason"], fromFinishReason); + } + const fromUrlContextMetadata = getValueByPath(fromObject, [ + "urlContextMetadata", + ]); + if (fromUrlContextMetadata != null) { + setValueByPath( + toObject, + ["urlContextMetadata"], + urlContextMetadataFromVertex(fromUrlContextMetadata), + ); + } + const fromAvgLogprobs = getValueByPath(fromObject, ["avgLogprobs"]); + if (fromAvgLogprobs != null) { + setValueByPath(toObject, ["avgLogprobs"], fromAvgLogprobs); + } + const fromGroundingMetadata = getValueByPath(fromObject, [ + "groundingMetadata", + ]); + if (fromGroundingMetadata != null) { + setValueByPath(toObject, ["groundingMetadata"], fromGroundingMetadata); + } + const fromIndex = getValueByPath(fromObject, ["index"]); + if (fromIndex != null) { + setValueByPath(toObject, ["index"], fromIndex); + } + const fromLogprobsResult = getValueByPath(fromObject, ["logprobsResult"]); + if (fromLogprobsResult != null) { + setValueByPath(toObject, ["logprobsResult"], fromLogprobsResult); + } + const fromSafetyRatings = getValueByPath(fromObject, ["safetyRatings"]); + if (fromSafetyRatings != null) { + setValueByPath(toObject, ["safetyRatings"], fromSafetyRatings); + } + return toObject; +} +function generateContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromCandidates = getValueByPath(fromObject, ["candidates"]); + if (fromCandidates != null) { + let transformedList = fromCandidates; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return candidateFromVertex(item); + }); + } + setValueByPath(toObject, ["candidates"], transformedList); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromResponseId = getValueByPath(fromObject, ["responseId"]); + if (fromResponseId != null) { + setValueByPath(toObject, ["responseId"], fromResponseId); + } + const fromModelVersion = getValueByPath(fromObject, ["modelVersion"]); + if (fromModelVersion != null) { + setValueByPath(toObject, ["modelVersion"], fromModelVersion); + } + const fromPromptFeedback = getValueByPath(fromObject, ["promptFeedback"]); + if (fromPromptFeedback != null) { + setValueByPath(toObject, ["promptFeedback"], fromPromptFeedback); + } + const fromUsageMetadata = getValueByPath(fromObject, ["usageMetadata"]); + if (fromUsageMetadata != null) { + setValueByPath(toObject, ["usageMetadata"], fromUsageMetadata); + } + return toObject; +} +function contentEmbeddingStatisticsFromVertex(fromObject) { + const toObject = {}; + const fromTruncated = getValueByPath(fromObject, ["truncated"]); + if (fromTruncated != null) { + setValueByPath(toObject, ["truncated"], fromTruncated); + } + const fromTokenCount = getValueByPath(fromObject, ["token_count"]); + if (fromTokenCount != null) { + setValueByPath(toObject, ["tokenCount"], fromTokenCount); + } + return toObject; +} +function contentEmbeddingFromVertex(fromObject) { + const toObject = {}; + const fromValues = getValueByPath(fromObject, ["values"]); + if (fromValues != null) { + setValueByPath(toObject, ["values"], fromValues); + } + const fromStatistics = getValueByPath(fromObject, ["statistics"]); + if (fromStatistics != null) { + setValueByPath( + toObject, + ["statistics"], + contentEmbeddingStatisticsFromVertex(fromStatistics), + ); + } + return toObject; +} +function embedContentMetadataFromVertex(fromObject) { + const toObject = {}; + const fromBillableCharacterCount = getValueByPath(fromObject, [ + "billableCharacterCount", + ]); + if (fromBillableCharacterCount != null) { + setValueByPath( + toObject, + ["billableCharacterCount"], + fromBillableCharacterCount, + ); + } + return toObject; +} +function embedContentResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromEmbeddings = getValueByPath(fromObject, [ + "predictions[]", + "embeddings", + ]); + if (fromEmbeddings != null) { + let transformedList = fromEmbeddings; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return contentEmbeddingFromVertex(item); + }); + } + setValueByPath(toObject, ["embeddings"], transformedList); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath( + toObject, + ["metadata"], + embedContentMetadataFromVertex(fromMetadata), + ); + } + return toObject; +} +function imageFromVertex(fromObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["gcsUri"], fromGcsUri); + } + const fromImageBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromImageBytes != null) { + setValueByPath(toObject, ["imageBytes"], tBytes(fromImageBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function safetyAttributesFromVertex(fromObject) { + const toObject = {}; + const fromCategories = getValueByPath(fromObject, [ + "safetyAttributes", + "categories", + ]); + if (fromCategories != null) { + setValueByPath(toObject, ["categories"], fromCategories); + } + const fromScores = getValueByPath(fromObject, ["safetyAttributes", "scores"]); + if (fromScores != null) { + setValueByPath(toObject, ["scores"], fromScores); + } + const fromContentType = getValueByPath(fromObject, ["contentType"]); + if (fromContentType != null) { + setValueByPath(toObject, ["contentType"], fromContentType); + } + return toObject; +} +function generatedImageFromVertex(fromObject) { + const toObject = {}; + const fromImage = getValueByPath(fromObject, ["_self"]); + if (fromImage != null) { + setValueByPath(toObject, ["image"], imageFromVertex(fromImage)); + } + const fromRaiFilteredReason = getValueByPath(fromObject, [ + "raiFilteredReason", + ]); + if (fromRaiFilteredReason != null) { + setValueByPath(toObject, ["raiFilteredReason"], fromRaiFilteredReason); + } + const fromSafetyAttributes = getValueByPath(fromObject, ["_self"]); + if (fromSafetyAttributes != null) { + setValueByPath( + toObject, + ["safetyAttributes"], + safetyAttributesFromVertex(fromSafetyAttributes), + ); + } + const fromEnhancedPrompt = getValueByPath(fromObject, ["prompt"]); + if (fromEnhancedPrompt != null) { + setValueByPath(toObject, ["enhancedPrompt"], fromEnhancedPrompt); + } + return toObject; +} +function generateImagesResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + const fromPositivePromptSafetyAttributes = getValueByPath(fromObject, [ + "positivePromptSafetyAttributes", + ]); + if (fromPositivePromptSafetyAttributes != null) { + setValueByPath( + toObject, + ["positivePromptSafetyAttributes"], + safetyAttributesFromVertex(fromPositivePromptSafetyAttributes), + ); + } + return toObject; +} +function editImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function upscaleImageResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromGeneratedImages = getValueByPath(fromObject, ["predictions"]); + if (fromGeneratedImages != null) { + let transformedList = fromGeneratedImages; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedImageFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedImages"], transformedList); + } + return toObject; +} +function endpointFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["endpoint"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDeployedModelId = getValueByPath(fromObject, ["deployedModelId"]); + if (fromDeployedModelId != null) { + setValueByPath(toObject, ["deployedModelId"], fromDeployedModelId); + } + return toObject; +} +function tunedModelInfoFromVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, [ + "labels", + "google-vertex-llm-tuning-base-model-id", + ]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + return toObject; +} +function checkpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + return toObject; +} +function modelFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromDisplayName = getValueByPath(fromObject, ["displayName"]); + if (fromDisplayName != null) { + setValueByPath(toObject, ["displayName"], fromDisplayName); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromVersion = getValueByPath(fromObject, ["versionId"]); + if (fromVersion != null) { + setValueByPath(toObject, ["version"], fromVersion); + } + const fromEndpoints = getValueByPath(fromObject, ["deployedModels"]); + if (fromEndpoints != null) { + let transformedList = fromEndpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return endpointFromVertex(item); + }); + } + setValueByPath(toObject, ["endpoints"], transformedList); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromTunedModelInfo = getValueByPath(fromObject, ["_self"]); + if (fromTunedModelInfo != null) { + setValueByPath( + toObject, + ["tunedModelInfo"], + tunedModelInfoFromVertex(fromTunedModelInfo), + ); + } + const fromDefaultCheckpointId = getValueByPath(fromObject, [ + "defaultCheckpointId", + ]); + if (fromDefaultCheckpointId != null) { + setValueByPath(toObject, ["defaultCheckpointId"], fromDefaultCheckpointId); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return checkpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function listModelsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromModels = getValueByPath(fromObject, ["_self"]); + if (fromModels != null) { + let transformedList = tExtractModels(fromModels); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return modelFromVertex(item); + }); + } + setValueByPath(toObject, ["models"], transformedList); + } + return toObject; +} +function deleteModelResponseFromVertex() { + const toObject = {}; + return toObject; +} +function countTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTotalTokens = getValueByPath(fromObject, ["totalTokens"]); + if (fromTotalTokens != null) { + setValueByPath(toObject, ["totalTokens"], fromTotalTokens); + } + return toObject; +} +function computeTokensResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromTokensInfo = getValueByPath(fromObject, ["tokensInfo"]); + if (fromTokensInfo != null) { + setValueByPath(toObject, ["tokensInfo"], fromTokensInfo); + } + return toObject; +} +function videoFromVertex(fromObject) { + const toObject = {}; + const fromUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromUri != null) { + setValueByPath(toObject, ["uri"], fromUri); + } + const fromVideoBytes = getValueByPath(fromObject, ["bytesBase64Encoded"]); + if (fromVideoBytes != null) { + setValueByPath(toObject, ["videoBytes"], tBytes(fromVideoBytes)); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function generatedVideoFromVertex(fromObject) { + const toObject = {}; + const fromVideo = getValueByPath(fromObject, ["_self"]); + if (fromVideo != null) { + setValueByPath(toObject, ["video"], videoFromVertex(fromVideo)); + } + return toObject; +} +function generateVideosResponseFromVertex(fromObject) { + const toObject = {}; + const fromGeneratedVideos = getValueByPath(fromObject, ["videos"]); + if (fromGeneratedVideos != null) { + let transformedList = fromGeneratedVideos; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return generatedVideoFromVertex(item); + }); + } + setValueByPath(toObject, ["generatedVideos"], transformedList); + } + const fromRaiMediaFilteredCount = getValueByPath(fromObject, [ + "raiMediaFilteredCount", + ]); + if (fromRaiMediaFilteredCount != null) { + setValueByPath( + toObject, + ["raiMediaFilteredCount"], + fromRaiMediaFilteredCount, + ); + } + const fromRaiMediaFilteredReasons = getValueByPath(fromObject, [ + "raiMediaFilteredReasons", + ]); + if (fromRaiMediaFilteredReasons != null) { + setValueByPath( + toObject, + ["raiMediaFilteredReasons"], + fromRaiMediaFilteredReasons, + ); + } + return toObject; +} +function generateVideosOperationFromVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath( + toObject, + ["response"], + generateVideosResponseFromVertex(fromResponse), + ); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const CONTENT_TYPE_HEADER = "Content-Type"; +const SERVER_TIMEOUT_HEADER = "X-Server-Timeout"; +const USER_AGENT_HEADER = "User-Agent"; +const GOOGLE_API_CLIENT_HEADER = "x-goog-api-client"; +const SDK_VERSION = "1.11.0"; // x-release-please-version +const LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`; +const VERTEX_AI_API_DEFAULT_VERSION = "v1beta1"; +const GOOGLE_AI_API_DEFAULT_VERSION = "v1beta"; +const responseLineRE = /^data: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +class ApiClient { + constructor(opts) { + var _a, _b; + this.clientOptions = Object.assign(Object.assign({}, opts), { + project: opts.project, + location: opts.location, + apiKey: opts.apiKey, + vertexai: opts.vertexai, + }); + const initHttpOptions = {}; + if (this.clientOptions.vertexai) { + initHttpOptions.apiVersion = + (_a = this.clientOptions.apiVersion) !== null && _a !== void 0 + ? _a + : VERTEX_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = this.baseUrlFromProjectLocation(); + this.normalizeAuthParameters(); + } else { + // Gemini API + initHttpOptions.apiVersion = + (_b = this.clientOptions.apiVersion) !== null && _b !== void 0 + ? _b + : GOOGLE_AI_API_DEFAULT_VERSION; + initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`; + } + initHttpOptions.headers = this.getDefaultHeaders(); + this.clientOptions.httpOptions = initHttpOptions; + if (opts.httpOptions) { + this.clientOptions.httpOptions = this.patchHttpOptions( + initHttpOptions, + opts.httpOptions, + ); + } + } + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + baseUrlFromProjectLocation() { + if ( + this.clientOptions.project && + this.clientOptions.location && + this.clientOptions.location !== "global" + ) { + // Regional endpoint + return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`; + } + // Global endpoint (covers 'global' location and API key usage) + return `https://aiplatform.googleapis.com/`; + } + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + normalizeAuthParameters() { + if (this.clientOptions.project && this.clientOptions.location) { + // Using project/location for auth, clear potential API key + this.clientOptions.apiKey = undefined; + return; + } + // Using API key for auth (or no auth provided yet), clear project/location + this.clientOptions.project = undefined; + this.clientOptions.location = undefined; + } + isVertexAI() { + var _a; + return (_a = this.clientOptions.vertexai) !== null && _a !== void 0 + ? _a + : false; + } + getProject() { + return this.clientOptions.project; + } + getLocation() { + return this.clientOptions.location; + } + getApiVersion() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.apiVersion !== undefined + ) { + return this.clientOptions.httpOptions.apiVersion; + } + throw new Error("API version is not set."); + } + getBaseUrl() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.baseUrl !== undefined + ) { + return this.clientOptions.httpOptions.baseUrl; + } + throw new Error("Base URL is not set."); + } + getRequestUrl() { + return this.getRequestUrlInternal(this.clientOptions.httpOptions); + } + getHeaders() { + if ( + this.clientOptions.httpOptions && + this.clientOptions.httpOptions.headers !== undefined + ) { + return this.clientOptions.httpOptions.headers; + } else { + throw new Error("Headers are not set."); + } + } + getRequestUrlInternal(httpOptions) { + if ( + !httpOptions || + httpOptions.baseUrl === undefined || + httpOptions.apiVersion === undefined + ) { + throw new Error("HTTP options are not correctly set."); + } + const baseUrl = httpOptions.baseUrl.endsWith("/") + ? httpOptions.baseUrl.slice(0, -1) + : httpOptions.baseUrl; + const urlElement = [baseUrl]; + if (httpOptions.apiVersion && httpOptions.apiVersion !== "") { + urlElement.push(httpOptions.apiVersion); + } + return urlElement.join("/"); + } + getBaseResourcePath() { + return `projects/${this.clientOptions.project}/locations/${this.clientOptions.location}`; + } + getApiKey() { + return this.clientOptions.apiKey; + } + getWebsocketBaseUrl() { + const baseUrl = this.getBaseUrl(); + const urlParts = new URL(baseUrl); + urlParts.protocol = urlParts.protocol == "http:" ? "ws" : "wss"; + return urlParts.toString(); + } + setBaseUrl(url) { + if (this.clientOptions.httpOptions) { + this.clientOptions.httpOptions.baseUrl = url; + } else { + throw new Error("HTTP options are not correctly set."); + } + } + constructUrl(path, httpOptions, prependProjectLocation) { + const urlElement = [this.getRequestUrlInternal(httpOptions)]; + if (prependProjectLocation) { + urlElement.push(this.getBaseResourcePath()); + } + if (path !== "") { + urlElement.push(path); + } + const url = new URL(`${urlElement.join("/")}`); + return url; + } + shouldPrependVertexProjectPath(request) { + if (this.clientOptions.apiKey) { + return false; + } + if (!this.clientOptions.vertexai) { + return false; + } + if (request.path.startsWith("projects/")) { + // Assume the path already starts with + // `projects//location/`. + return false; + } + if ( + request.httpMethod === "GET" && + request.path.startsWith("publishers/google/models") + ) { + // These paths are used by Vertex's models.get and models.list + // calls. For base models Vertex does not accept a project/location + // prefix (for tuned model the prefix is required). + return false; + } + return true; + } + async request(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (request.queryParams) { + for (const [key, value] of Object.entries(request.queryParams)) { + url.searchParams.append(key, String(value)); + } + } + let requestInit = {}; + if (request.httpMethod === "GET") { + if (request.body && request.body !== "{}") { + throw new Error( + "Request body should be empty for GET request, but got non empty request body", + ); + } + } else { + requestInit.body = request.body; + } + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.unaryApiCall(url, requestInit, request.httpMethod); + } + patchHttpOptions(baseHttpOptions, requestHttpOptions) { + const patchedHttpOptions = JSON.parse(JSON.stringify(baseHttpOptions)); + for (const [key, value] of Object.entries(requestHttpOptions)) { + // Records compile to objects. + if (typeof value === "object") { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = Object.assign( + Object.assign({}, patchedHttpOptions[key]), + value, + ); + } else if (value !== undefined) { + // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type + // because expression of type 'string' can't be used to index type + // 'HttpOptions'. + patchedHttpOptions[key] = value; + } + } + return patchedHttpOptions; + } + async requestStream(request) { + let patchedHttpOptions = this.clientOptions.httpOptions; + if (request.httpOptions) { + patchedHttpOptions = this.patchHttpOptions( + this.clientOptions.httpOptions, + request.httpOptions, + ); + } + const prependProjectLocation = this.shouldPrependVertexProjectPath(request); + const url = this.constructUrl( + request.path, + patchedHttpOptions, + prependProjectLocation, + ); + if (!url.searchParams.has("alt") || url.searchParams.get("alt") !== "sse") { + url.searchParams.set("alt", "sse"); + } + let requestInit = {}; + requestInit.body = request.body; + requestInit = await this.includeExtraHttpOptionsToRequestInit( + requestInit, + patchedHttpOptions, + request.abortSignal, + ); + return this.streamApiCall(url, requestInit, request.httpMethod); + } + async includeExtraHttpOptionsToRequestInit( + requestInit, + httpOptions, + abortSignal, + ) { + if ((httpOptions && httpOptions.timeout) || abortSignal) { + const abortController = new AbortController(); + const signal = abortController.signal; + if ( + httpOptions.timeout && + (httpOptions === null || httpOptions === void 0 + ? void 0 + : httpOptions.timeout) > 0 + ) { + const timeoutHandle = setTimeout( + () => abortController.abort(), + httpOptions.timeout, + ); + if (timeoutHandle && typeof timeoutHandle.unref === "function") { + // call unref to prevent nodejs process from hanging, see + // https://nodejs.org/api/timers.html#timeoutunref + timeoutHandle.unref(); + } + } + if (abortSignal) { + abortSignal.addEventListener("abort", () => { + abortController.abort(); + }); + } + requestInit.signal = signal; + } + if (httpOptions && httpOptions.extraBody !== null) { + includeExtraBodyToRequestInit(requestInit, httpOptions.extraBody); + } + requestInit.headers = await this.getHeadersInternal(httpOptions); + return requestInit; + } + async unaryApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return new HttpResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + async streamApiCall(url, requestInit, httpMethod) { + return this.apiCall( + url.toString(), + Object.assign(Object.assign({}, requestInit), { method: httpMethod }), + ) + .then(async (response) => { + await throwErrorIfNotOK(response); + return this.processStreamResponse(response); + }) + .catch((e) => { + if (e instanceof Error) { + throw e; + } else { + throw new Error(JSON.stringify(e)); + } + }); + } + processStreamResponse(response) { + var _a; + return __asyncGenerator( + this, + arguments, + function* processStreamResponse_1() { + const reader = + (_a = + response === null || response === void 0 + ? void 0 + : response.body) === null || _a === void 0 + ? void 0 + : _a.getReader(); + const decoder = new TextDecoder("utf-8"); + if (!reader) { + throw new Error("Response body is empty"); + } + try { + let buffer = ""; + while (true) { + const { done, value } = yield __await(reader.read()); + if (done) { + if (buffer.trim().length > 0) { + throw new Error("Incomplete JSON segment at the end"); + } + break; + } + const chunkString = decoder.decode(value, { stream: true }); + // Parse and throw an error if the chunk contains an error. + try { + const chunkJson = JSON.parse(chunkString); + if ("error" in chunkJson) { + const errorJson = JSON.parse( + JSON.stringify(chunkJson["error"]), + ); + const status = errorJson["status"]; + const code = errorJson["code"]; + const errorMessage = `got status: ${status}. ${JSON.stringify(chunkJson)}`; + if (code >= 400 && code < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: code, + }); + throw apiError; + } + } + } catch (e) { + const error = e; + if (error.name === "ApiError") { + throw e; + } + } + buffer += chunkString; + let match = buffer.match(responseLineRE); + while (match) { + const processedChunkString = match[1]; + try { + const partialResponse = new Response(processedChunkString, { + headers: + response === null || response === void 0 + ? void 0 + : response.headers, + status: + response === null || response === void 0 + ? void 0 + : response.status, + statusText: + response === null || response === void 0 + ? void 0 + : response.statusText, + }); + yield yield __await(new HttpResponse(partialResponse)); + buffer = buffer.slice(match[0].length); + match = buffer.match(responseLineRE); + } catch (e) { + throw new Error( + `exception parsing stream chunk ${processedChunkString}. ${e}`, + ); + } + } + } + } finally { + reader.releaseLock(); + } + }, + ); + } + async apiCall(url, requestInit) { + return fetch(url, requestInit).catch((e) => { + throw new Error(`exception ${e} sending request`); + }); + } + getDefaultHeaders() { + const headers = {}; + const versionHeaderValue = + LIBRARY_LABEL + " " + this.clientOptions.userAgentExtra; + headers[USER_AGENT_HEADER] = versionHeaderValue; + headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue; + headers[CONTENT_TYPE_HEADER] = "application/json"; + return headers; + } + async getHeadersInternal(httpOptions) { + const headers = new Headers(); + if (httpOptions && httpOptions.headers) { + for (const [key, value] of Object.entries(httpOptions.headers)) { + headers.append(key, value); + } + // Append a timeout header if it is set, note that the timeout option is + // in milliseconds but the header is in seconds. + if (httpOptions.timeout && httpOptions.timeout > 0) { + headers.append( + SERVER_TIMEOUT_HEADER, + String(Math.ceil(httpOptions.timeout / 1000)), + ); + } + } + await this.clientOptions.auth.addAuthHeaders(headers); + return headers; + } + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + async uploadFile(file, config) { + var _a; + const fileToUpload = {}; + if (config != null) { + fileToUpload.mimeType = config.mimeType; + fileToUpload.name = config.name; + fileToUpload.displayName = config.displayName; + } + if (fileToUpload.name && !fileToUpload.name.startsWith("files/")) { + fileToUpload.name = `files/${fileToUpload.name}`; + } + const uploader = this.clientOptions.uploader; + const fileStat = await uploader.stat(file); + fileToUpload.sizeBytes = String(fileStat.size); + const mimeType = + (_a = config === null || config === void 0 ? void 0 : config.mimeType) !== + null && _a !== void 0 + ? _a + : fileStat.type; + if (mimeType === undefined || mimeType === "") { + throw new Error( + "Can not determine mimeType. Please provide mimeType in the config.", + ); + } + fileToUpload.mimeType = mimeType; + const uploadUrl = await this.fetchUploadUrl(fileToUpload, config); + return uploader.upload(file, uploadUrl, this); + } + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + async downloadFile(params) { + const downloader = this.clientOptions.downloader; + await downloader.download(params, this); + } + async fetchUploadUrl(file, config) { + var _a; + let httpOptions = {}; + if (config === null || config === void 0 ? void 0 : config.httpOptions) { + httpOptions = config.httpOptions; + } else { + httpOptions = { + apiVersion: "", + headers: { + "Content-Type": "application/json", + "X-Goog-Upload-Protocol": "resumable", + "X-Goog-Upload-Command": "start", + "X-Goog-Upload-Header-Content-Length": `${file.sizeBytes}`, + "X-Goog-Upload-Header-Content-Type": `${file.mimeType}`, + }, + }; + } + const body = { + file: file, + }; + const httpResponse = await this.request({ + path: formatMap("upload/v1beta/files", body["_url"]), + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions, + }); + if ( + !httpResponse || + !(httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) + ) { + throw new Error( + "Server did not return an HttpResponse or the returned HttpResponse did not have headers.", + ); + } + const uploadUrl = + (_a = + httpResponse === null || httpResponse === void 0 + ? void 0 + : httpResponse.headers) === null || _a === void 0 + ? void 0 + : _a["x-goog-upload-url"]; + if (uploadUrl === undefined) { + throw new Error( + "Failed to get upload url. Server did not return the x-google-upload-url in the headers", + ); + } + return uploadUrl; + } +} +async function throwErrorIfNotOK(response) { + var _a; + if (response === undefined) { + throw new Error("response is undefined"); + } + if (!response.ok) { + const status = response.status; + let errorBody; + if ( + (_a = response.headers.get("content-type")) === null || _a === void 0 + ? void 0 + : _a.includes("application/json") + ) { + errorBody = await response.json(); + } else { + errorBody = { + error: { + message: await response.text(), + code: response.status, + status: response.statusText, + }, + }; + } + const errorMessage = JSON.stringify(errorBody); + if (status >= 400 && status < 600) { + const apiError = new ApiError({ + message: errorMessage, + status: status, + }); + throw apiError; + } + throw new Error(errorMessage); + } +} +/** + * Recursively updates the `requestInit.body` with values from an `extraBody` object. + * + * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed. + * The `extraBody` is then deeply merged into this parsed object. + * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged, + * as merging structured data into an opaque Blob is not supported. + * + * The function does not enforce that updated values from `extraBody` have the + * same type as existing values in `requestInit.body`. Type mismatches during + * the merge will result in a warning, but the value from `extraBody` will overwrite + * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure. + * + * @param requestInit The RequestInit object whose body will be updated. + * @param extraBody The object containing updates to be merged into `requestInit.body`. + */ +function includeExtraBodyToRequestInit(requestInit, extraBody) { + if (!extraBody || Object.keys(extraBody).length === 0) { + return; + } + if (requestInit.body instanceof Blob) { + console.warn( + "includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.", + ); + return; + } + let currentBodyObject = {}; + // If adding new type to HttpRequest.body, please check the code below to + // see if we need to update the logic. + if (typeof requestInit.body === "string" && requestInit.body.length > 0) { + try { + const parsedBody = JSON.parse(requestInit.body); + if ( + typeof parsedBody === "object" && + parsedBody !== null && + !Array.isArray(parsedBody) + ) { + currentBodyObject = parsedBody; + } else { + console.warn( + "includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.", + ); + return; + } + /* eslint-disable-next-line @typescript-eslint/no-unused-vars */ + } catch (e) { + console.warn( + "includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.", + ); + return; + } + } + function deepMerge(target, source) { + const output = Object.assign({}, target); + for (const key in source) { + if (Object.prototype.hasOwnProperty.call(source, key)) { + const sourceValue = source[key]; + const targetValue = output[key]; + if ( + sourceValue && + typeof sourceValue === "object" && + !Array.isArray(sourceValue) && + targetValue && + typeof targetValue === "object" && + !Array.isArray(targetValue) + ) { + output[key] = deepMerge(targetValue, sourceValue); + } else { + if ( + targetValue && + sourceValue && + typeof targetValue !== typeof sourceValue + ) { + console.warn( + `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key "${key}". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`, + ); + } + output[key] = sourceValue; + } + } + } + return output; + } + const mergedBody = deepMerge(currentBodyObject, extraBody); + requestInit.body = JSON.stringify(mergedBody); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// TODO: b/416041229 - Determine how to retrieve the MCP package version. +const MCP_LABEL = "mcp_used/unknown"; +// Whether MCP tool usage is detected from mcpToTool. This is used for +// telemetry. +let hasMcpToolUsageFromMcpToTool = false; +// Checks whether the list of tools contains any MCP tools. +function hasMcpToolUsage(tools) { + for (const tool of tools) { + if (isMcpCallableTool(tool)) { + return true; + } + if (typeof tool === "object" && "inputSchema" in tool) { + return true; + } + } + return hasMcpToolUsageFromMcpToTool; +} +// Sets the MCP version label in the Google API client header. +function setMcpUsageHeader(headers) { + var _a; + const existingHeader = + (_a = headers[GOOGLE_API_CLIENT_HEADER]) !== null && _a !== void 0 + ? _a + : ""; + headers[GOOGLE_API_CLIENT_HEADER] = ( + existingHeader + ` ${MCP_LABEL}` + ).trimStart(); +} +// Returns true if the object is a MCP CallableTool, otherwise false. +function isMcpCallableTool(object) { + return ( + object !== null && + typeof object === "object" && + object instanceof McpCallableTool + ); +} +// List all tools from the MCP client. +function listAllTools(mcpClient, maxTools = 100) { + return __asyncGenerator(this, arguments, function* listAllTools_1() { + let cursor = undefined; + let numTools = 0; + while (numTools < maxTools) { + const t = yield __await(mcpClient.listTools({ cursor })); + for (const tool of t.tools) { + yield yield __await(tool); + numTools++; + } + if (!t.nextCursor) { + break; + } + cursor = t.nextCursor; + } + }); +} +/** + * McpCallableTool can be used for model inference and invoking MCP clients with + * given function call arguments. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +class McpCallableTool { + constructor(mcpClients = [], config) { + this.mcpTools = []; + this.functionNameToMcpClient = {}; + this.mcpClients = mcpClients; + this.config = config; + } + /** + * Creates a McpCallableTool. + */ + static create(mcpClients, config) { + return new McpCallableTool(mcpClients, config); + } + /** + * Validates the function names are not duplicate and initialize the function + * name to MCP client mapping. + * + * @throws {Error} if the MCP tools from the MCP clients have duplicate tool + * names. + */ + async initialize() { + var _a, e_1, _b, _c; + if (this.mcpTools.length > 0) { + return; + } + const functionMap = {}; + const mcpTools = []; + for (const mcpClient of this.mcpClients) { + try { + for ( + var _d = true, + _e = ((e_1 = void 0), __asyncValues(listAllTools(mcpClient))), + _f; + (_f = await _e.next()), (_a = _f.done), !_a; + _d = true + ) { + _c = _f.value; + _d = false; + const mcpTool = _c; + mcpTools.push(mcpTool); + const mcpToolName = mcpTool.name; + if (functionMap[mcpToolName]) { + throw new Error( + `Duplicate function name ${mcpToolName} found in MCP tools. Please ensure function names are unique.`, + ); + } + functionMap[mcpToolName] = mcpClient; + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_d && !_a && (_b = _e.return)) await _b.call(_e); + } finally { + if (e_1) throw e_1.error; + } + } + } + this.mcpTools = mcpTools; + this.functionNameToMcpClient = functionMap; + } + async tool() { + await this.initialize(); + return mcpToolsToGeminiTool(this.mcpTools, this.config); + } + async callTool(functionCalls) { + await this.initialize(); + const functionCallResponseParts = []; + for (const functionCall of functionCalls) { + if (functionCall.name in this.functionNameToMcpClient) { + const mcpClient = this.functionNameToMcpClient[functionCall.name]; + let requestOptions = undefined; + // TODO: b/424238654 - Add support for finer grained timeout control. + if (this.config.timeout) { + requestOptions = { + timeout: this.config.timeout, + }; + } + const callToolResponse = await mcpClient.callTool( + { + name: functionCall.name, + arguments: functionCall.args, + }, + // Set the result schema to undefined to allow MCP to rely on the + // default schema. + undefined, + requestOptions, + ); + functionCallResponseParts.push({ + functionResponse: { + name: functionCall.name, + response: callToolResponse.isError + ? { error: callToolResponse } + : callToolResponse, + }, + }); + } + } + return functionCallResponseParts; + } +} +function isMcpClient(client) { + return ( + client !== null && + typeof client === "object" && + "listTools" in client && + typeof client.listTools === "function" + ); +} +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +function mcpToTool(...args) { + // Set MCP usage for telemetry. + hasMcpToolUsageFromMcpToTool = true; + if (args.length === 0) { + throw new Error("No MCP clients provided"); + } + const maybeConfig = args[args.length - 1]; + if (isMcpClient(maybeConfig)) { + return McpCallableTool.create(args, {}); + } + return McpCallableTool.create(args.slice(0, args.length - 1), maybeConfig); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveMusicServerMessage, and then calling the onmessage callback. + * Note that the first message which is received from the server is a + * setupComplete message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage$1(apiClient, onmessage, event) { + const serverMessage = new LiveMusicServerMessage(); + let data; + if (event.data instanceof Blob) { + data = JSON.parse(await event.data.text()); + } else { + data = JSON.parse(event.data); + } + const response = liveMusicServerMessageFromMldev(data); + Object.assign(serverMessage, response); + onmessage(serverMessage); +} +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +class LiveMusic { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + } + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b; + if (this.apiClient.isVertexAI()) { + throw new Error("Live music is not supported for Vertex AI."); + } + console.warn( + "Live music generation is experimental and may change in future versions.", + ); + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + const headers = mapToHeaders$1(this.apiClient.getDefaultHeaders()); + const apiKey = this.apiClient.getApiKey(); + const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.BidiGenerateMusic?key=${apiKey}`; + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage$1(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap$1(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + const model = tModel(this.apiClient, params.model); + const setup = liveMusicClientSetupToMldev({ + model, + }); + const clientMessage = liveMusicClientMessageToMldev({ setup }); + conn.send(JSON.stringify(clientMessage)); + return new LiveMusicSession(conn, this.apiClient); + } +} +/** + Represents a connection to the API. + + @experimental + */ +class LiveMusicSession { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + async setWeightedPrompts(params) { + if ( + !params.weightedPrompts || + Object.keys(params.weightedPrompts).length === 0 + ) { + throw new Error( + "Weighted prompts must be set and contain at least one entry.", + ); + } + const setWeightedPromptsParameters = + liveMusicSetWeightedPromptsParametersToMldev(params); + const clientContent = liveMusicClientContentToMldev( + setWeightedPromptsParameters, + ); + this.conn.send(JSON.stringify({ clientContent })); + } + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + async setMusicGenerationConfig(params) { + if (!params.musicGenerationConfig) { + params.musicGenerationConfig = {}; + } + const setConfigParameters = liveMusicSetConfigParametersToMldev(params); + const clientMessage = liveMusicClientMessageToMldev(setConfigParameters); + this.conn.send(JSON.stringify(clientMessage)); + } + sendPlaybackControl(playbackControl) { + const clientMessage = liveMusicClientMessageToMldev({ + playbackControl, + }); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + * Start the music stream. + * + * @experimental + */ + play() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PLAY); + } + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause() { + this.sendPlaybackControl(LiveMusicPlaybackControl.PAUSE); + } + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop() { + this.sendPlaybackControl(LiveMusicPlaybackControl.STOP); + } + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext() { + this.sendPlaybackControl(LiveMusicPlaybackControl.RESET_CONTEXT); + } + /** + Terminates the WebSocket connection. + + @experimental + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap$1(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders$1(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const FUNCTION_RESPONSE_REQUIRES_ID = + "FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI."; +/** + * Handles incoming messages from the WebSocket. + * + * @remarks + * This function is responsible for parsing incoming messages, transforming them + * into LiveServerMessages, and then calling the onmessage callback. Note that + * the first message which is received from the server is a setupComplete + * message. + * + * @param apiClient The ApiClient instance. + * @param onmessage The user-provided onmessage callback (if any). + * @param event The MessageEvent from the WebSocket. + */ +async function handleWebSocketMessage(apiClient, onmessage, event) { + const serverMessage = new LiveServerMessage(); + let jsonData; + if (event.data instanceof Blob) { + jsonData = await event.data.text(); + } else if (event.data instanceof ArrayBuffer) { + jsonData = new TextDecoder().decode(event.data); + } else { + jsonData = event.data; + } + const data = JSON.parse(jsonData); + if (apiClient.isVertexAI()) { + const resp = liveServerMessageFromVertex(data); + Object.assign(serverMessage, resp); + } else { + const resp = liveServerMessageFromMldev(data); + Object.assign(serverMessage, resp); + } + onmessage(serverMessage); +} +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +class Live { + constructor(apiClient, auth, webSocketFactory) { + this.apiClient = apiClient; + this.auth = auth; + this.webSocketFactory = webSocketFactory; + this.music = new LiveMusic( + this.apiClient, + this.auth, + this.webSocketFactory, + ); + } + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + async connect(params) { + var _a, _b, _c, _d, _e, _f; + // TODO: b/404946746 - Support per request HTTP options. + if (params.config && params.config.httpOptions) { + throw new Error( + "The Live module does not support httpOptions at request-level in" + + " LiveConnectConfig yet. Please use the client-level httpOptions" + + " configuration instead.", + ); + } + const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl(); + const apiVersion = this.apiClient.getApiVersion(); + let url; + const defaultHeaders = this.apiClient.getDefaultHeaders(); + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + setMcpUsageHeader(defaultHeaders); + } + const headers = mapToHeaders(defaultHeaders); + if (this.apiClient.isVertexAI()) { + url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${apiVersion}.LlmBidiService/BidiGenerateContent`; + await this.auth.addAuthHeaders(headers); + } else { + const apiKey = this.apiClient.getApiKey(); + let method = "BidiGenerateContent"; + let keyName = "key"; + if ( + apiKey === null || apiKey === void 0 + ? void 0 + : apiKey.startsWith("auth_tokens/") + ) { + console.warn( + "Warning: Ephemeral token support is experimental and may change in future versions.", + ); + if (apiVersion !== "v1alpha") { + 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.", + ); + } + method = "BidiGenerateContentConstrained"; + keyName = "access_token"; + } + url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${apiVersion}.GenerativeService.${method}?${keyName}=${apiKey}`; + } + let onopenResolve = () => {}; + const onopenPromise = new Promise((resolve) => { + onopenResolve = resolve; + }); + const callbacks = params.callbacks; + const onopenAwaitedCallback = function () { + var _a; + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onopen) === null || _a === void 0 + ? void 0 + : _a.call(callbacks); + onopenResolve({}); + }; + const apiClient = this.apiClient; + const websocketCallbacks = { + onopen: onopenAwaitedCallback, + onmessage: (event) => { + void handleWebSocketMessage(apiClient, callbacks.onmessage, event); + }, + onerror: + (_a = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onerror) !== null && _a !== void 0 + ? _a + : function (e) {}, + onclose: + (_b = + callbacks === null || callbacks === void 0 + ? void 0 + : callbacks.onclose) !== null && _b !== void 0 + ? _b + : function (e) {}, + }; + const conn = this.webSocketFactory.create( + url, + headersToMap(headers), + websocketCallbacks, + ); + conn.connect(); + // Wait for the websocket to open before sending requests. + await onopenPromise; + let transformedModel = tModel(this.apiClient, params.model); + if ( + this.apiClient.isVertexAI() && + transformedModel.startsWith("publishers/") + ) { + const project = this.apiClient.getProject(); + const location = this.apiClient.getLocation(); + transformedModel = + `projects/${project}/locations/${location}/` + transformedModel; + } + let clientMessage = {}; + if ( + this.apiClient.isVertexAI() && + ((_c = params.config) === null || _c === void 0 + ? void 0 + : _c.responseModalities) === undefined + ) { + // Set default to AUDIO to align with MLDev API. + if (params.config === undefined) { + params.config = { responseModalities: [Modality.AUDIO] }; + } else { + params.config.responseModalities = [Modality.AUDIO]; + } + } + if ( + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.generationConfig + ) { + // Raise deprecation warning for 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).", + ); + } + const inputTools = + (_f = + (_e = params.config) === null || _e === void 0 ? void 0 : _e.tools) !== + null && _f !== void 0 + ? _f + : []; + const convertedTools = []; + for (const tool of inputTools) { + if (this.isCallableTool(tool)) { + const callableTool = tool; + convertedTools.push(await callableTool.tool()); + } else { + convertedTools.push(tool); + } + } + if (convertedTools.length > 0) { + params.config.tools = convertedTools; + } + const liveConnectParameters = { + model: transformedModel, + config: params.config, + callbacks: params.callbacks, + }; + if (this.apiClient.isVertexAI()) { + clientMessage = liveConnectParametersToVertex( + this.apiClient, + liveConnectParameters, + ); + } else { + clientMessage = liveConnectParametersToMldev( + this.apiClient, + liveConnectParameters, + ); + } + delete clientMessage["config"]; + conn.send(JSON.stringify(clientMessage)); + return new Session(conn, this.apiClient); + } + // TODO: b/416041229 - Abstract this method to a common place. + isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; + } +} +const defaultLiveSendClientContentParamerters = { + turnComplete: true, +}; +/** + Represents a connection to the API. + + @experimental + */ +class Session { + constructor(conn, apiClient) { + this.conn = conn; + this.apiClient = apiClient; + } + tLiveClientContent(apiClient, params) { + if (params.turns !== null && params.turns !== undefined) { + let contents = []; + try { + contents = tContents(params.turns); + if (apiClient.isVertexAI()) { + contents = contents.map((item) => contentToVertex(item)); + } else { + contents = contents.map((item) => contentToMldev$1(item)); + } + } catch (_a) { + throw new Error( + `Failed to parse client content "turns", type: '${typeof params.turns}'`, + ); + } + return { + clientContent: { turns: contents, turnComplete: params.turnComplete }, + }; + } + return { + clientContent: { turnComplete: params.turnComplete }, + }; + } + tLiveClienttToolResponse(apiClient, params) { + let functionResponses = []; + if (params.functionResponses == null) { + throw new Error("functionResponses is required."); + } + if (!Array.isArray(params.functionResponses)) { + functionResponses = [params.functionResponses]; + } else { + functionResponses = params.functionResponses; + } + if (functionResponses.length === 0) { + throw new Error("functionResponses is required."); + } + for (const functionResponse of functionResponses) { + if ( + typeof functionResponse !== "object" || + functionResponse === null || + !("name" in functionResponse) || + !("response" in functionResponse) + ) { + throw new Error( + `Could not parse function response, type '${typeof functionResponse}'.`, + ); + } + if (!apiClient.isVertexAI() && !("id" in functionResponse)) { + throw new Error(FUNCTION_RESPONSE_REQUIRES_ID); + } + } + const clientMessage = { + toolResponse: { functionResponses: functionResponses }, + }; + return clientMessage; + } + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params) { + params = Object.assign( + Object.assign({}, defaultLiveSendClientContentParamerters), + params, + ); + const clientMessage = this.tLiveClientContent(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params) { + let clientMessage = {}; + if (this.apiClient.isVertexAI()) { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToVertex(params), + }; + } else { + clientMessage = { + realtimeInput: liveSendRealtimeInputParametersToMldev(params), + }; + } + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params) { + if (params.functionResponses == null) { + throw new Error("Tool response parameters are required."); + } + const clientMessage = this.tLiveClienttToolResponse(this.apiClient, params); + this.conn.send(JSON.stringify(clientMessage)); + } + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close() { + this.conn.close(); + } +} +// Converts an headers object to a "map" object as expected by the WebSocket +// constructor. We use this as the Auth interface works with Headers objects +// while the WebSocket constructor takes a map. +function headersToMap(headers) { + const headerMap = {}; + headers.forEach((value, key) => { + headerMap[key] = value; + }); + return headerMap; +} +// Converts a "map" object to a headers object. We use this as the Auth +// interface works with Headers objects while the API client default headers +// returns a map. +function mapToHeaders(map) { + const headers = new Headers(); + for (const [key, value] of Object.entries(map)) { + headers.append(key, value); + } + return headers; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const DEFAULT_MAX_REMOTE_CALLS = 10; +/** Returns whether automatic function calling is disabled. */ +function shouldDisableAfc(config) { + var _a, _b, _c; + if ( + (_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.disable + ) { + return true; + } + let callableToolsPresent = false; + for (const tool of (_b = + config === null || config === void 0 ? void 0 : config.tools) !== null && + _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + callableToolsPresent = true; + break; + } + } + if (!callableToolsPresent) { + return true; + } + const maxCalls = + (_c = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _c === void 0 + ? void 0 + : _c.maximumRemoteCalls; + if ( + (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) || + maxCalls == 0 + ) { + 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:", + maxCalls, + ); + return true; + } + return false; +} +function isCallableTool(tool) { + return "callTool" in tool && typeof tool.callTool === "function"; +} +// Checks whether the list of tools contains any CallableTools. Will return true +// if there is at least one CallableTool. +function hasCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +// Checks whether the list of tools contains any non-callable tools. Will return +// true if there is at least one non-Callable tool. +function hasNonCallableTools(params) { + var _a, _b, _c; + return (_c = + (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) === + null || _b === void 0 + ? void 0 + : _b.some((tool) => !isCallableTool(tool))) !== null && _c !== void 0 + ? _c + : false; +} +/** + * Returns whether to append automatic function calling history to the + * response. + */ +function shouldAppendAfcHistory(config) { + var _a; + return !((_a = + config === null || config === void 0 + ? void 0 + : config.automaticFunctionCalling) === null || _a === void 0 + ? void 0 + : _a.ignoreCallHistory); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Models extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + this.generateContent = async (params) => { + var _a, _b, _c, _d, _e; + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + this.maybeMoveToResponseJsonSchem(params); + if (!hasCallableTools(params) || shouldDisableAfc(params.config)) { + return await this.generateContentInternal(transformedParams); + } + if (hasNonCallableTools(params)) { + throw new Error( + "Automatic function calling with CallableTools and Tools is not yet supported.", + ); + } + let response; + let functionResponseContent; + const automaticFunctionCallingHistory = tContents( + transformedParams.contents, + ); + const maxRemoteCalls = + (_c = + (_b = + (_a = transformedParams.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let remoteCalls = 0; + while (remoteCalls < maxRemoteCalls) { + response = await this.generateContentInternal(transformedParams); + if (!response.functionCalls || response.functionCalls.length === 0) { + break; + } + const responseContent = response.candidates[0].content; + const functionResponseParts = []; + for (const tool of (_e = + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.tools) !== null && _e !== void 0 + ? _e + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const parts = await callableTool.callTool(response.functionCalls); + functionResponseParts.push(...parts); + } + } + remoteCalls++; + functionResponseContent = { + role: "user", + parts: functionResponseParts, + }; + transformedParams.contents = tContents(transformedParams.contents); + transformedParams.contents.push(responseContent); + transformedParams.contents.push(functionResponseContent); + if (shouldAppendAfcHistory(transformedParams.config)) { + automaticFunctionCallingHistory.push(responseContent); + automaticFunctionCallingHistory.push(functionResponseContent); + } + } + if (shouldAppendAfcHistory(transformedParams.config)) { + response.automaticFunctionCallingHistory = + automaticFunctionCallingHistory; + } + return response; + }; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + this.generateContentStream = async (params) => { + this.maybeMoveToResponseJsonSchem(params); + if (shouldDisableAfc(params.config)) { + const transformedParams = + await this.processParamsMaybeAddMcpUsage(params); + return await this.generateContentStreamInternal(transformedParams); + } else { + return await this.processAfcStream(params); + } + }; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.generateImages = async (params) => { + return await this.generateImagesInternal(params).then((apiResponse) => { + var _a; + let positivePromptSafetyAttributes; + const generatedImages = []; + if ( + apiResponse === null || apiResponse === void 0 + ? void 0 + : apiResponse.generatedImages + ) { + for (const generatedImage of apiResponse.generatedImages) { + if ( + generatedImage && + (generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) && + ((_a = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes) === null || _a === void 0 + ? void 0 + : _a.contentType) === "Positive Prompt" + ) { + positivePromptSafetyAttributes = + generatedImage === null || generatedImage === void 0 + ? void 0 + : generatedImage.safetyAttributes; + } else { + generatedImages.push(generatedImage); + } + } + } + let response; + if (positivePromptSafetyAttributes) { + response = { + generatedImages: generatedImages, + positivePromptSafetyAttributes: positivePromptSafetyAttributes, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } else { + response = { + generatedImages: generatedImages, + sdkHttpResponse: apiResponse.sdkHttpResponse, + }; + } + return response; + }); + }; + this.list = async (params) => { + var _a; + const defaultConfig = { + queryBase: true, + }; + const actualConfig = Object.assign( + Object.assign({}, defaultConfig), + params === null || params === void 0 ? void 0 : params.config, + ); + const actualParams = { + config: actualConfig, + }; + if (this.apiClient.isVertexAI()) { + if (!actualParams.config.queryBase) { + if ( + (_a = actualParams.config) === null || _a === void 0 + ? void 0 + : _a.filter + ) { + throw new Error( + "Filtering tuned models list for Vertex AI is not currently supported", + ); + } else { + actualParams.config.filter = "labels.tune-type:*"; + } + } + } + return new Pager( + PagedItem.PAGED_ITEM_MODELS, + (x) => this.listInternal(x), + await this.listInternal(actualParams), + actualParams, + ); + }; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.editImage = async (params) => { + const paramsInternal = { + model: params.model, + prompt: params.prompt, + referenceImages: [], + config: params.config, + }; + if (params.referenceImages) { + if (params.referenceImages) { + paramsInternal.referenceImages = params.referenceImages.map((img) => + img.toReferenceImageAPI(), + ); + } + } + return await this.editImageInternal(paramsInternal); + }; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + this.upscaleImage = async (params) => { + let apiConfig = { + numberOfImages: 1, + mode: "upscale", + }; + if (params.config) { + apiConfig = Object.assign(Object.assign({}, apiConfig), params.config); + } + const apiParams = { + model: params.model, + image: params.image, + upscaleFactor: params.upscaleFactor, + config: apiConfig, + }; + return await this.upscaleImageInternal(apiParams); + }; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + this.generateVideos = async (params) => { + return await this.generateVideosInternal(params); + }; + } + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + maybeMoveToResponseJsonSchem(params) { + if (params.config && params.config.responseSchema) { + if (!params.config.responseJsonSchema) { + if (Object.keys(params.config.responseSchema).includes("$schema")) { + params.config.responseJsonSchema = params.config.responseSchema; + delete params.config.responseSchema; + } + } + } + return; + } + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + async processParamsMaybeAddMcpUsage(params) { + var _a, _b, _c; + const tools = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools; + if (!tools) { + return params; + } + const transformedTools = await Promise.all( + tools.map(async (tool) => { + if (isCallableTool(tool)) { + const callableTool = tool; + return await callableTool.tool(); + } + return tool; + }), + ); + const newParams = { + model: params.model, + contents: params.contents, + config: Object.assign(Object.assign({}, params.config), { + tools: transformedTools, + }), + }; + newParams.config.tools = transformedTools; + if ( + params.config && + params.config.tools && + hasMcpToolUsage(params.config.tools) + ) { + const headers = + (_c = + (_b = params.config.httpOptions) === null || _b === void 0 + ? void 0 + : _b.headers) !== null && _c !== void 0 + ? _c + : {}; + let newHeaders = Object.assign({}, headers); + if (Object.keys(newHeaders).length === 0) { + newHeaders = this.apiClient.getDefaultHeaders(); + } + setMcpUsageHeader(newHeaders); + newParams.config.httpOptions = Object.assign( + Object.assign({}, params.config.httpOptions), + { headers: newHeaders }, + ); + } + return newParams; + } + async initAfcToolsMap(params) { + var _a, _b, _c; + const afcTools = new Map(); + for (const tool of (_b = + (_a = params.config) === null || _a === void 0 ? void 0 : _a.tools) !== + null && _b !== void 0 + ? _b + : []) { + if (isCallableTool(tool)) { + const callableTool = tool; + const toolDeclaration = await callableTool.tool(); + for (const declaration of (_c = + toolDeclaration.functionDeclarations) !== null && _c !== void 0 + ? _c + : []) { + if (!declaration.name) { + throw new Error("Function declaration name is required."); + } + if (afcTools.has(declaration.name)) { + throw new Error( + `Duplicate tool declaration name: ${declaration.name}`, + ); + } + afcTools.set(declaration.name, callableTool); + } + } + } + return afcTools; + } + async processAfcStream(params) { + var _a, _b, _c; + const maxRemoteCalls = + (_c = + (_b = + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.automaticFunctionCalling) === null || _b === void 0 + ? void 0 + : _b.maximumRemoteCalls) !== null && _c !== void 0 + ? _c + : DEFAULT_MAX_REMOTE_CALLS; + let wereFunctionsCalled = false; + let remoteCallCount = 0; + const afcToolsMap = await this.initAfcToolsMap(params); + return (function (models, afcTools, params) { + var _a, _b; + return __asyncGenerator(this, arguments, function* () { + var _c, e_1, _d, _e; + while (remoteCallCount < maxRemoteCalls) { + if (wereFunctionsCalled) { + remoteCallCount++; + wereFunctionsCalled = false; + } + const transformedParams = yield __await( + models.processParamsMaybeAddMcpUsage(params), + ); + const response = yield __await( + models.generateContentStreamInternal(transformedParams), + ); + const functionResponses = []; + const responseContents = []; + try { + for ( + var _f = true, + response_1 = ((e_1 = void 0), __asyncValues(response)), + response_1_1; + (response_1_1 = yield __await(response_1.next())), + (_c = response_1_1.done), + !_c; + _f = true + ) { + _e = response_1_1.value; + _f = false; + const chunk = _e; + yield yield __await(chunk); + if ( + chunk.candidates && + ((_a = chunk.candidates[0]) === null || _a === void 0 + ? void 0 + : _a.content) + ) { + responseContents.push(chunk.candidates[0].content); + for (const part of (_b = chunk.candidates[0].content.parts) !== + null && _b !== void 0 + ? _b + : []) { + if (remoteCallCount < maxRemoteCalls && part.functionCall) { + if (!part.functionCall.name) { + throw new Error( + "Function call name was not returned by the model.", + ); + } + if (!afcTools.has(part.functionCall.name)) { + throw new Error( + `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${part.functionCall.name}`, + ); + } else { + const responseParts = yield __await( + afcTools + .get(part.functionCall.name) + .callTool([part.functionCall]), + ); + functionResponses.push(...responseParts); + } + } + } + } + } + } catch (e_1_1) { + e_1 = { error: e_1_1 }; + } finally { + try { + if (!_f && !_c && (_d = response_1.return)) + yield __await(_d.call(response_1)); + } finally { + if (e_1) throw e_1.error; + } + } + if (functionResponses.length > 0) { + wereFunctionsCalled = true; + const typedResponseChunk = new GenerateContentResponse(); + typedResponseChunk.candidates = [ + { + content: { + role: "user", + parts: functionResponses, + }, + }, + ]; + yield yield __await(typedResponseChunk); + const newContents = []; + newContents.push(...responseContents); + newContents.push({ + role: "user", + parts: functionResponses, + }); + const updatedContents = tContents(params.contents).concat( + newContents, + ); + params.contents = updatedContents; + } else { + break; + } + } + }); + })(this, afcToolsMap, params); + } + async generateContentInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromVertex(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:generateContent", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateContentResponseFromMldev(apiResponse); + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async generateContentStreamInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_2, _b, _c; + try { + for ( + var _d = true, + apiResponse_1 = __asyncValues(apiResponse), + apiResponse_1_1; + (apiResponse_1_1 = yield __await(apiResponse_1.next())), + (_a = apiResponse_1_1.done), + !_a; + _d = true + ) { + _c = apiResponse_1_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromVertex( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_2_1) { + e_2 = { error: e_2_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_1.return)) + yield __await(_b.call(apiResponse_1)); + } finally { + if (e_2) throw e_2.error; + } + } + }); + }); + } else { + const body = generateContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:streamGenerateContent?alt=sse", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const apiClient = this.apiClient; + response = apiClient.requestStream({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }); + return response.then(function (apiResponse) { + return __asyncGenerator(this, arguments, function* () { + var _a, e_3, _b, _c; + try { + for ( + var _d = true, + apiResponse_2 = __asyncValues(apiResponse), + apiResponse_2_1; + (apiResponse_2_1 = yield __await(apiResponse_2.next())), + (_a = apiResponse_2_1.done), + !_a; + _d = true + ) { + _c = apiResponse_2_1.value; + _d = false; + const chunk = _c; + const resp = generateContentResponseFromMldev( + yield __await(chunk.json()), + ); + resp["sdkHttpResponse"] = { + headers: chunk.headers, + }; + const typedResp = new GenerateContentResponse(); + Object.assign(typedResp, resp); + yield yield __await(typedResp); + } + } catch (e_3_1) { + e_3 = { error: e_3_1 }; + } finally { + try { + if (!_d && !_a && (_b = apiResponse_2.return)) + yield __await(_b.call(apiResponse_2)); + } finally { + if (e_3) throw e_3.error; + } + } + }); + }); + } + } + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + async embedContent(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = embedContentParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromVertex(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = embedContentParametersToMldev(this.apiClient, params); + path = formatMap("{model}:batchEmbedContents", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = embedContentResponseFromMldev(apiResponse); + const typedResp = new EmbedContentResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + async generateImagesInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateImagesParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromVertex(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateImagesParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = generateImagesResponseFromMldev(apiResponse); + const typedResp = new GenerateImagesResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async editImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = editImageParametersInternalToVertex(this.apiClient, params); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = editImageResponseFromVertex(apiResponse); + const typedResp = new EditImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async upscaleImageInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = upscaleImageAPIParametersInternalToVertex( + this.apiClient, + params, + ); + path = formatMap("{model}:predict", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = upscaleImageResponseFromVertex(apiResponse); + const typedResp = new UpscaleImageResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + async get(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = getModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listModelsParametersToVertex(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromVertex(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listModelsParametersToMldev(this.apiClient, params); + path = formatMap("{models_url}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listModelsResponseFromMldev(apiResponse); + const typedResp = new ListModelsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + async update(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = updateModelParametersToVertex(this.apiClient, params); + path = formatMap("{model}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromVertex(apiResponse); + return resp; + }); + } else { + const body = updateModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "PATCH", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = modelFromMldev(apiResponse); + return resp; + }); + } + } + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + async delete(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = deleteModelParametersToVertex(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromVertex(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = deleteModelParametersToMldev(this.apiClient, params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "DELETE", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then(() => { + const resp = deleteModelResponseFromMldev(); + const typedResp = new DeleteModelResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + async countTokens(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = countTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromVertex(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = countTokensParametersToMldev(this.apiClient, params); + path = formatMap("{model}:countTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = countTokensResponseFromMldev(apiResponse); + const typedResp = new CountTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + async computeTokens(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = computeTokensParametersToVertex(this.apiClient, params); + path = formatMap("{model}:computeTokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = computeTokensResponseFromVertex(apiResponse); + const typedResp = new ComputeTokensResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + async generateVideosInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = generateVideosParametersToVertex(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromVertex(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = generateVideosParametersToMldev(this.apiClient, params); + path = formatMap("{model}:predictLongRunning", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = generateVideosOperationFromMldev(apiResponse); + const typedResp = new GenerateVideosOperation(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getOperationParametersToMldev(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function getOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["_url", "operationName"], fromOperationName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function fetchPredictOperationParametersToVertex(fromObject) { + const toObject = {}; + const fromOperationName = getValueByPath(fromObject, ["operationName"]); + if (fromOperationName != null) { + setValueByPath(toObject, ["operationName"], fromOperationName); + } + const fromResourceName = getValueByPath(fromObject, ["resourceName"]); + if (fromResourceName != null) { + setValueByPath(toObject, ["_url", "resourceName"], fromResourceName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Operations extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async getVideosOperation(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + async get(parameters) { + const operation = parameters.operation; + const config = parameters.config; + if (operation.name === undefined || operation.name === "") { + throw new Error("Operation name is required."); + } + if (this.apiClient.isVertexAI()) { + const resourceName = operation.name.split("/operations/")[0]; + let httpOptions = undefined; + if (config && "httpOptions" in config) { + httpOptions = config.httpOptions; + } + const rawOperation = await this.fetchPredictVideosOperationInternal({ + operationName: operation.name, + resourceName: resourceName, + config: { httpOptions: httpOptions }, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: true, + }); + } else { + const rawOperation = await this.getVideosOperationInternal({ + operationName: operation.name, + config: config, + }); + return operation._fromAPIResponse({ + apiResponse: rawOperation, + isVertexAI: false, + }); + } + } + async getVideosOperationInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getOperationParametersToVertex(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + const body = getOperationParametersToMldev(params); + path = formatMap("{operationName}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } + } + async fetchPredictVideosOperationInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = fetchPredictOperationParametersToVertex(params); + path = formatMap("{resourceName}:fetchPredictOperation", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response; + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +function prebuiltVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceName = getValueByPath(fromObject, ["voiceName"]); + if (fromVoiceName != null) { + setValueByPath(toObject, ["voiceName"], fromVoiceName); + } + return toObject; +} +function voiceConfigToMldev(fromObject) { + const toObject = {}; + const fromPrebuiltVoiceConfig = getValueByPath(fromObject, [ + "prebuiltVoiceConfig", + ]); + if (fromPrebuiltVoiceConfig != null) { + setValueByPath( + toObject, + ["prebuiltVoiceConfig"], + prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig), + ); + } + return toObject; +} +function speakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeaker = getValueByPath(fromObject, ["speaker"]); + if (fromSpeaker != null) { + setValueByPath(toObject, ["speaker"], fromSpeaker); + } + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + return toObject; +} +function multiSpeakerVoiceConfigToMldev(fromObject) { + const toObject = {}; + const fromSpeakerVoiceConfigs = getValueByPath(fromObject, [ + "speakerVoiceConfigs", + ]); + if (fromSpeakerVoiceConfigs != null) { + let transformedList = fromSpeakerVoiceConfigs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return speakerVoiceConfigToMldev(item); + }); + } + setValueByPath(toObject, ["speakerVoiceConfigs"], transformedList); + } + return toObject; +} +function speechConfigToMldev(fromObject) { + const toObject = {}; + const fromVoiceConfig = getValueByPath(fromObject, ["voiceConfig"]); + if (fromVoiceConfig != null) { + setValueByPath( + toObject, + ["voiceConfig"], + voiceConfigToMldev(fromVoiceConfig), + ); + } + const fromMultiSpeakerVoiceConfig = getValueByPath(fromObject, [ + "multiSpeakerVoiceConfig", + ]); + if (fromMultiSpeakerVoiceConfig != null) { + setValueByPath( + toObject, + ["multiSpeakerVoiceConfig"], + multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig), + ); + } + const fromLanguageCode = getValueByPath(fromObject, ["languageCode"]); + if (fromLanguageCode != null) { + setValueByPath(toObject, ["languageCode"], fromLanguageCode); + } + return toObject; +} +function videoMetadataToMldev(fromObject) { + const toObject = {}; + const fromFps = getValueByPath(fromObject, ["fps"]); + if (fromFps != null) { + setValueByPath(toObject, ["fps"], fromFps); + } + const fromEndOffset = getValueByPath(fromObject, ["endOffset"]); + if (fromEndOffset != null) { + setValueByPath(toObject, ["endOffset"], fromEndOffset); + } + const fromStartOffset = getValueByPath(fromObject, ["startOffset"]); + if (fromStartOffset != null) { + setValueByPath(toObject, ["startOffset"], fromStartOffset); + } + return toObject; +} +function blobToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromData = getValueByPath(fromObject, ["data"]); + if (fromData != null) { + setValueByPath(toObject, ["data"], fromData); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function fileDataToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["displayName"]) !== undefined) { + throw new Error("displayName parameter is not supported in Gemini API."); + } + const fromFileUri = getValueByPath(fromObject, ["fileUri"]); + if (fromFileUri != null) { + setValueByPath(toObject, ["fileUri"], fromFileUri); + } + const fromMimeType = getValueByPath(fromObject, ["mimeType"]); + if (fromMimeType != null) { + setValueByPath(toObject, ["mimeType"], fromMimeType); + } + return toObject; +} +function partToMldev(fromObject) { + const toObject = {}; + const fromVideoMetadata = getValueByPath(fromObject, ["videoMetadata"]); + if (fromVideoMetadata != null) { + setValueByPath( + toObject, + ["videoMetadata"], + videoMetadataToMldev(fromVideoMetadata), + ); + } + const fromThought = getValueByPath(fromObject, ["thought"]); + if (fromThought != null) { + setValueByPath(toObject, ["thought"], fromThought); + } + const fromInlineData = getValueByPath(fromObject, ["inlineData"]); + if (fromInlineData != null) { + setValueByPath(toObject, ["inlineData"], blobToMldev(fromInlineData)); + } + const fromFileData = getValueByPath(fromObject, ["fileData"]); + if (fromFileData != null) { + setValueByPath(toObject, ["fileData"], fileDataToMldev(fromFileData)); + } + const fromThoughtSignature = getValueByPath(fromObject, ["thoughtSignature"]); + if (fromThoughtSignature != null) { + setValueByPath(toObject, ["thoughtSignature"], fromThoughtSignature); + } + const fromCodeExecutionResult = getValueByPath(fromObject, [ + "codeExecutionResult", + ]); + if (fromCodeExecutionResult != null) { + setValueByPath(toObject, ["codeExecutionResult"], fromCodeExecutionResult); + } + const fromExecutableCode = getValueByPath(fromObject, ["executableCode"]); + if (fromExecutableCode != null) { + setValueByPath(toObject, ["executableCode"], fromExecutableCode); + } + const fromFunctionCall = getValueByPath(fromObject, ["functionCall"]); + if (fromFunctionCall != null) { + setValueByPath(toObject, ["functionCall"], fromFunctionCall); + } + const fromFunctionResponse = getValueByPath(fromObject, ["functionResponse"]); + if (fromFunctionResponse != null) { + setValueByPath(toObject, ["functionResponse"], fromFunctionResponse); + } + const fromText = getValueByPath(fromObject, ["text"]); + if (fromText != null) { + setValueByPath(toObject, ["text"], fromText); + } + return toObject; +} +function contentToMldev(fromObject) { + const toObject = {}; + const fromParts = getValueByPath(fromObject, ["parts"]); + if (fromParts != null) { + let transformedList = fromParts; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return partToMldev(item); + }); + } + setValueByPath(toObject, ["parts"], transformedList); + } + const fromRole = getValueByPath(fromObject, ["role"]); + if (fromRole != null) { + setValueByPath(toObject, ["role"], fromRole); + } + return toObject; +} +function functionDeclarationToMldev(fromObject) { + const toObject = {}; + const fromBehavior = getValueByPath(fromObject, ["behavior"]); + if (fromBehavior != null) { + setValueByPath(toObject, ["behavior"], fromBehavior); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromParameters = getValueByPath(fromObject, ["parameters"]); + if (fromParameters != null) { + setValueByPath(toObject, ["parameters"], fromParameters); + } + const fromParametersJsonSchema = getValueByPath(fromObject, [ + "parametersJsonSchema", + ]); + if (fromParametersJsonSchema != null) { + setValueByPath( + toObject, + ["parametersJsonSchema"], + fromParametersJsonSchema, + ); + } + const fromResponse = getValueByPath(fromObject, ["response"]); + if (fromResponse != null) { + setValueByPath(toObject, ["response"], fromResponse); + } + const fromResponseJsonSchema = getValueByPath(fromObject, [ + "responseJsonSchema", + ]); + if (fromResponseJsonSchema != null) { + setValueByPath(toObject, ["responseJsonSchema"], fromResponseJsonSchema); + } + return toObject; +} +function intervalToMldev(fromObject) { + const toObject = {}; + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + return toObject; +} +function googleSearchToMldev(fromObject) { + const toObject = {}; + const fromTimeRangeFilter = getValueByPath(fromObject, ["timeRangeFilter"]); + if (fromTimeRangeFilter != null) { + setValueByPath( + toObject, + ["timeRangeFilter"], + intervalToMldev(fromTimeRangeFilter), + ); + } + return toObject; +} +function dynamicRetrievalConfigToMldev(fromObject) { + const toObject = {}; + const fromMode = getValueByPath(fromObject, ["mode"]); + if (fromMode != null) { + setValueByPath(toObject, ["mode"], fromMode); + } + const fromDynamicThreshold = getValueByPath(fromObject, ["dynamicThreshold"]); + if (fromDynamicThreshold != null) { + setValueByPath(toObject, ["dynamicThreshold"], fromDynamicThreshold); + } + return toObject; +} +function googleSearchRetrievalToMldev(fromObject) { + const toObject = {}; + const fromDynamicRetrievalConfig = getValueByPath(fromObject, [ + "dynamicRetrievalConfig", + ]); + if (fromDynamicRetrievalConfig != null) { + setValueByPath( + toObject, + ["dynamicRetrievalConfig"], + dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig), + ); + } + return toObject; +} +function urlContextToMldev() { + const toObject = {}; + return toObject; +} +function toolComputerUseToMldev(fromObject) { + const toObject = {}; + const fromExcludedPredefinedFunctions = getValueByPath(fromObject, [ + "excludedPredefinedFunctions", + ]); + if (fromExcludedPredefinedFunctions != null) { + setValueByPath( + toObject, + ["excludedPredefinedFunctions"], + fromExcludedPredefinedFunctions, + ); + } + const fromEnvironment = getValueByPath(fromObject, ["environment"]); + if (fromEnvironment != null) { + setValueByPath(toObject, ["environment"], fromEnvironment); + } + return toObject; +} +function toolToMldev(fromObject) { + const toObject = {}; + const fromFunctionDeclarations = getValueByPath(fromObject, [ + "functionDeclarations", + ]); + if (fromFunctionDeclarations != null) { + let transformedList = fromFunctionDeclarations; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return functionDeclarationToMldev(item); + }); + } + setValueByPath(toObject, ["functionDeclarations"], transformedList); + } + if (getValueByPath(fromObject, ["retrieval"]) !== undefined) { + throw new Error("retrieval parameter is not supported in Gemini API."); + } + const fromGoogleSearch = getValueByPath(fromObject, ["googleSearch"]); + if (fromGoogleSearch != null) { + setValueByPath( + toObject, + ["googleSearch"], + googleSearchToMldev(fromGoogleSearch), + ); + } + const fromGoogleSearchRetrieval = getValueByPath(fromObject, [ + "googleSearchRetrieval", + ]); + if (fromGoogleSearchRetrieval != null) { + setValueByPath( + toObject, + ["googleSearchRetrieval"], + googleSearchRetrievalToMldev(fromGoogleSearchRetrieval), + ); + } + if (getValueByPath(fromObject, ["enterpriseWebSearch"]) !== undefined) { + throw new Error( + "enterpriseWebSearch parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["googleMaps"]) !== undefined) { + throw new Error("googleMaps parameter is not supported in Gemini API."); + } + const fromUrlContext = getValueByPath(fromObject, ["urlContext"]); + if (fromUrlContext != null) { + setValueByPath(toObject, ["urlContext"], urlContextToMldev()); + } + const fromComputerUse = getValueByPath(fromObject, ["computerUse"]); + if (fromComputerUse != null) { + setValueByPath( + toObject, + ["computerUse"], + toolComputerUseToMldev(fromComputerUse), + ); + } + const fromCodeExecution = getValueByPath(fromObject, ["codeExecution"]); + if (fromCodeExecution != null) { + setValueByPath(toObject, ["codeExecution"], fromCodeExecution); + } + return toObject; +} +function sessionResumptionConfigToMldev(fromObject) { + const toObject = {}; + const fromHandle = getValueByPath(fromObject, ["handle"]); + if (fromHandle != null) { + setValueByPath(toObject, ["handle"], fromHandle); + } + if (getValueByPath(fromObject, ["transparent"]) !== undefined) { + throw new Error("transparent parameter is not supported in Gemini API."); + } + return toObject; +} +function audioTranscriptionConfigToMldev() { + const toObject = {}; + return toObject; +} +function automaticActivityDetectionToMldev(fromObject) { + const toObject = {}; + const fromDisabled = getValueByPath(fromObject, ["disabled"]); + if (fromDisabled != null) { + setValueByPath(toObject, ["disabled"], fromDisabled); + } + const fromStartOfSpeechSensitivity = getValueByPath(fromObject, [ + "startOfSpeechSensitivity", + ]); + if (fromStartOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["startOfSpeechSensitivity"], + fromStartOfSpeechSensitivity, + ); + } + const fromEndOfSpeechSensitivity = getValueByPath(fromObject, [ + "endOfSpeechSensitivity", + ]); + if (fromEndOfSpeechSensitivity != null) { + setValueByPath( + toObject, + ["endOfSpeechSensitivity"], + fromEndOfSpeechSensitivity, + ); + } + const fromPrefixPaddingMs = getValueByPath(fromObject, ["prefixPaddingMs"]); + if (fromPrefixPaddingMs != null) { + setValueByPath(toObject, ["prefixPaddingMs"], fromPrefixPaddingMs); + } + const fromSilenceDurationMs = getValueByPath(fromObject, [ + "silenceDurationMs", + ]); + if (fromSilenceDurationMs != null) { + setValueByPath(toObject, ["silenceDurationMs"], fromSilenceDurationMs); + } + return toObject; +} +function realtimeInputConfigToMldev(fromObject) { + const toObject = {}; + const fromAutomaticActivityDetection = getValueByPath(fromObject, [ + "automaticActivityDetection", + ]); + if (fromAutomaticActivityDetection != null) { + setValueByPath( + toObject, + ["automaticActivityDetection"], + automaticActivityDetectionToMldev(fromAutomaticActivityDetection), + ); + } + const fromActivityHandling = getValueByPath(fromObject, ["activityHandling"]); + if (fromActivityHandling != null) { + setValueByPath(toObject, ["activityHandling"], fromActivityHandling); + } + const fromTurnCoverage = getValueByPath(fromObject, ["turnCoverage"]); + if (fromTurnCoverage != null) { + setValueByPath(toObject, ["turnCoverage"], fromTurnCoverage); + } + return toObject; +} +function slidingWindowToMldev(fromObject) { + const toObject = {}; + const fromTargetTokens = getValueByPath(fromObject, ["targetTokens"]); + if (fromTargetTokens != null) { + setValueByPath(toObject, ["targetTokens"], fromTargetTokens); + } + return toObject; +} +function contextWindowCompressionConfigToMldev(fromObject) { + const toObject = {}; + const fromTriggerTokens = getValueByPath(fromObject, ["triggerTokens"]); + if (fromTriggerTokens != null) { + setValueByPath(toObject, ["triggerTokens"], fromTriggerTokens); + } + const fromSlidingWindow = getValueByPath(fromObject, ["slidingWindow"]); + if (fromSlidingWindow != null) { + setValueByPath( + toObject, + ["slidingWindow"], + slidingWindowToMldev(fromSlidingWindow), + ); + } + return toObject; +} +function proactivityConfigToMldev(fromObject) { + const toObject = {}; + const fromProactiveAudio = getValueByPath(fromObject, ["proactiveAudio"]); + if (fromProactiveAudio != null) { + setValueByPath(toObject, ["proactiveAudio"], fromProactiveAudio); + } + return toObject; +} +function liveConnectConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromGenerationConfig = getValueByPath(fromObject, ["generationConfig"]); + if (parentObject !== undefined && fromGenerationConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig"], + fromGenerationConfig, + ); + } + const fromResponseModalities = getValueByPath(fromObject, [ + "responseModalities", + ]); + if (parentObject !== undefined && fromResponseModalities != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "responseModalities"], + fromResponseModalities, + ); + } + const fromTemperature = getValueByPath(fromObject, ["temperature"]); + if (parentObject !== undefined && fromTemperature != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "temperature"], + fromTemperature, + ); + } + const fromTopP = getValueByPath(fromObject, ["topP"]); + if (parentObject !== undefined && fromTopP != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topP"], + fromTopP, + ); + } + const fromTopK = getValueByPath(fromObject, ["topK"]); + if (parentObject !== undefined && fromTopK != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "topK"], + fromTopK, + ); + } + const fromMaxOutputTokens = getValueByPath(fromObject, ["maxOutputTokens"]); + if (parentObject !== undefined && fromMaxOutputTokens != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "maxOutputTokens"], + fromMaxOutputTokens, + ); + } + const fromMediaResolution = getValueByPath(fromObject, ["mediaResolution"]); + if (parentObject !== undefined && fromMediaResolution != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "mediaResolution"], + fromMediaResolution, + ); + } + const fromSeed = getValueByPath(fromObject, ["seed"]); + if (parentObject !== undefined && fromSeed != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "seed"], + fromSeed, + ); + } + const fromSpeechConfig = getValueByPath(fromObject, ["speechConfig"]); + if (parentObject !== undefined && fromSpeechConfig != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "speechConfig"], + speechConfigToMldev(tLiveSpeechConfig(fromSpeechConfig)), + ); + } + const fromEnableAffectiveDialog = getValueByPath(fromObject, [ + "enableAffectiveDialog", + ]); + if (parentObject !== undefined && fromEnableAffectiveDialog != null) { + setValueByPath( + parentObject, + ["setup", "generationConfig", "enableAffectiveDialog"], + fromEnableAffectiveDialog, + ); + } + const fromSystemInstruction = getValueByPath(fromObject, [ + "systemInstruction", + ]); + if (parentObject !== undefined && fromSystemInstruction != null) { + setValueByPath( + parentObject, + ["setup", "systemInstruction"], + contentToMldev(tContent(fromSystemInstruction)), + ); + } + const fromTools = getValueByPath(fromObject, ["tools"]); + if (parentObject !== undefined && fromTools != null) { + let transformedList = tTools(fromTools); + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return toolToMldev(tTool(item)); + }); + } + setValueByPath(parentObject, ["setup", "tools"], transformedList); + } + const fromSessionResumption = getValueByPath(fromObject, [ + "sessionResumption", + ]); + if (parentObject !== undefined && fromSessionResumption != null) { + setValueByPath( + parentObject, + ["setup", "sessionResumption"], + sessionResumptionConfigToMldev(fromSessionResumption), + ); + } + const fromInputAudioTranscription = getValueByPath(fromObject, [ + "inputAudioTranscription", + ]); + if (parentObject !== undefined && fromInputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "inputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromOutputAudioTranscription = getValueByPath(fromObject, [ + "outputAudioTranscription", + ]); + if (parentObject !== undefined && fromOutputAudioTranscription != null) { + setValueByPath( + parentObject, + ["setup", "outputAudioTranscription"], + audioTranscriptionConfigToMldev(), + ); + } + const fromRealtimeInputConfig = getValueByPath(fromObject, [ + "realtimeInputConfig", + ]); + if (parentObject !== undefined && fromRealtimeInputConfig != null) { + setValueByPath( + parentObject, + ["setup", "realtimeInputConfig"], + realtimeInputConfigToMldev(fromRealtimeInputConfig), + ); + } + const fromContextWindowCompression = getValueByPath(fromObject, [ + "contextWindowCompression", + ]); + if (parentObject !== undefined && fromContextWindowCompression != null) { + setValueByPath( + parentObject, + ["setup", "contextWindowCompression"], + contextWindowCompressionConfigToMldev(fromContextWindowCompression), + ); + } + const fromProactivity = getValueByPath(fromObject, ["proactivity"]); + if (parentObject !== undefined && fromProactivity != null) { + setValueByPath( + parentObject, + ["setup", "proactivity"], + proactivityConfigToMldev(fromProactivity), + ); + } + return toObject; +} +function liveConnectConstraintsToMldev(apiClient, fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["setup", "model"], tModel(apiClient, fromModel)); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + liveConnectConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function createAuthTokenConfigToMldev(apiClient, fromObject, parentObject) { + const toObject = {}; + const fromExpireTime = getValueByPath(fromObject, ["expireTime"]); + if (parentObject !== undefined && fromExpireTime != null) { + setValueByPath(parentObject, ["expireTime"], fromExpireTime); + } + const fromNewSessionExpireTime = getValueByPath(fromObject, [ + "newSessionExpireTime", + ]); + if (parentObject !== undefined && fromNewSessionExpireTime != null) { + setValueByPath( + parentObject, + ["newSessionExpireTime"], + fromNewSessionExpireTime, + ); + } + const fromUses = getValueByPath(fromObject, ["uses"]); + if (parentObject !== undefined && fromUses != null) { + setValueByPath(parentObject, ["uses"], fromUses); + } + const fromLiveConnectConstraints = getValueByPath(fromObject, [ + "liveConnectConstraints", + ]); + if (parentObject !== undefined && fromLiveConnectConstraints != null) { + setValueByPath( + parentObject, + ["bidiGenerateContentSetup"], + liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints), + ); + } + const fromLockAdditionalFields = getValueByPath(fromObject, [ + "lockAdditionalFields", + ]); + if (parentObject !== undefined && fromLockAdditionalFields != null) { + setValueByPath(parentObject, ["fieldMask"], fromLockAdditionalFields); + } + return toObject; +} +function createAuthTokenParametersToMldev(apiClient, fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createAuthTokenConfigToMldev(apiClient, fromConfig, toObject), + ); + } + return toObject; +} +function authTokenFromMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Returns a comma-separated list of field masks from a given object. + * + * @param setup The object to extract field masks from. + * @return A comma-separated list of field masks. + */ +function getFieldMasks(setup) { + const fields = []; + for (const key in setup) { + if (Object.prototype.hasOwnProperty.call(setup, key)) { + const value = setup[key]; + // 2nd layer, recursively get field masks see TODO(b/418290100) + if ( + typeof value === "object" && + value != null && + Object.keys(value).length > 0 + ) { + const field = Object.keys(value).map((kk) => `${key}.${kk}`); + fields.push(...field); + } else { + fields.push(key); // 1st layer + } + } + } + return fields.join(","); +} +/** + * Converts bidiGenerateContentSetup. + * @param requestDict - The request dictionary. + * @param config - The configuration object. + * @return - The modified request dictionary. + */ +function convertBidiSetupToTokenSetup(requestDict, config) { + // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup. + let setupForMaskGeneration = null; + const bidiGenerateContentSetupValue = requestDict["bidiGenerateContentSetup"]; + if ( + typeof bidiGenerateContentSetupValue === "object" && + bidiGenerateContentSetupValue !== null && + "setup" in bidiGenerateContentSetupValue + ) { + // Now we know bidiGenerateContentSetupValue is an object and has a 'setup' + // property. + const innerSetup = bidiGenerateContentSetupValue.setup; + if (typeof innerSetup === "object" && innerSetup !== null) { + // Valid inner setup found. + requestDict["bidiGenerateContentSetup"] = innerSetup; + setupForMaskGeneration = innerSetup; + } else { + // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as + // if bidiGenerateContentSetup is invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + } else if (bidiGenerateContentSetupValue !== undefined) { + // `bidiGenerateContentSetup` exists but not in the expected + // shape {setup: {...}}; treat as invalid. + delete requestDict["bidiGenerateContentSetup"]; + } + const preExistingFieldMask = requestDict["fieldMask"]; + // Handle mask generation setup. + if (setupForMaskGeneration) { + const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration); + if ( + Array.isArray( + config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields, + ) && + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields.length) === 0 + ) { + // Case 1: lockAdditionalFields is an empty array. Lock only fields from + // bidi setup. + if (generatedMaskFromBidi) { + // Only assign if mask is not empty + requestDict["fieldMask"] = generatedMaskFromBidi; + } else { + delete requestDict["fieldMask"]; // If mask is empty, effectively no + // specific fields locked by bidi + } + } else if ( + (config === null || config === void 0 + ? void 0 + : config.lockAdditionalFields) && + config.lockAdditionalFields.length > 0 && + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // Case 2: Lock fields from bidi setup + additional fields + // (preExistingFieldMask). + const generationConfigFields = [ + "temperature", + "topK", + "topP", + "maxOutputTokens", + "responseModalities", + "seed", + "speechConfig", + ]; + let mappedFieldsFromPreExisting = []; + if (preExistingFieldMask.length > 0) { + mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => { + if (generationConfigFields.includes(field)) { + return `generationConfig.${field}`; + } + return field; // Keep original field name if not in + // generationConfigFields + }); + } + const finalMaskParts = []; + if (generatedMaskFromBidi) { + finalMaskParts.push(generatedMaskFromBidi); + } + if (mappedFieldsFromPreExisting.length > 0) { + finalMaskParts.push(...mappedFieldsFromPreExisting); + } + if (finalMaskParts.length > 0) { + requestDict["fieldMask"] = finalMaskParts.join(","); + } else { + // If no fields from bidi and no valid additional fields from + // pre-existing mask. + delete requestDict["fieldMask"]; + } + } else { + // Case 3: "Lock all fields" (meaning, don't send a field_mask, let server + // defaults apply or all are mutable). This is hit if: + // - `config.lockAdditionalFields` is undefined. + // - `config.lockAdditionalFields` is non-empty, BUT + // `preExistingFieldMask` is null, not a string, or an empty string. + delete requestDict["fieldMask"]; + } + } else { + // No valid `bidiGenerateContentSetup` was found or extracted. + // "Lock additional null fields if any". + if ( + preExistingFieldMask !== null && + Array.isArray(preExistingFieldMask) && + preExistingFieldMask.length > 0 + ) { + // If there's a pre-existing field mask, it's a string, and it's not + // empty, then we should lock all fields. + requestDict["fieldMask"] = preExistingFieldMask.join(","); + } else { + delete requestDict["fieldMask"]; + } + } + return requestDict; +} +class Tokens extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + } + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + async create(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "The client.tokens.create method is only supported by the Gemini Developer API.", + ); + } else { + const body = createAuthTokenParametersToMldev(this.apiClient, params); + path = formatMap("auth_tokens", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + const transformedBody = convertBidiSetupToTokenSetup(body, params.config); + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(transformedBody), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = authTokenFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. +function getTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToMldev(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToMldev(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function tuningExampleToMldev(fromObject) { + const toObject = {}; + const fromTextInput = getValueByPath(fromObject, ["textInput"]); + if (fromTextInput != null) { + setValueByPath(toObject, ["textInput"], fromTextInput); + } + const fromOutput = getValueByPath(fromObject, ["output"]); + if (fromOutput != null) { + setValueByPath(toObject, ["output"], fromOutput); + } + return toObject; +} +function tuningDatasetToMldev(fromObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["gcsUri"]) !== undefined) { + throw new Error("gcsUri parameter is not supported in Gemini API."); + } + if (getValueByPath(fromObject, ["vertexDatasetResource"]) !== undefined) { + throw new Error( + "vertexDatasetResource parameter is not supported in Gemini API.", + ); + } + const fromExamples = getValueByPath(fromObject, ["examples"]); + if (fromExamples != null) { + let transformedList = fromExamples; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningExampleToMldev(item); + }); + } + setValueByPath(toObject, ["examples", "examples"], transformedList); + } + return toObject; +} +function createTuningJobConfigToMldev(fromObject, parentObject) { + const toObject = {}; + if (getValueByPath(fromObject, ["validationDataset"]) !== undefined) { + throw new Error( + "validationDataset parameter is not supported in Gemini API.", + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath(parentObject, ["displayName"], fromTunedModelDisplayName); + } + if (getValueByPath(fromObject, ["description"]) !== undefined) { + throw new Error("description parameter is not supported in Gemini API."); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (fromLearningRateMultiplier != null) { + setValueByPath( + toObject, + ["tuningTask", "hyperparameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + if (getValueByPath(fromObject, ["exportLastCheckpointOnly"]) !== undefined) { + throw new Error( + "exportLastCheckpointOnly parameter is not supported in Gemini API.", + ); + } + if (getValueByPath(fromObject, ["adapterSize"]) !== undefined) { + throw new Error("adapterSize parameter is not supported in Gemini API."); + } + const fromBatchSize = getValueByPath(fromObject, ["batchSize"]); + if (parentObject !== undefined && fromBatchSize != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "batchSize"], + fromBatchSize, + ); + } + const fromLearningRate = getValueByPath(fromObject, ["learningRate"]); + if (parentObject !== undefined && fromLearningRate != null) { + setValueByPath( + parentObject, + ["tuningTask", "hyperparameters", "learningRate"], + fromLearningRate, + ); + } + return toObject; +} +function createTuningJobParametersToMldev(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["tuningTask", "trainingData"], + tuningDatasetToMldev(fromTrainingDataset), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToMldev(fromConfig, toObject), + ); + } + return toObject; +} +function getTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["_url", "name"], fromName); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath(toObject, ["config"], fromConfig); + } + return toObject; +} +function listTuningJobsConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromPageSize = getValueByPath(fromObject, ["pageSize"]); + if (parentObject !== undefined && fromPageSize != null) { + setValueByPath(parentObject, ["_query", "pageSize"], fromPageSize); + } + const fromPageToken = getValueByPath(fromObject, ["pageToken"]); + if (parentObject !== undefined && fromPageToken != null) { + setValueByPath(parentObject, ["_query", "pageToken"], fromPageToken); + } + const fromFilter = getValueByPath(fromObject, ["filter"]); + if (parentObject !== undefined && fromFilter != null) { + setValueByPath(parentObject, ["_query", "filter"], fromFilter); + } + return toObject; +} +function listTuningJobsParametersToVertex(fromObject) { + const toObject = {}; + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + listTuningJobsConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tuningDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (parentObject !== undefined && fromGcsUri != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromGcsUri, + ); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + if (getValueByPath(fromObject, ["examples"]) !== undefined) { + throw new Error("examples parameter is not supported in Vertex AI."); + } + return toObject; +} +function tuningValidationDatasetToVertex(fromObject, parentObject) { + const toObject = {}; + const fromGcsUri = getValueByPath(fromObject, ["gcsUri"]); + if (fromGcsUri != null) { + setValueByPath(toObject, ["validationDatasetUri"], fromGcsUri); + } + const fromVertexDatasetResource = getValueByPath(fromObject, [ + "vertexDatasetResource", + ]); + if (parentObject !== undefined && fromVertexDatasetResource != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + fromVertexDatasetResource, + ); + } + return toObject; +} +function createTuningJobConfigToVertex(fromObject, parentObject) { + const toObject = {}; + const fromValidationDataset = getValueByPath(fromObject, [ + "validationDataset", + ]); + if (parentObject !== undefined && fromValidationDataset != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec"], + tuningValidationDatasetToVertex(fromValidationDataset, toObject), + ); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (parentObject !== undefined && fromTunedModelDisplayName != null) { + setValueByPath( + parentObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (parentObject !== undefined && fromDescription != null) { + setValueByPath(parentObject, ["description"], fromDescription); + } + const fromEpochCount = getValueByPath(fromObject, ["epochCount"]); + if (parentObject !== undefined && fromEpochCount != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "epochCount"], + fromEpochCount, + ); + } + const fromLearningRateMultiplier = getValueByPath(fromObject, [ + "learningRateMultiplier", + ]); + if (parentObject !== undefined && fromLearningRateMultiplier != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "learningRateMultiplier"], + fromLearningRateMultiplier, + ); + } + const fromExportLastCheckpointOnly = getValueByPath(fromObject, [ + "exportLastCheckpointOnly", + ]); + if (parentObject !== undefined && fromExportLastCheckpointOnly != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "exportLastCheckpointOnly"], + fromExportLastCheckpointOnly, + ); + } + const fromAdapterSize = getValueByPath(fromObject, ["adapterSize"]); + if (parentObject !== undefined && fromAdapterSize != null) { + setValueByPath( + parentObject, + ["supervisedTuningSpec", "hyperParameters", "adapterSize"], + fromAdapterSize, + ); + } + if (getValueByPath(fromObject, ["batchSize"]) !== undefined) { + throw new Error("batchSize parameter is not supported in Vertex AI."); + } + if (getValueByPath(fromObject, ["learningRate"]) !== undefined) { + throw new Error("learningRate parameter is not supported in Vertex AI."); + } + return toObject; +} +function createTuningJobParametersToVertex(fromObject) { + const toObject = {}; + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTrainingDataset = getValueByPath(fromObject, ["trainingDataset"]); + if (fromTrainingDataset != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec", "trainingDatasetUri"], + tuningDatasetToVertex(fromTrainingDataset, toObject), + ); + } + const fromConfig = getValueByPath(fromObject, ["config"]); + if (fromConfig != null) { + setValueByPath( + toObject, + ["config"], + createTuningJobConfigToVertex(fromConfig, toObject), + ); + } + return toObject; +} +function tunedModelFromMldev(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["name"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["name"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tuningJobFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["tuningTask", "startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, [ + "tuningTask", + "completeTime", + ]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["_self"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromMldev(fromTunedModel), + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tunedModels"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromMldev(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} +function tuningOperationFromMldev(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromMetadata = getValueByPath(fromObject, ["metadata"]); + if (fromMetadata != null) { + setValueByPath(toObject, ["metadata"], fromMetadata); + } + const fromDone = getValueByPath(fromObject, ["done"]); + if (fromDone != null) { + setValueByPath(toObject, ["done"], fromDone); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + return toObject; +} +function tunedModelCheckpointFromVertex(fromObject) { + const toObject = {}; + const fromCheckpointId = getValueByPath(fromObject, ["checkpointId"]); + if (fromCheckpointId != null) { + setValueByPath(toObject, ["checkpointId"], fromCheckpointId); + } + const fromEpoch = getValueByPath(fromObject, ["epoch"]); + if (fromEpoch != null) { + setValueByPath(toObject, ["epoch"], fromEpoch); + } + const fromStep = getValueByPath(fromObject, ["step"]); + if (fromStep != null) { + setValueByPath(toObject, ["step"], fromStep); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + return toObject; +} +function tunedModelFromVertex(fromObject) { + const toObject = {}; + const fromModel = getValueByPath(fromObject, ["model"]); + if (fromModel != null) { + setValueByPath(toObject, ["model"], fromModel); + } + const fromEndpoint = getValueByPath(fromObject, ["endpoint"]); + if (fromEndpoint != null) { + setValueByPath(toObject, ["endpoint"], fromEndpoint); + } + const fromCheckpoints = getValueByPath(fromObject, ["checkpoints"]); + if (fromCheckpoints != null) { + let transformedList = fromCheckpoints; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tunedModelCheckpointFromVertex(item); + }); + } + setValueByPath(toObject, ["checkpoints"], transformedList); + } + return toObject; +} +function tuningJobFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromName = getValueByPath(fromObject, ["name"]); + if (fromName != null) { + setValueByPath(toObject, ["name"], fromName); + } + const fromState = getValueByPath(fromObject, ["state"]); + if (fromState != null) { + setValueByPath(toObject, ["state"], tTuningJobStatus(fromState)); + } + const fromCreateTime = getValueByPath(fromObject, ["createTime"]); + if (fromCreateTime != null) { + setValueByPath(toObject, ["createTime"], fromCreateTime); + } + const fromStartTime = getValueByPath(fromObject, ["startTime"]); + if (fromStartTime != null) { + setValueByPath(toObject, ["startTime"], fromStartTime); + } + const fromEndTime = getValueByPath(fromObject, ["endTime"]); + if (fromEndTime != null) { + setValueByPath(toObject, ["endTime"], fromEndTime); + } + const fromUpdateTime = getValueByPath(fromObject, ["updateTime"]); + if (fromUpdateTime != null) { + setValueByPath(toObject, ["updateTime"], fromUpdateTime); + } + const fromError = getValueByPath(fromObject, ["error"]); + if (fromError != null) { + setValueByPath(toObject, ["error"], fromError); + } + const fromDescription = getValueByPath(fromObject, ["description"]); + if (fromDescription != null) { + setValueByPath(toObject, ["description"], fromDescription); + } + const fromBaseModel = getValueByPath(fromObject, ["baseModel"]); + if (fromBaseModel != null) { + setValueByPath(toObject, ["baseModel"], fromBaseModel); + } + const fromTunedModel = getValueByPath(fromObject, ["tunedModel"]); + if (fromTunedModel != null) { + setValueByPath( + toObject, + ["tunedModel"], + tunedModelFromVertex(fromTunedModel), + ); + } + const fromSupervisedTuningSpec = getValueByPath(fromObject, [ + "supervisedTuningSpec", + ]); + if (fromSupervisedTuningSpec != null) { + setValueByPath( + toObject, + ["supervisedTuningSpec"], + fromSupervisedTuningSpec, + ); + } + const fromTuningDataStats = getValueByPath(fromObject, ["tuningDataStats"]); + if (fromTuningDataStats != null) { + setValueByPath(toObject, ["tuningDataStats"], fromTuningDataStats); + } + const fromEncryptionSpec = getValueByPath(fromObject, ["encryptionSpec"]); + if (fromEncryptionSpec != null) { + setValueByPath(toObject, ["encryptionSpec"], fromEncryptionSpec); + } + const fromPartnerModelTuningSpec = getValueByPath(fromObject, [ + "partnerModelTuningSpec", + ]); + if (fromPartnerModelTuningSpec != null) { + setValueByPath( + toObject, + ["partnerModelTuningSpec"], + fromPartnerModelTuningSpec, + ); + } + const fromDistillationSpec = getValueByPath(fromObject, ["distillationSpec"]); + if (fromDistillationSpec != null) { + setValueByPath(toObject, ["distillationSpec"], fromDistillationSpec); + } + const fromExperiment = getValueByPath(fromObject, ["experiment"]); + if (fromExperiment != null) { + setValueByPath(toObject, ["experiment"], fromExperiment); + } + const fromLabels = getValueByPath(fromObject, ["labels"]); + if (fromLabels != null) { + setValueByPath(toObject, ["labels"], fromLabels); + } + const fromPipelineJob = getValueByPath(fromObject, ["pipelineJob"]); + if (fromPipelineJob != null) { + setValueByPath(toObject, ["pipelineJob"], fromPipelineJob); + } + const fromSatisfiesPzi = getValueByPath(fromObject, ["satisfiesPzi"]); + if (fromSatisfiesPzi != null) { + setValueByPath(toObject, ["satisfiesPzi"], fromSatisfiesPzi); + } + const fromSatisfiesPzs = getValueByPath(fromObject, ["satisfiesPzs"]); + if (fromSatisfiesPzs != null) { + setValueByPath(toObject, ["satisfiesPzs"], fromSatisfiesPzs); + } + const fromServiceAccount = getValueByPath(fromObject, ["serviceAccount"]); + if (fromServiceAccount != null) { + setValueByPath(toObject, ["serviceAccount"], fromServiceAccount); + } + const fromTunedModelDisplayName = getValueByPath(fromObject, [ + "tunedModelDisplayName", + ]); + if (fromTunedModelDisplayName != null) { + setValueByPath( + toObject, + ["tunedModelDisplayName"], + fromTunedModelDisplayName, + ); + } + return toObject; +} +function listTuningJobsResponseFromVertex(fromObject) { + const toObject = {}; + const fromSdkHttpResponse = getValueByPath(fromObject, ["sdkHttpResponse"]); + if (fromSdkHttpResponse != null) { + setValueByPath(toObject, ["sdkHttpResponse"], fromSdkHttpResponse); + } + const fromNextPageToken = getValueByPath(fromObject, ["nextPageToken"]); + if (fromNextPageToken != null) { + setValueByPath(toObject, ["nextPageToken"], fromNextPageToken); + } + const fromTuningJobs = getValueByPath(fromObject, ["tuningJobs"]); + if (fromTuningJobs != null) { + let transformedList = fromTuningJobs; + if (Array.isArray(transformedList)) { + transformedList = transformedList.map((item) => { + return tuningJobFromVertex(item); + }); + } + setValueByPath(toObject, ["tuningJobs"], transformedList); + } + return toObject; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class Tunings extends BaseModule { + constructor(apiClient) { + super(); + this.apiClient = apiClient; + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.get = async (params) => { + return await this.getInternal(params); + }; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.list = async (params = {}) => { + return new Pager( + PagedItem.PAGED_ITEM_TUNING_JOBS, + (x) => this.listInternal(x), + await this.listInternal(params), + params, + ); + }; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + this.tune = async (params) => { + if (this.apiClient.isVertexAI()) { + return await this.tuneInternal(params); + } else { + const operation = await this.tuneMldevInternal(params); + let tunedModelName = ""; + if ( + operation["metadata"] !== undefined && + operation["metadata"]["tunedModel"] !== undefined + ) { + tunedModelName = operation["metadata"]["tunedModel"]; + } else if ( + operation["name"] !== undefined && + operation["name"].includes("/operations/") + ) { + tunedModelName = operation["name"].split("/operations/")[0]; + } + const tuningJob = { + name: tunedModelName, + state: JobState.JOB_STATE_QUEUED, + }; + return tuningJob; + } + }; + } + async getInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = getTuningJobParametersToVertex(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + const body = getTuningJobParametersToMldev(params); + path = formatMap("{name}", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json(); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromMldev(apiResponse); + return resp; + }); + } + } + async listInternal(params) { + var _a, _b, _c, _d; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = listTuningJobsParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromVertex(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + const body = listTuningJobsParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "GET", + httpOptions: + (_c = params.config) === null || _c === void 0 + ? void 0 + : _c.httpOptions, + abortSignal: + (_d = params.config) === null || _d === void 0 + ? void 0 + : _d.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = listTuningJobsResponseFromMldev(apiResponse); + const typedResp = new ListTuningJobsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } + } + async tuneInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + const body = createTuningJobParametersToVertex(params); + path = formatMap("tuningJobs", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningJobFromVertex(apiResponse); + return resp; + }); + } else { + throw new Error("This method is only supported by the Vertex AI."); + } + } + async tuneMldevInternal(params) { + var _a, _b; + let response; + let path = ""; + let queryParams = {}; + if (this.apiClient.isVertexAI()) { + throw new Error( + "This method is only supported by the Gemini Developer API.", + ); + } else { + const body = createTuningJobParametersToMldev(params); + path = formatMap("tunedModels", body["_url"]); + queryParams = body["_query"]; + delete body["config"]; + delete body["_url"]; + delete body["_query"]; + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: "POST", + httpOptions: + (_a = params.config) === null || _a === void 0 + ? void 0 + : _a.httpOptions, + abortSignal: + (_b = params.config) === null || _b === void 0 + ? void 0 + : _b.abortSignal, + }) + .then((httpResponse) => { + return httpResponse.json().then((jsonResponse) => { + const response = jsonResponse; + response.sdkHttpResponse = { + headers: httpResponse.headers, + }; + return response; + }); + }); + return response.then((apiResponse) => { + const resp = tuningOperationFromMldev(apiResponse); + return resp; + }); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserDownloader { + async download(_params, _apiClient) { + throw new Error( + "Download to file is not supported in the browser, please use a browser compliant download like an tag.", + ); + } +} + +const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes +const MAX_RETRY_COUNT = 3; +const INITIAL_RETRY_DELAY_MS = 1000; +const DELAY_MULTIPLIER = 2; +const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = "x-goog-upload-status"; +async function uploadBlob(file, uploadUrl, apiClient) { + var _a, _b, _c; + let fileSize = 0; + let offset = 0; + let response = new HttpResponse(new Response()); + let uploadCommand = "upload"; + fileSize = file.size; + while (offset < fileSize) { + const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset); + const chunk = file.slice(offset, offset + chunkSize); + if (offset + chunkSize >= fileSize) { + uploadCommand += ", finalize"; + } + let retryCount = 0; + let currentDelayMs = INITIAL_RETRY_DELAY_MS; + while (retryCount < MAX_RETRY_COUNT) { + response = await apiClient.request({ + path: "", + body: chunk, + httpMethod: "POST", + httpOptions: { + apiVersion: "", + baseUrl: uploadUrl, + headers: { + "X-Goog-Upload-Command": uploadCommand, + "X-Goog-Upload-Offset": String(offset), + "Content-Length": String(chunkSize), + }, + }, + }); + if ( + (_a = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _a === void 0 + ? void 0 + : _a[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] + ) { + break; + } + retryCount++; + await sleep(currentDelayMs); + currentDelayMs = currentDelayMs * DELAY_MULTIPLIER; + } + offset += chunkSize; + // The `x-goog-upload-status` header field can be `active`, `final` and + //`cancelled` in resposne. + if ( + ((_b = + response === null || response === void 0 + ? void 0 + : response.headers) === null || _b === void 0 + ? void 0 + : _b[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "active" + ) { + break; + } + // TODO(b/401391430) Investigate why the upload status is not finalized + // even though all content has been uploaded. + if (fileSize <= offset) { + throw new Error( + "All content has been uploaded, but the upload status is not finalized.", + ); + } + } + const responseJson = await (response === null || response === void 0 + ? void 0 + : response.json()); + if ( + ((_c = + response === null || response === void 0 ? void 0 : response.headers) === + null || _c === void 0 + ? void 0 + : _c[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) !== "final" + ) { + throw new Error("Failed to upload file: Upload status is not finalized."); + } + return responseJson["file"]; +} +async function getBlobStat(file) { + const fileStat = { size: file.size, type: file.type }; + return fileStat; +} +function sleep(ms) { + return new Promise((resolvePromise) => setTimeout(resolvePromise, ms)); +} + +class BrowserUploader { + async upload(file, uploadUrl, apiClient) { + if (typeof file === "string") { + throw new Error("File path is not supported in browser uploader."); + } + return await uploadBlob(file, uploadUrl, apiClient); + } + async stat(file) { + if (typeof file === "string") { + throw new Error("File path is not supported in browser uploader."); + } else { + return await getBlobStat(file); + } + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +class BrowserWebSocketFactory { + create(url, headers, callbacks) { + return new BrowserWebSocket(url, headers, callbacks); + } +} +class BrowserWebSocket { + constructor(url, headers, callbacks) { + this.url = url; + this.headers = headers; + this.callbacks = callbacks; + } + connect() { + this.ws = new WebSocket(this.url); + 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(message) { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.send(message); + } + close() { + if (this.ws === undefined) { + throw new Error("WebSocket is not connected"); + } + this.ws.close(); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const GOOGLE_API_KEY_HEADER = "x-goog-api-key"; +// TODO(b/395122533): We need a secure client side authentication mechanism. +class WebAuth { + constructor(apiKey) { + this.apiKey = apiKey; + } + async addAuthHeaders(headers) { + if (headers.get(GOOGLE_API_KEY_HEADER) !== null) { + return; + } + if (this.apiKey.startsWith("auth_tokens/")) { + throw new Error("Ephemeral tokens are only supported by the live API."); + } + // Check if API key is empty or null + if (!this.apiKey) { + throw new Error("API key is missing. Please provide a valid API key."); + } + headers.append(GOOGLE_API_KEY_HEADER, this.apiKey); + } +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +const LANGUAGE_LABEL_PREFIX = "gl-node/"; +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +class GoogleGenAI { + constructor(options) { + var _a; + if (options.apiKey == null) { + throw new Error("An API Key must be set when running in a browser"); + } + // Web client only supports API key mode for Vertex AI. + if (options.project || options.location) { + throw new Error( + "Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.", + ); + } + this.vertexai = + (_a = options.vertexai) !== null && _a !== void 0 ? _a : false; + this.apiKey = options.apiKey; + const baseUrl = getBaseUrl( + options.httpOptions, + options.vertexai, + /*vertexBaseUrlFromEnv*/ undefined, + /*geminiBaseUrlFromEnv*/ undefined, + ); + if (baseUrl) { + if (options.httpOptions) { + options.httpOptions.baseUrl = baseUrl; + } else { + options.httpOptions = { baseUrl: baseUrl }; + } + } + this.apiVersion = options.apiVersion; + const auth = new WebAuth(this.apiKey); + this.apiClient = new ApiClient({ + auth: auth, + apiVersion: this.apiVersion, + apiKey: this.apiKey, + vertexai: this.vertexai, + httpOptions: options.httpOptions, + userAgentExtra: LANGUAGE_LABEL_PREFIX + "web", + uploader: new BrowserUploader(), + downloader: new BrowserDownloader(), + }); + this.models = new Models(this.apiClient); + this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory()); + this.batches = new Batches(this.apiClient); + this.chats = new Chats(this.models, this.apiClient); + this.caches = new Caches(this.apiClient); + this.files = new Files(this.apiClient); + this.operations = new Operations(this.apiClient); + this.authTokens = new Tokens(this.apiClient); + this.tunings = new Tunings(this.apiClient); + } +} + +export { + ActivityHandling, + AdapterSize, + ApiError, + ApiSpec, + AuthType, + Batches, + Behavior, + BlockedReason, + Caches, + Chat, + Chats, + ComputeTokensResponse, + ControlReferenceImage, + ControlReferenceType, + CountTokensResponse, + CreateFileResponse, + DeleteCachedContentResponse, + DeleteFileResponse, + DeleteModelResponse, + DynamicRetrievalConfigMode, + EditImageResponse, + EditMode, + EmbedContentResponse, + EndSensitivity, + Environment, + FeatureSelectionPreference, + FileSource, + FileState, + Files, + FinishReason, + FunctionCallingConfigMode, + FunctionResponse, + FunctionResponseScheduling, + GenerateContentResponse, + GenerateContentResponsePromptFeedback, + GenerateContentResponseUsageMetadata, + GenerateImagesResponse, + GenerateVideosOperation, + GenerateVideosResponse, + GoogleGenAI, + HarmBlockMethod, + HarmBlockThreshold, + HarmCategory, + HarmProbability, + HarmSeverity, + HttpResponse, + ImagePromptLanguage, + InlinedResponse, + JobState, + Language, + ListBatchJobsResponse, + ListCachedContentsResponse, + ListFilesResponse, + ListModelsResponse, + ListTuningJobsResponse, + Live, + LiveClientToolResponse, + LiveMusicPlaybackControl, + LiveMusicServerMessage, + LiveSendToolResponseParameters, + LiveServerMessage, + MaskReferenceImage, + MaskReferenceMode, + MediaModality, + MediaResolution, + Modality, + Mode, + Models, + Operations, + Outcome, + PagedItem, + Pager, + PersonGeneration, + RawReferenceImage, + ReplayResponse, + SafetyFilterLevel, + Scale, + Session, + StartSensitivity, + StyleReferenceImage, + SubjectReferenceImage, + SubjectReferenceType, + Tokens, + TrafficType, + TurnCoverage, + Type, + UpscaleImageResponse, + UrlRetrievalStatus, + VideoCompressionQuality, + createModelContent, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromText, + createPartFromUri, + createUserContent, + mcpToTool, + setDefaultBaseUrls, +}; +//# sourceMappingURL=index.mjs.map diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs.map b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs.map new file mode 100644 index 0000000..3f4b31f --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/index.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"index.mjs","sources":["../../src/_base_url.ts","../../src/_common.ts","../../src/_base_transformers.ts","../../src/types.ts","../../src/_transformers.ts","../../src/converters/_batches_converters.ts","../../src/pagers.ts","../../src/batches.ts","../../src/converters/_caches_converters.ts","../../src/caches.ts","../../src/chats.ts","../../src/errors.ts","../../src/converters/_files_converters.ts","../../src/files.ts","../../src/converters/_live_converters.ts","../../src/converters/_models_converters.ts","../../src/_api_client.ts","../../src/mcp/_mcp.ts","../../src/music.ts","../../src/live.ts","../../src/_afc.ts","../../src/models.ts","../../src/converters/_operations_converters.ts","../../src/operations.ts","../../src/converters/_tokens_converters.ts","../../src/tokens.ts","../../src/converters/_tunings_converters.ts","../../src/tunings.ts","../../src/web/_browser_downloader.ts","../../src/cross/_cross_uploader.ts","../../src/web/_browser_uploader.ts","../../src/web/_browser_websocket.ts","../../src/web/_web_auth.ts","../../src/web/web_client.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {HttpOptions} from './types.js';\n\nlet _defaultBaseGeminiUrl: string | undefined = undefined;\nlet _defaultBaseVertexUrl: string | undefined = undefined;\n\n/**\n * Parameters for setting the base URLs for the Gemini API and Vertex AI API.\n */\nexport interface BaseUrlParameters {\n geminiUrl?: string;\n vertexUrl?: string;\n}\n\n/**\n * Overrides the base URLs for the Gemini API and Vertex AI API.\n *\n * @remarks This function should be called before initializing the SDK. If the\n * base URLs are set after initializing the SDK, the base URLs will not be\n * updated. Base URLs provided in the HttpOptions will also take precedence over\n * URLs set here.\n *\n * @example\n * ```ts\n * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai';\n * // Override the base URL for the Gemini API.\n * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'});\n *\n * // Override the base URL for the Vertex AI API.\n * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'});\n *\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n */\nexport function setDefaultBaseUrls(baseUrlParams: BaseUrlParameters) {\n _defaultBaseGeminiUrl = baseUrlParams.geminiUrl;\n _defaultBaseVertexUrl = baseUrlParams.vertexUrl;\n}\n\n/**\n * Returns the default base URLs for the Gemini API and Vertex AI API.\n */\nexport function getDefaultBaseUrls(): BaseUrlParameters {\n return {\n geminiUrl: _defaultBaseGeminiUrl,\n vertexUrl: _defaultBaseVertexUrl,\n };\n}\n\n/**\n * Returns the default base URL based on the following priority:\n * 1. Base URLs set via HttpOptions.\n * 2. Base URLs set via the latest call to setDefaultBaseUrls.\n * 3. Base URLs set via environment variables.\n */\nexport function getBaseUrl(\n httpOptions: HttpOptions | undefined,\n vertexai: boolean | undefined,\n vertexBaseUrlFromEnv: string | undefined,\n geminiBaseUrlFromEnv: string | undefined,\n): string | undefined {\n if (!httpOptions?.baseUrl) {\n const defaultBaseUrls = getDefaultBaseUrls();\n if (vertexai) {\n return defaultBaseUrls.vertexUrl ?? vertexBaseUrlFromEnv;\n } else {\n return defaultBaseUrls.geminiUrl ?? geminiBaseUrlFromEnv;\n }\n }\n\n return httpOptions.baseUrl;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport class BaseModule {}\n\nexport function formatMap(\n templateString: string,\n valueMap: Record,\n): string {\n // Use a regular expression to find all placeholders in the template string\n const regex = /\\{([^}]+)\\}/g;\n\n // Replace each placeholder with its corresponding value from the valueMap\n return templateString.replace(regex, (match, key) => {\n if (Object.prototype.hasOwnProperty.call(valueMap, key)) {\n const value = valueMap[key];\n // Convert the value to a string if it's not a string already\n return value !== undefined && value !== null ? String(value) : '';\n } else {\n // Handle missing keys\n throw new Error(`Key '${key}' not found in valueMap.`);\n }\n });\n}\n\nexport function setValueByPath(\n data: Record,\n keys: string[],\n value: unknown,\n): void {\n for (let i = 0; i < keys.length - 1; i++) {\n const key = keys[i];\n\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (!(keyName in data)) {\n if (Array.isArray(value)) {\n data[keyName] = Array.from({length: value.length}, () => ({}));\n } else {\n throw new Error(`Value must be a list given an array path ${key}`);\n }\n }\n\n if (Array.isArray(data[keyName])) {\n const arrayData = data[keyName] as Array;\n\n if (Array.isArray(value)) {\n for (let j = 0; j < arrayData.length; j++) {\n const entry = arrayData[j] as Record;\n setValueByPath(entry, keys.slice(i + 1), value[j]);\n }\n } else {\n for (const d of arrayData) {\n setValueByPath(\n d as Record,\n keys.slice(i + 1),\n value,\n );\n }\n }\n }\n return;\n } else if (key.endsWith('[0]')) {\n const keyName = key.slice(0, -3);\n if (!(keyName in data)) {\n data[keyName] = [{}];\n }\n const arrayData = (data as Record)[keyName];\n setValueByPath(\n (arrayData as Array>)[0],\n keys.slice(i + 1),\n value,\n );\n return;\n }\n\n if (!data[key] || typeof data[key] !== 'object') {\n data[key] = {};\n }\n\n data = data[key] as Record;\n }\n\n const keyToSet = keys[keys.length - 1];\n const existingData = data[keyToSet];\n\n if (existingData !== undefined) {\n if (\n !value ||\n (typeof value === 'object' && Object.keys(value).length === 0)\n ) {\n return;\n }\n\n if (value === existingData) {\n return;\n }\n\n if (\n typeof existingData === 'object' &&\n typeof value === 'object' &&\n existingData !== null &&\n value !== null\n ) {\n Object.assign(existingData, value);\n } else {\n throw new Error(`Cannot set value for an existing key. Key: ${keyToSet}`);\n }\n } else {\n data[keyToSet] = value;\n }\n}\n\nexport function getValueByPath(data: unknown, keys: string[]): unknown {\n try {\n if (keys.length === 1 && keys[0] === '_self') {\n return data;\n }\n\n for (let i = 0; i < keys.length; i++) {\n if (typeof data !== 'object' || data === null) {\n return undefined;\n }\n\n const key = keys[i];\n if (key.endsWith('[]')) {\n const keyName = key.slice(0, -2);\n if (keyName in data) {\n const arrayData = (data as Record)[keyName];\n if (!Array.isArray(arrayData)) {\n return undefined;\n }\n return arrayData.map((d) => getValueByPath(d, keys.slice(i + 1)));\n } else {\n return undefined;\n }\n } else {\n data = (data as Record)[key];\n }\n }\n\n return data;\n } catch (error) {\n if (error instanceof TypeError) {\n return undefined;\n }\n throw error;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nexport function tBytes(fromBytes: string | unknown): string {\n if (typeof fromBytes !== 'string') {\n throw new Error('fromImageBytes must be a string');\n }\n // TODO(b/389133914): Remove dummy bytes converter.\n return fromBytes;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {tBytes} from './_base_transformers.js';\nimport type {ReferenceImageAPIInternal} from './_internal_types.js';\n\n/** Required. Outcome of the code execution. */\nexport enum Outcome {\n /**\n * Unspecified status. This value should not be used.\n */\n OUTCOME_UNSPECIFIED = 'OUTCOME_UNSPECIFIED',\n /**\n * Code execution completed successfully.\n */\n OUTCOME_OK = 'OUTCOME_OK',\n /**\n * Code execution finished but with a failure. `stderr` should contain the reason.\n */\n OUTCOME_FAILED = 'OUTCOME_FAILED',\n /**\n * Code execution ran for too long, and was cancelled. There may or may not be a partial output present.\n */\n OUTCOME_DEADLINE_EXCEEDED = 'OUTCOME_DEADLINE_EXCEEDED',\n}\n\n/** Required. Programming language of the `code`. */\nexport enum Language {\n /**\n * Unspecified language. This value should not be used.\n */\n LANGUAGE_UNSPECIFIED = 'LANGUAGE_UNSPECIFIED',\n /**\n * Python >= 3.10, with numpy and simpy available.\n */\n PYTHON = 'PYTHON',\n}\n\n/** Optional. The type of the data. */\nexport enum Type {\n /**\n * Not specified, should not be used.\n */\n TYPE_UNSPECIFIED = 'TYPE_UNSPECIFIED',\n /**\n * OpenAPI string type\n */\n STRING = 'STRING',\n /**\n * OpenAPI number type\n */\n NUMBER = 'NUMBER',\n /**\n * OpenAPI integer type\n */\n INTEGER = 'INTEGER',\n /**\n * OpenAPI boolean type\n */\n BOOLEAN = 'BOOLEAN',\n /**\n * OpenAPI array type\n */\n ARRAY = 'ARRAY',\n /**\n * OpenAPI object type\n */\n OBJECT = 'OBJECT',\n /**\n * Null type\n */\n NULL = 'NULL',\n}\n\n/** Required. Harm category. */\nexport enum HarmCategory {\n /**\n * The harm category is unspecified.\n */\n HARM_CATEGORY_UNSPECIFIED = 'HARM_CATEGORY_UNSPECIFIED',\n /**\n * The harm category is hate speech.\n */\n HARM_CATEGORY_HATE_SPEECH = 'HARM_CATEGORY_HATE_SPEECH',\n /**\n * The harm category is dangerous content.\n */\n HARM_CATEGORY_DANGEROUS_CONTENT = 'HARM_CATEGORY_DANGEROUS_CONTENT',\n /**\n * The harm category is harassment.\n */\n HARM_CATEGORY_HARASSMENT = 'HARM_CATEGORY_HARASSMENT',\n /**\n * The harm category is sexually explicit content.\n */\n HARM_CATEGORY_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_SEXUALLY_EXPLICIT',\n /**\n * Deprecated: Election filter is not longer supported. The harm category is civic integrity.\n */\n HARM_CATEGORY_CIVIC_INTEGRITY = 'HARM_CATEGORY_CIVIC_INTEGRITY',\n /**\n * The harm category is image hate.\n */\n HARM_CATEGORY_IMAGE_HATE = 'HARM_CATEGORY_IMAGE_HATE',\n /**\n * The harm category is image dangerous content.\n */\n HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = 'HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT',\n /**\n * The harm category is image harassment.\n */\n HARM_CATEGORY_IMAGE_HARASSMENT = 'HARM_CATEGORY_IMAGE_HARASSMENT',\n /**\n * The harm category is image sexually explicit content.\n */\n HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = 'HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT',\n}\n\n/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */\nexport enum HarmBlockMethod {\n /**\n * The harm block method is unspecified.\n */\n HARM_BLOCK_METHOD_UNSPECIFIED = 'HARM_BLOCK_METHOD_UNSPECIFIED',\n /**\n * The harm block method uses both probability and severity scores.\n */\n SEVERITY = 'SEVERITY',\n /**\n * The harm block method uses the probability score.\n */\n PROBABILITY = 'PROBABILITY',\n}\n\n/** Required. The harm block threshold. */\nexport enum HarmBlockThreshold {\n /**\n * Unspecified harm block threshold.\n */\n HARM_BLOCK_THRESHOLD_UNSPECIFIED = 'HARM_BLOCK_THRESHOLD_UNSPECIFIED',\n /**\n * Block low threshold and above (i.e. block more).\n */\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n /**\n * Block medium threshold and above.\n */\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n /**\n * Block only high threshold (i.e. block less).\n */\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n /**\n * Block none.\n */\n BLOCK_NONE = 'BLOCK_NONE',\n /**\n * Turn off the safety filter.\n */\n OFF = 'OFF',\n}\n\n/** The mode of the predictor to be used in dynamic retrieval. */\nexport enum Mode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Type of auth scheme. */\nexport enum AuthType {\n AUTH_TYPE_UNSPECIFIED = 'AUTH_TYPE_UNSPECIFIED',\n /**\n * No Auth.\n */\n NO_AUTH = 'NO_AUTH',\n /**\n * API Key Auth.\n */\n API_KEY_AUTH = 'API_KEY_AUTH',\n /**\n * HTTP Basic Auth.\n */\n HTTP_BASIC_AUTH = 'HTTP_BASIC_AUTH',\n /**\n * Google Service Account Auth.\n */\n GOOGLE_SERVICE_ACCOUNT_AUTH = 'GOOGLE_SERVICE_ACCOUNT_AUTH',\n /**\n * OAuth auth.\n */\n OAUTH = 'OAUTH',\n /**\n * OpenID Connect (OIDC) Auth.\n */\n OIDC_AUTH = 'OIDC_AUTH',\n}\n\n/** Required. The environment being operated. */\nexport enum Environment {\n /**\n * Defaults to browser.\n */\n ENVIRONMENT_UNSPECIFIED = 'ENVIRONMENT_UNSPECIFIED',\n /**\n * Operates in a web browser.\n */\n ENVIRONMENT_BROWSER = 'ENVIRONMENT_BROWSER',\n}\n\n/** The API spec that the external API implements. */\nexport enum ApiSpec {\n /**\n * Unspecified API spec. This value should not be used.\n */\n API_SPEC_UNSPECIFIED = 'API_SPEC_UNSPECIFIED',\n /**\n * Simple search API spec.\n */\n SIMPLE_SEARCH = 'SIMPLE_SEARCH',\n /**\n * Elastic search API spec.\n */\n ELASTIC_SEARCH = 'ELASTIC_SEARCH',\n}\n\n/** Status of the url retrieval. */\nexport enum UrlRetrievalStatus {\n /**\n * Default value. This value is unused\n */\n URL_RETRIEVAL_STATUS_UNSPECIFIED = 'URL_RETRIEVAL_STATUS_UNSPECIFIED',\n /**\n * Url retrieval is successful.\n */\n URL_RETRIEVAL_STATUS_SUCCESS = 'URL_RETRIEVAL_STATUS_SUCCESS',\n /**\n * Url retrieval is failed due to error.\n */\n URL_RETRIEVAL_STATUS_ERROR = 'URL_RETRIEVAL_STATUS_ERROR',\n}\n\n/** Output only. The reason why the model stopped generating tokens.\n\n If empty, the model has not stopped generating the tokens.\n */\nexport enum FinishReason {\n /**\n * The finish reason is unspecified.\n */\n FINISH_REASON_UNSPECIFIED = 'FINISH_REASON_UNSPECIFIED',\n /**\n * Token generation reached a natural stopping point or a configured stop sequence.\n */\n STOP = 'STOP',\n /**\n * Token generation reached the configured maximum output tokens.\n */\n MAX_TOKENS = 'MAX_TOKENS',\n /**\n * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output.\n */\n SAFETY = 'SAFETY',\n /**\n * The token generation stopped because of potential recitation.\n */\n RECITATION = 'RECITATION',\n /**\n * The token generation stopped because of using an unsupported language.\n */\n LANGUAGE = 'LANGUAGE',\n /**\n * All other reasons that stopped the token generation.\n */\n OTHER = 'OTHER',\n /**\n * Token generation stopped because the content contains forbidden terms.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Token generation stopped for potentially containing prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII).\n */\n SPII = 'SPII',\n /**\n * The function call generated by the model is invalid.\n */\n MALFORMED_FUNCTION_CALL = 'MALFORMED_FUNCTION_CALL',\n /**\n * Token generation stopped because generated images have safety violations.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n /**\n * The tool call generated by the model is invalid.\n */\n UNEXPECTED_TOOL_CALL = 'UNEXPECTED_TOOL_CALL',\n}\n\n/** Output only. Harm probability levels in the content. */\nexport enum HarmProbability {\n /**\n * Harm probability unspecified.\n */\n HARM_PROBABILITY_UNSPECIFIED = 'HARM_PROBABILITY_UNSPECIFIED',\n /**\n * Negligible level of harm.\n */\n NEGLIGIBLE = 'NEGLIGIBLE',\n /**\n * Low level of harm.\n */\n LOW = 'LOW',\n /**\n * Medium level of harm.\n */\n MEDIUM = 'MEDIUM',\n /**\n * High level of harm.\n */\n HIGH = 'HIGH',\n}\n\n/** Output only. Harm severity levels in the content. */\nexport enum HarmSeverity {\n /**\n * Harm severity unspecified.\n */\n HARM_SEVERITY_UNSPECIFIED = 'HARM_SEVERITY_UNSPECIFIED',\n /**\n * Negligible level of harm severity.\n */\n HARM_SEVERITY_NEGLIGIBLE = 'HARM_SEVERITY_NEGLIGIBLE',\n /**\n * Low level of harm severity.\n */\n HARM_SEVERITY_LOW = 'HARM_SEVERITY_LOW',\n /**\n * Medium level of harm severity.\n */\n HARM_SEVERITY_MEDIUM = 'HARM_SEVERITY_MEDIUM',\n /**\n * High level of harm severity.\n */\n HARM_SEVERITY_HIGH = 'HARM_SEVERITY_HIGH',\n}\n\n/** Output only. Blocked reason. */\nexport enum BlockedReason {\n /**\n * Unspecified blocked reason.\n */\n BLOCKED_REASON_UNSPECIFIED = 'BLOCKED_REASON_UNSPECIFIED',\n /**\n * Candidates blocked due to safety.\n */\n SAFETY = 'SAFETY',\n /**\n * Candidates blocked due to other reason.\n */\n OTHER = 'OTHER',\n /**\n * Candidates blocked due to the terms which are included from the terminology blocklist.\n */\n BLOCKLIST = 'BLOCKLIST',\n /**\n * Candidates blocked due to prohibited content.\n */\n PROHIBITED_CONTENT = 'PROHIBITED_CONTENT',\n /**\n * Candidates blocked due to unsafe image generation content.\n */\n IMAGE_SAFETY = 'IMAGE_SAFETY',\n}\n\n/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\nexport enum TrafficType {\n /**\n * Unspecified request traffic type.\n */\n TRAFFIC_TYPE_UNSPECIFIED = 'TRAFFIC_TYPE_UNSPECIFIED',\n /**\n * Type for Pay-As-You-Go traffic.\n */\n ON_DEMAND = 'ON_DEMAND',\n /**\n * Type for Provisioned Throughput traffic.\n */\n PROVISIONED_THROUGHPUT = 'PROVISIONED_THROUGHPUT',\n}\n\n/** Server content modalities. */\nexport enum Modality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Indicates the model should return text\n */\n TEXT = 'TEXT',\n /**\n * Indicates the model should return images.\n */\n IMAGE = 'IMAGE',\n /**\n * Indicates the model should return audio.\n */\n AUDIO = 'AUDIO',\n}\n\n/** The media resolution to use. */\nexport enum MediaResolution {\n /**\n * Media resolution has not been set\n */\n MEDIA_RESOLUTION_UNSPECIFIED = 'MEDIA_RESOLUTION_UNSPECIFIED',\n /**\n * Media resolution set to low (64 tokens).\n */\n MEDIA_RESOLUTION_LOW = 'MEDIA_RESOLUTION_LOW',\n /**\n * Media resolution set to medium (256 tokens).\n */\n MEDIA_RESOLUTION_MEDIUM = 'MEDIA_RESOLUTION_MEDIUM',\n /**\n * Media resolution set to high (zoomed reframing with 256 tokens).\n */\n MEDIA_RESOLUTION_HIGH = 'MEDIA_RESOLUTION_HIGH',\n}\n\n/** Job state. */\nexport enum JobState {\n /**\n * The job state is unspecified.\n */\n JOB_STATE_UNSPECIFIED = 'JOB_STATE_UNSPECIFIED',\n /**\n * The job has been just created or resumed and processing has not yet begun.\n */\n JOB_STATE_QUEUED = 'JOB_STATE_QUEUED',\n /**\n * The service is preparing to run the job.\n */\n JOB_STATE_PENDING = 'JOB_STATE_PENDING',\n /**\n * The job is in progress.\n */\n JOB_STATE_RUNNING = 'JOB_STATE_RUNNING',\n /**\n * The job completed successfully.\n */\n JOB_STATE_SUCCEEDED = 'JOB_STATE_SUCCEEDED',\n /**\n * The job failed.\n */\n JOB_STATE_FAILED = 'JOB_STATE_FAILED',\n /**\n * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`.\n */\n JOB_STATE_CANCELLING = 'JOB_STATE_CANCELLING',\n /**\n * The job has been cancelled.\n */\n JOB_STATE_CANCELLED = 'JOB_STATE_CANCELLED',\n /**\n * The job has been stopped, and can be resumed.\n */\n JOB_STATE_PAUSED = 'JOB_STATE_PAUSED',\n /**\n * The job has expired.\n */\n JOB_STATE_EXPIRED = 'JOB_STATE_EXPIRED',\n /**\n * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state.\n */\n JOB_STATE_UPDATING = 'JOB_STATE_UPDATING',\n /**\n * The job is partially succeeded, some results may be missing due to errors.\n */\n JOB_STATE_PARTIALLY_SUCCEEDED = 'JOB_STATE_PARTIALLY_SUCCEEDED',\n}\n\n/** Optional. Adapter size for tuning. */\nexport enum AdapterSize {\n /**\n * Adapter size is unspecified.\n */\n ADAPTER_SIZE_UNSPECIFIED = 'ADAPTER_SIZE_UNSPECIFIED',\n /**\n * Adapter size 1.\n */\n ADAPTER_SIZE_ONE = 'ADAPTER_SIZE_ONE',\n /**\n * Adapter size 2.\n */\n ADAPTER_SIZE_TWO = 'ADAPTER_SIZE_TWO',\n /**\n * Adapter size 4.\n */\n ADAPTER_SIZE_FOUR = 'ADAPTER_SIZE_FOUR',\n /**\n * Adapter size 8.\n */\n ADAPTER_SIZE_EIGHT = 'ADAPTER_SIZE_EIGHT',\n /**\n * Adapter size 16.\n */\n ADAPTER_SIZE_SIXTEEN = 'ADAPTER_SIZE_SIXTEEN',\n /**\n * Adapter size 32.\n */\n ADAPTER_SIZE_THIRTY_TWO = 'ADAPTER_SIZE_THIRTY_TWO',\n}\n\n/** Options for feature selection preference. */\nexport enum FeatureSelectionPreference {\n FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = 'FEATURE_SELECTION_PREFERENCE_UNSPECIFIED',\n PRIORITIZE_QUALITY = 'PRIORITIZE_QUALITY',\n BALANCED = 'BALANCED',\n PRIORITIZE_COST = 'PRIORITIZE_COST',\n}\n\n/** Defines the function behavior. Defaults to `BLOCKING`. */\nexport enum Behavior {\n /**\n * This value is unused.\n */\n UNSPECIFIED = 'UNSPECIFIED',\n /**\n * If set, the system will wait to receive the function response before continuing the conversation.\n */\n BLOCKING = 'BLOCKING',\n /**\n * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model.\n */\n NON_BLOCKING = 'NON_BLOCKING',\n}\n\n/** Config for the dynamic retrieval config mode. */\nexport enum DynamicRetrievalConfigMode {\n /**\n * Always trigger retrieval.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Run retrieval only when system decides it is necessary.\n */\n MODE_DYNAMIC = 'MODE_DYNAMIC',\n}\n\n/** Config for the function calling config mode. */\nexport enum FunctionCallingConfigMode {\n /**\n * The function calling config mode is unspecified. Should not be used.\n */\n MODE_UNSPECIFIED = 'MODE_UNSPECIFIED',\n /**\n * Default model behavior, model decides to predict either function calls or natural language response.\n */\n AUTO = 'AUTO',\n /**\n * Model is constrained to always predicting function calls only. If \"allowed_function_names\" are set, the predicted function calls will be limited to any one of \"allowed_function_names\", else the predicted function calls will be any one of the provided \"function_declarations\".\n */\n ANY = 'ANY',\n /**\n * Model will not predict any function calls. Model behavior is same as when not passing any function declarations.\n */\n NONE = 'NONE',\n}\n\n/** Enum that controls the safety filter level for objectionable content. */\nexport enum SafetyFilterLevel {\n BLOCK_LOW_AND_ABOVE = 'BLOCK_LOW_AND_ABOVE',\n BLOCK_MEDIUM_AND_ABOVE = 'BLOCK_MEDIUM_AND_ABOVE',\n BLOCK_ONLY_HIGH = 'BLOCK_ONLY_HIGH',\n BLOCK_NONE = 'BLOCK_NONE',\n}\n\n/** Enum that controls the generation of people. */\nexport enum PersonGeneration {\n /**\n * Block generation of images of people.\n */\n DONT_ALLOW = 'DONT_ALLOW',\n /**\n * Generate images of adults, but not children.\n */\n ALLOW_ADULT = 'ALLOW_ADULT',\n /**\n * Generate images that include adults and children.\n */\n ALLOW_ALL = 'ALLOW_ALL',\n}\n\n/** Enum that specifies the language of the text in the prompt. */\nexport enum ImagePromptLanguage {\n /**\n * Auto-detect the language.\n */\n auto = 'auto',\n /**\n * English\n */\n en = 'en',\n /**\n * Japanese\n */\n ja = 'ja',\n /**\n * Korean\n */\n ko = 'ko',\n /**\n * Hindi\n */\n hi = 'hi',\n /**\n * Chinese\n */\n zh = 'zh',\n /**\n * Portuguese\n */\n pt = 'pt',\n /**\n * Spanish\n */\n es = 'es',\n}\n\n/** Enum representing the mask mode of a mask reference image. */\nexport enum MaskReferenceMode {\n MASK_MODE_DEFAULT = 'MASK_MODE_DEFAULT',\n MASK_MODE_USER_PROVIDED = 'MASK_MODE_USER_PROVIDED',\n MASK_MODE_BACKGROUND = 'MASK_MODE_BACKGROUND',\n MASK_MODE_FOREGROUND = 'MASK_MODE_FOREGROUND',\n MASK_MODE_SEMANTIC = 'MASK_MODE_SEMANTIC',\n}\n\n/** Enum representing the control type of a control reference image. */\nexport enum ControlReferenceType {\n CONTROL_TYPE_DEFAULT = 'CONTROL_TYPE_DEFAULT',\n CONTROL_TYPE_CANNY = 'CONTROL_TYPE_CANNY',\n CONTROL_TYPE_SCRIBBLE = 'CONTROL_TYPE_SCRIBBLE',\n CONTROL_TYPE_FACE_MESH = 'CONTROL_TYPE_FACE_MESH',\n}\n\n/** Enum representing the subject type of a subject reference image. */\nexport enum SubjectReferenceType {\n SUBJECT_TYPE_DEFAULT = 'SUBJECT_TYPE_DEFAULT',\n SUBJECT_TYPE_PERSON = 'SUBJECT_TYPE_PERSON',\n SUBJECT_TYPE_ANIMAL = 'SUBJECT_TYPE_ANIMAL',\n SUBJECT_TYPE_PRODUCT = 'SUBJECT_TYPE_PRODUCT',\n}\n\n/** Enum representing the Imagen 3 Edit mode. */\nexport enum EditMode {\n EDIT_MODE_DEFAULT = 'EDIT_MODE_DEFAULT',\n EDIT_MODE_INPAINT_REMOVAL = 'EDIT_MODE_INPAINT_REMOVAL',\n EDIT_MODE_INPAINT_INSERTION = 'EDIT_MODE_INPAINT_INSERTION',\n EDIT_MODE_OUTPAINT = 'EDIT_MODE_OUTPAINT',\n EDIT_MODE_CONTROLLED_EDITING = 'EDIT_MODE_CONTROLLED_EDITING',\n EDIT_MODE_STYLE = 'EDIT_MODE_STYLE',\n EDIT_MODE_BGSWAP = 'EDIT_MODE_BGSWAP',\n EDIT_MODE_PRODUCT_IMAGE = 'EDIT_MODE_PRODUCT_IMAGE',\n}\n\n/** Enum that controls the compression quality of the generated videos. */\nexport enum VideoCompressionQuality {\n /**\n * Optimized video compression quality. This will produce videos\n with a compressed, smaller file size.\n */\n OPTIMIZED = 'OPTIMIZED',\n /**\n * Lossless video compression quality. This will produce videos\n with a larger file size.\n */\n LOSSLESS = 'LOSSLESS',\n}\n\n/** State for the lifecycle of a File. */\nexport enum FileState {\n STATE_UNSPECIFIED = 'STATE_UNSPECIFIED',\n PROCESSING = 'PROCESSING',\n ACTIVE = 'ACTIVE',\n FAILED = 'FAILED',\n}\n\n/** Source of the File. */\nexport enum FileSource {\n SOURCE_UNSPECIFIED = 'SOURCE_UNSPECIFIED',\n UPLOADED = 'UPLOADED',\n GENERATED = 'GENERATED',\n}\n\n/** Server content modalities. */\nexport enum MediaModality {\n /**\n * The modality is unspecified.\n */\n MODALITY_UNSPECIFIED = 'MODALITY_UNSPECIFIED',\n /**\n * Plain text.\n */\n TEXT = 'TEXT',\n /**\n * Images.\n */\n IMAGE = 'IMAGE',\n /**\n * Video.\n */\n VIDEO = 'VIDEO',\n /**\n * Audio.\n */\n AUDIO = 'AUDIO',\n /**\n * Document, e.g. PDF.\n */\n DOCUMENT = 'DOCUMENT',\n}\n\n/** Start of speech sensitivity. */\nexport enum StartSensitivity {\n /**\n * The default is START_SENSITIVITY_LOW.\n */\n START_SENSITIVITY_UNSPECIFIED = 'START_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection will detect the start of speech more often.\n */\n START_SENSITIVITY_HIGH = 'START_SENSITIVITY_HIGH',\n /**\n * Automatic detection will detect the start of speech less often.\n */\n START_SENSITIVITY_LOW = 'START_SENSITIVITY_LOW',\n}\n\n/** End of speech sensitivity. */\nexport enum EndSensitivity {\n /**\n * The default is END_SENSITIVITY_LOW.\n */\n END_SENSITIVITY_UNSPECIFIED = 'END_SENSITIVITY_UNSPECIFIED',\n /**\n * Automatic detection ends speech more often.\n */\n END_SENSITIVITY_HIGH = 'END_SENSITIVITY_HIGH',\n /**\n * Automatic detection ends speech less often.\n */\n END_SENSITIVITY_LOW = 'END_SENSITIVITY_LOW',\n}\n\n/** The different ways of handling user activity. */\nexport enum ActivityHandling {\n /**\n * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`.\n */\n ACTIVITY_HANDLING_UNSPECIFIED = 'ACTIVITY_HANDLING_UNSPECIFIED',\n /**\n * If true, start of activity will interrupt the model's response (also called \"barge in\"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior.\n */\n START_OF_ACTIVITY_INTERRUPTS = 'START_OF_ACTIVITY_INTERRUPTS',\n /**\n * The model's response will not be interrupted.\n */\n NO_INTERRUPTION = 'NO_INTERRUPTION',\n}\n\n/** Options about which input is included in the user's turn. */\nexport enum TurnCoverage {\n /**\n * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`.\n */\n TURN_COVERAGE_UNSPECIFIED = 'TURN_COVERAGE_UNSPECIFIED',\n /**\n * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior.\n */\n TURN_INCLUDES_ONLY_ACTIVITY = 'TURN_INCLUDES_ONLY_ACTIVITY',\n /**\n * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream).\n */\n TURN_INCLUDES_ALL_INPUT = 'TURN_INCLUDES_ALL_INPUT',\n}\n\n/** Specifies how the response should be scheduled in the conversation. */\nexport enum FunctionResponseScheduling {\n /**\n * This value is unused.\n */\n SCHEDULING_UNSPECIFIED = 'SCHEDULING_UNSPECIFIED',\n /**\n * Only add the result to the conversation context, do not interrupt or trigger generation.\n */\n SILENT = 'SILENT',\n /**\n * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation.\n */\n WHEN_IDLE = 'WHEN_IDLE',\n /**\n * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output.\n */\n INTERRUPT = 'INTERRUPT',\n}\n\n/** Scale of the generated music. */\nexport enum Scale {\n /**\n * Default value. This value is unused.\n */\n SCALE_UNSPECIFIED = 'SCALE_UNSPECIFIED',\n /**\n * C major or A minor.\n */\n C_MAJOR_A_MINOR = 'C_MAJOR_A_MINOR',\n /**\n * Db major or Bb minor.\n */\n D_FLAT_MAJOR_B_FLAT_MINOR = 'D_FLAT_MAJOR_B_FLAT_MINOR',\n /**\n * D major or B minor.\n */\n D_MAJOR_B_MINOR = 'D_MAJOR_B_MINOR',\n /**\n * Eb major or C minor\n */\n E_FLAT_MAJOR_C_MINOR = 'E_FLAT_MAJOR_C_MINOR',\n /**\n * E major or Db minor.\n */\n E_MAJOR_D_FLAT_MINOR = 'E_MAJOR_D_FLAT_MINOR',\n /**\n * F major or D minor.\n */\n F_MAJOR_D_MINOR = 'F_MAJOR_D_MINOR',\n /**\n * Gb major or Eb minor.\n */\n G_FLAT_MAJOR_E_FLAT_MINOR = 'G_FLAT_MAJOR_E_FLAT_MINOR',\n /**\n * G major or E minor.\n */\n G_MAJOR_E_MINOR = 'G_MAJOR_E_MINOR',\n /**\n * Ab major or F minor.\n */\n A_FLAT_MAJOR_F_MINOR = 'A_FLAT_MAJOR_F_MINOR',\n /**\n * A major or Gb minor.\n */\n A_MAJOR_G_FLAT_MINOR = 'A_MAJOR_G_FLAT_MINOR',\n /**\n * Bb major or G minor.\n */\n B_FLAT_MAJOR_G_MINOR = 'B_FLAT_MAJOR_G_MINOR',\n /**\n * B major or Ab minor.\n */\n B_MAJOR_A_FLAT_MINOR = 'B_MAJOR_A_FLAT_MINOR',\n}\n\n/** The playback control signal to apply to the music generation. */\nexport enum LiveMusicPlaybackControl {\n /**\n * This value is unused.\n */\n PLAYBACK_CONTROL_UNSPECIFIED = 'PLAYBACK_CONTROL_UNSPECIFIED',\n /**\n * Start generating the music.\n */\n PLAY = 'PLAY',\n /**\n * Hold the music generation. Use PLAY to resume from the current position.\n */\n PAUSE = 'PAUSE',\n /**\n * Stop the music generation and reset the context (prompts retained).\n Use PLAY to restart the music generation.\n */\n STOP = 'STOP',\n /**\n * Reset the context of the music generation without stopping it.\n Retains the current prompts and config.\n */\n RESET_CONTEXT = 'RESET_CONTEXT',\n}\n\n/** Describes how the video in the Part should be used by the model. */\nexport declare interface VideoMetadata {\n /** The frame rate of the video sent to the model. If not specified, the\n default value will be 1.0. The fps range is (0.0, 24.0]. */\n fps?: number;\n /** Optional. The end offset of the video. */\n endOffset?: string;\n /** Optional. The start offset of the video. */\n startOffset?: string;\n}\n\n/** Content blob. */\nexport declare interface Blob {\n /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. Raw bytes.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** URI based data. */\nexport declare interface FileData {\n /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */\n displayName?: string;\n /** Required. URI. */\n fileUri?: string;\n /** Required. The IANA standard MIME type of the source data. */\n mimeType?: string;\n}\n\n/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */\nexport declare interface CodeExecutionResult {\n /** Required. Outcome of the code execution. */\n outcome?: Outcome;\n /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */\n output?: string;\n}\n\n/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */\nexport declare interface ExecutableCode {\n /** Required. The code to be executed. */\n code?: string;\n /** Required. Programming language of the `code`. */\n language?: Language;\n}\n\n/** A function call. */\nexport declare interface FunctionCall {\n /** The unique id of the function call. If populated, the client to execute the\n `function_call` and return the response with the matching `id`. */\n id?: string;\n /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */\n args?: Record;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */\n name?: string;\n}\n\n/** A function response. */\nexport class FunctionResponse {\n /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */\n willContinue?: boolean;\n /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */\n scheduling?: FunctionResponseScheduling;\n /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */\n data?: Part[];\n /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */\n id?: string;\n /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */\n name?: string;\n /** Required. The function response in JSON object format. Use \"output\" key to specify function output and \"error\" key to specify error details (if any). If \"output\" and \"error\" keys are not specified, then whole \"response\" is treated as function output. */\n response?: Record;\n}\n\n/** A datatype containing media content.\n\n Exactly one field within a Part should be set, representing the specific type\n of content being conveyed. Using multiple fields within the same `Part`\n instance is considered invalid.\n */\nexport declare interface Part {\n /** Metadata for a given video. */\n videoMetadata?: VideoMetadata;\n /** Indicates if the part is thought from the model. */\n thought?: boolean;\n /** Optional. Inlined bytes data. */\n inlineData?: Blob;\n /** Optional. URI based data. */\n fileData?: FileData;\n /** An opaque signature for the thought so it can be reused in subsequent requests.\n * @remarks Encoded as base64 string. */\n thoughtSignature?: string;\n /** Optional. Result of executing the [ExecutableCode]. */\n codeExecutionResult?: CodeExecutionResult;\n /** Optional. Code generated by the model that is meant to be executed. */\n executableCode?: ExecutableCode;\n /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */\n functionCall?: FunctionCall;\n /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */\n functionResponse?: FunctionResponse;\n /** Optional. Text part (can be code). */\n text?: string;\n}\n/**\n * Creates a `Part` object from a `URI` string.\n */\nexport function createPartFromUri(uri: string, mimeType: string): Part {\n return {\n fileData: {\n fileUri: uri,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from a `text` string.\n */\nexport function createPartFromText(text: string): Part {\n return {\n text: text,\n };\n}\n/**\n * Creates a `Part` object from a `FunctionCall` object.\n */\nexport function createPartFromFunctionCall(\n name: string,\n args: Record,\n): Part {\n return {\n functionCall: {\n name: name,\n args: args,\n },\n };\n}\n/**\n * Creates a `Part` object from a `FunctionResponse` object.\n */\nexport function createPartFromFunctionResponse(\n id: string,\n name: string,\n response: Record,\n): Part {\n return {\n functionResponse: {\n id: id,\n name: name,\n response: response,\n },\n };\n}\n/**\n * Creates a `Part` object from a `base64` encoded `string`.\n */\nexport function createPartFromBase64(data: string, mimeType: string): Part {\n return {\n inlineData: {\n data: data,\n mimeType: mimeType,\n },\n };\n}\n/**\n * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object.\n */\nexport function createPartFromCodeExecutionResult(\n outcome: Outcome,\n output: string,\n): Part {\n return {\n codeExecutionResult: {\n outcome: outcome,\n output: output,\n },\n };\n}\n/**\n * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object.\n */\nexport function createPartFromExecutableCode(\n code: string,\n language: Language,\n): Part {\n return {\n executableCode: {\n code: code,\n language: language,\n },\n };\n}\n\n/** Contains the multi-part content of a message. */\nexport declare interface Content {\n /** List of parts that constitute a single message. Each part may have\n a different IANA MIME type. */\n parts?: Part[];\n /** Optional. The producer of the content. Must be either 'user' or\n 'model'. Useful to set for multi-turn conversations, otherwise can be\n empty. If role is not specified, SDK will determine the role. */\n role?: string;\n}\nfunction _isPart(obj: unknown): obj is Part {\n if (typeof obj === 'object' && obj !== null) {\n return (\n 'fileData' in obj ||\n 'text' in obj ||\n 'functionCall' in obj ||\n 'functionResponse' in obj ||\n 'inlineData' in obj ||\n 'videoMetadata' in obj ||\n 'codeExecutionResult' in obj ||\n 'executableCode' in obj\n );\n }\n return false;\n}\nfunction _toParts(partOrString: PartListUnion | string): Part[] {\n const parts: Part[] = [];\n if (typeof partOrString === 'string') {\n parts.push(createPartFromText(partOrString));\n } else if (_isPart(partOrString)) {\n parts.push(partOrString);\n } else if (Array.isArray(partOrString)) {\n if (partOrString.length === 0) {\n throw new Error('partOrString cannot be an empty array');\n }\n for (const part of partOrString) {\n if (typeof part === 'string') {\n parts.push(createPartFromText(part));\n } else if (_isPart(part)) {\n parts.push(part);\n } else {\n throw new Error('element in PartUnion must be a Part object or string');\n }\n }\n } else {\n throw new Error('partOrString must be a Part object, string, or array');\n }\n return parts;\n}\n/**\n * Creates a `Content` object with a user role from a `PartListUnion` object or `string`.\n */\nexport function createUserContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'user',\n parts: _toParts(partOrString),\n };\n}\n\n/**\n * Creates a `Content` object with a model role from a `PartListUnion` object or `string`.\n */\nexport function createModelContent(\n partOrString: PartListUnion | string,\n): Content {\n return {\n role: 'model',\n parts: _toParts(partOrString),\n };\n}\n\n/** HTTP options to be used in each of the requests. */\nexport declare interface HttpOptions {\n /** The base URL for the AI platform service endpoint. */\n baseUrl?: string;\n /** Specifies the version of the API to use. */\n apiVersion?: string;\n /** Additional HTTP headers to be sent with the request. */\n headers?: Record;\n /** Timeout for the request in milliseconds. */\n timeout?: number;\n /** Extra parameters to add to the request body.\n The structure must match the backend API's request structure.\n - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest\n - GeminiAPI backend API docs: https://ai.google.dev/api/rest */\n extraBody?: Record;\n}\n\n/** Schema is used to define the format of input/output data.\n\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may\n be added in the future as needed.\n */\nexport declare interface Schema {\n /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */\n anyOf?: Schema[];\n /** Optional. Default value of the data. */\n default?: unknown;\n /** Optional. The description of the data. */\n description?: string;\n /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:[\"EAST\", NORTH\", \"SOUTH\", \"WEST\"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:[\"101\", \"201\", \"301\"]} */\n enum?: string[];\n /** Optional. Example of the object. Will only populated when the object is the root. */\n example?: unknown;\n /** Optional. The format of the data. Supported formats: for NUMBER type: \"float\", \"double\" for INTEGER type: \"int32\", \"int64\" for STRING type: \"email\", \"byte\", etc */\n format?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */\n items?: Schema;\n /** Optional. Maximum number of the elements for Type.ARRAY. */\n maxItems?: string;\n /** Optional. Maximum length of the Type.STRING */\n maxLength?: string;\n /** Optional. Maximum number of the properties for Type.OBJECT. */\n maxProperties?: string;\n /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */\n maximum?: number;\n /** Optional. Minimum number of the elements for Type.ARRAY. */\n minItems?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */\n minLength?: string;\n /** Optional. Minimum number of the properties for Type.OBJECT. */\n minProperties?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */\n minimum?: number;\n /** Optional. Indicates if the value may be null. */\n nullable?: boolean;\n /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */\n pattern?: string;\n /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */\n properties?: Record;\n /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */\n propertyOrdering?: string[];\n /** Optional. Required properties of Type.OBJECT. */\n required?: string[];\n /** Optional. The title of the Schema. */\n title?: string;\n /** Optional. The type of the data. */\n type?: Type;\n}\n\n/** Config for model selection. */\nexport declare interface ModelSelectionConfig {\n /** Options for feature selection preference. */\n featureSelectionPreference?: FeatureSelectionPreference;\n}\n\n/** Safety settings. */\nexport declare interface SafetySetting {\n /** Determines if the harm block method uses probability or probability\n and severity scores. */\n method?: HarmBlockMethod;\n /** Required. Harm category. */\n category?: HarmCategory;\n /** Required. The harm block threshold. */\n threshold?: HarmBlockThreshold;\n}\n\n/** Defines a function that the model can generate JSON inputs for.\n\n The inputs are based on `OpenAPI 3.0 specifications\n `_.\n */\nexport declare interface FunctionDeclaration {\n /** Defines the function behavior. */\n behavior?: Behavior;\n /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */\n description?: string;\n /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */\n name?: string;\n /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */\n parameters?: Schema;\n /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { \"type\": \"object\", \"properties\": { \"name\": { \"type\": \"string\" }, \"age\": { \"type\": \"integer\" } }, \"additionalProperties\": false, \"required\": [\"name\", \"age\"], \"propertyOrdering\": [\"name\", \"age\"] } ``` This field is mutually exclusive with `parameters`. */\n parametersJsonSchema?: unknown;\n /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */\n response?: Schema;\n /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */\n responseJsonSchema?: unknown;\n}\n\n/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive).\n\n The start time must be less than or equal to the end time.\n When the start equals the end time, the interval is an empty interval.\n (matches no time)\n When both start and end are unspecified, the interval matches any time.\n */\nexport declare interface Interval {\n /** The start time of the interval. */\n startTime?: string;\n /** The end time of the interval. */\n endTime?: string;\n}\n\n/** Tool to support Google Search in Model. Powered by Google. */\nexport declare interface GoogleSearch {\n /** Optional. Filter search results to a specific time range.\n If customers set a start time, they must set an end time (and vice versa).\n */\n timeRangeFilter?: Interval;\n}\n\n/** Describes the options to customize dynamic retrieval. */\nexport declare interface DynamicRetrievalConfig {\n /** The mode of the predictor to be used in dynamic retrieval. */\n mode?: DynamicRetrievalConfigMode;\n /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */\n dynamicThreshold?: number;\n}\n\n/** Tool to retrieve public web data for grounding, powered by Google. */\nexport declare interface GoogleSearchRetrieval {\n /** Specifies the dynamic retrieval configuration for the given source. */\n dynamicRetrievalConfig?: DynamicRetrievalConfig;\n}\n\n/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */\nexport declare interface EnterpriseWebSearch {}\n\n/** Config for authentication with API key. */\nexport declare interface ApiKeyConfig {\n /** The API key to be used in the request directly. */\n apiKeyString?: string;\n}\n\n/** Config for Google Service Account Authentication. */\nexport declare interface AuthConfigGoogleServiceAccountConfig {\n /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */\n serviceAccount?: string;\n}\n\n/** Config for HTTP Basic Authentication. */\nexport declare interface AuthConfigHttpBasicAuthConfig {\n /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */\n credentialSecret?: string;\n}\n\n/** Config for user oauth. */\nexport declare interface AuthConfigOauthConfig {\n /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n accessToken?: string;\n /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */\n serviceAccount?: string;\n}\n\n/** Config for user OIDC auth. */\nexport declare interface AuthConfigOidcConfig {\n /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */\n idToken?: string;\n /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */\n serviceAccount?: string;\n}\n\n/** Auth configuration to run the extension. */\nexport declare interface AuthConfig {\n /** Config for API key auth. */\n apiKeyConfig?: ApiKeyConfig;\n /** Type of auth scheme. */\n authType?: AuthType;\n /** Config for Google Service Account auth. */\n googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig;\n /** Config for HTTP Basic auth. */\n httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig;\n /** Config for user oauth. */\n oauthConfig?: AuthConfigOauthConfig;\n /** Config for user OIDC auth. */\n oidcConfig?: AuthConfigOidcConfig;\n}\n\n/** Tool to support Google Maps in Model. */\nexport declare interface GoogleMaps {\n /** Optional. Auth config for the Google Maps tool. */\n authConfig?: AuthConfig;\n}\n\n/** Tool to support URL context retrieval. */\nexport declare interface UrlContext {}\n\n/** Computer Use tool type. */\nexport declare interface ToolComputerUse {\n /** A list of predefined functions that the should not be prepopulated. */\n excludedPredefinedFunctions?: string[];\n /** Required. The environment being operated. */\n environment?: Environment;\n}\n\n/** The API secret. */\nexport declare interface ApiAuthApiKeyConfig {\n /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */\n apiKeySecretVersion?: string;\n /** The API key string. Either this or `api_key_secret_version` must be set. */\n apiKeyString?: string;\n}\n\n/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */\nexport declare interface ApiAuth {\n /** The API secret. */\n apiKeyConfig?: ApiAuthApiKeyConfig;\n}\n\n/** The search parameters to use for the ELASTIC_SEARCH spec. */\nexport declare interface ExternalApiElasticSearchParams {\n /** The ElasticSearch index to use. */\n index?: string;\n /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */\n numHits?: number;\n /** The ElasticSearch search template to use. */\n searchTemplate?: string;\n}\n\n/** The search parameters to use for SIMPLE_SEARCH spec. */\nexport declare interface ExternalApiSimpleSearchParams {}\n\n/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */\nexport declare interface ExternalApi {\n /** The authentication config to access the API. Deprecated. Please use auth_config instead. */\n apiAuth?: ApiAuth;\n /** The API spec that the external API implements. */\n apiSpec?: ApiSpec;\n /** The authentication config to access the API. */\n authConfig?: AuthConfig;\n /** Parameters for the elastic search API. */\n elasticSearchParams?: ExternalApiElasticSearchParams;\n /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */\n endpoint?: string;\n /** Parameters for the simple search API. */\n simpleSearchParams?: ExternalApiSimpleSearchParams;\n}\n\n/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */\nexport declare interface VertexAISearchDataStoreSpec {\n /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n dataStore?: string;\n /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */\n filter?: string;\n}\n\n/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */\nexport declare interface VertexAISearch {\n /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */\n dataStoreSpecs?: VertexAISearchDataStoreSpec[];\n /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */\n datastore?: string;\n /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */\n engine?: string;\n /** Optional. Filter strings to be passed to the search API. */\n filter?: string;\n /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */\n maxResults?: number;\n}\n\n/** The definition of the Rag resource. */\nexport declare interface VertexRagStoreRagResource {\n /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */\n ragCorpus?: string;\n /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */\n ragFileIds?: string[];\n}\n\n/** Config for filters. */\nexport declare interface RagRetrievalConfigFilter {\n /** Optional. String for metadata filtering. */\n metadataFilter?: string;\n /** Optional. Only returns contexts with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n /** Optional. Only returns contexts with vector similarity larger than the threshold. */\n vectorSimilarityThreshold?: number;\n}\n\n/** Config for Hybrid Search. */\nexport declare interface RagRetrievalConfigHybridSearch {\n /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */\n alpha?: number;\n}\n\n/** Config for LlmRanker. */\nexport declare interface RagRetrievalConfigRankingLlmRanker {\n /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** Config for Rank Service. */\nexport declare interface RagRetrievalConfigRankingRankService {\n /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */\n modelName?: string;\n}\n\n/** Config for ranking and reranking. */\nexport declare interface RagRetrievalConfigRanking {\n /** Optional. Config for LlmRanker. */\n llmRanker?: RagRetrievalConfigRankingLlmRanker;\n /** Optional. Config for Rank Service. */\n rankService?: RagRetrievalConfigRankingRankService;\n}\n\n/** Specifies the context retrieval config. */\nexport declare interface RagRetrievalConfig {\n /** Optional. Config for filters. */\n filter?: RagRetrievalConfigFilter;\n /** Optional. Config for Hybrid Search. */\n hybridSearch?: RagRetrievalConfigHybridSearch;\n /** Optional. Config for ranking and reranking. */\n ranking?: RagRetrievalConfigRanking;\n /** Optional. The number of contexts to retrieve. */\n topK?: number;\n}\n\n/** Retrieve from Vertex RAG Store for grounding. */\nexport declare interface VertexRagStore {\n /** Optional. Deprecated. Please use rag_resources instead. */\n ragCorpora?: string[];\n /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */\n ragResources?: VertexRagStoreRagResource[];\n /** Optional. The retrieval config for the Rag query. */\n ragRetrievalConfig?: RagRetrievalConfig;\n /** Optional. Number of top k results to return from the selected corpora. */\n similarityTopK?: number;\n /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */\n storeContext?: boolean;\n /** Optional. Only return results with vector distance smaller than the threshold. */\n vectorDistanceThreshold?: number;\n}\n\n/** Defines a retrieval tool that model can call to access external knowledge. */\nexport declare interface Retrieval {\n /** Optional. Deprecated. This option is no longer supported. */\n disableAttribution?: boolean;\n /** Use data source powered by external API for grounding. */\n externalApi?: ExternalApi;\n /** Set to use data source powered by Vertex AI Search. */\n vertexAiSearch?: VertexAISearch;\n /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */\n vertexRagStore?: VertexRagStore;\n}\n\n/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */\nexport declare interface ToolCodeExecution {}\n\n/** Tool details of a tool that the model may use to generate a response. */\nexport declare interface Tool {\n /** List of function declarations that the tool supports. */\n functionDeclarations?: FunctionDeclaration[];\n /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */\n retrieval?: Retrieval;\n /** Optional. Google Search tool type. Specialized retrieval tool\n that is powered by Google Search. */\n googleSearch?: GoogleSearch;\n /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */\n googleSearchRetrieval?: GoogleSearchRetrieval;\n /** Optional. Enterprise web search tool type. Specialized retrieval\n tool that is powered by Vertex AI Search and Sec4 compliance. */\n enterpriseWebSearch?: EnterpriseWebSearch;\n /** Optional. Google Maps tool type. Specialized retrieval tool\n that is powered by Google Maps. */\n googleMaps?: GoogleMaps;\n /** Optional. Tool to support URL context retrieval. */\n urlContext?: UrlContext;\n /** \n Tool to support the model interacting directly with the computer.\n If enabled, it automatically populates computer-use specific Function\n Declarations. */\n computerUse?: ToolComputerUse;\n /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */\n codeExecution?: ToolCodeExecution;\n}\n\n/** Function calling config. */\nexport declare interface FunctionCallingConfig {\n /** Optional. Function calling mode. */\n mode?: FunctionCallingConfigMode;\n /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */\n allowedFunctionNames?: string[];\n}\n\n/** An object that represents a latitude/longitude pair.\n\n This is expressed as a pair of doubles to represent degrees latitude and\n degrees longitude. Unless specified otherwise, this object must conform to the\n \n WGS84 standard. Values must be within normalized ranges.\n */\nexport declare interface LatLng {\n /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */\n latitude?: number;\n /** The longitude in degrees. It must be in the range [-180.0, +180.0] */\n longitude?: number;\n}\n\n/** Retrieval config.\n */\nexport declare interface RetrievalConfig {\n /** Optional. The location of the user. */\n latLng?: LatLng;\n /** The language code of the user. */\n languageCode?: string;\n}\n\n/** Tool config.\n\n This config is shared for all tools provided in the request.\n */\nexport declare interface ToolConfig {\n /** Optional. Function calling config. */\n functionCallingConfig?: FunctionCallingConfig;\n /** Optional. Retrieval config. */\n retrievalConfig?: RetrievalConfig;\n}\n\n/** The configuration for the prebuilt speaker to use. */\nexport declare interface PrebuiltVoiceConfig {\n /** The name of the prebuilt voice to use. */\n voiceName?: string;\n}\n\n/** The configuration for the voice to use. */\nexport declare interface VoiceConfig {\n /** The configuration for the speaker to use.\n */\n prebuiltVoiceConfig?: PrebuiltVoiceConfig;\n}\n\n/** The configuration for the speaker to use. */\nexport declare interface SpeakerVoiceConfig {\n /** The name of the speaker to use. Should be the same as in the\n prompt. */\n speaker?: string;\n /** The configuration for the voice to use. */\n voiceConfig?: VoiceConfig;\n}\n\n/** The configuration for the multi-speaker setup. */\nexport declare interface MultiSpeakerVoiceConfig {\n /** The configuration for the speaker to use. */\n speakerVoiceConfigs?: SpeakerVoiceConfig[];\n}\n\n/** The speech generation configuration. */\nexport declare interface SpeechConfig {\n /** The configuration for the speaker to use.\n */\n voiceConfig?: VoiceConfig;\n /** The configuration for the multi-speaker setup.\n It is mutually exclusive with the voice_config field.\n */\n multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig;\n /** Language code (ISO 639. e.g. en-US) for the speech synthesization.\n Only available for Live API.\n */\n languageCode?: string;\n}\n\n/** The configuration for automatic function calling. */\nexport declare interface AutomaticFunctionCallingConfig {\n /** Whether to disable automatic function calling.\n If not set or set to False, will enable automatic function calling.\n If set to True, will disable automatic function calling.\n */\n disable?: boolean;\n /** If automatic function calling is enabled,\n maximum number of remote calls for automatic function calling.\n This number should be a positive integer.\n If not set, SDK will set maximum number of remote calls to 10.\n */\n maximumRemoteCalls?: number;\n /** If automatic function calling is enabled,\n whether to ignore call history to the response.\n If not set, SDK will set ignore_call_history to false,\n and will append the call history to\n GenerateContentResponse.automatic_function_calling_history.\n */\n ignoreCallHistory?: boolean;\n}\n\n/** The thinking features configuration. */\nexport declare interface ThinkingConfig {\n /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available.\n */\n includeThoughts?: boolean;\n /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent.\n */\n thinkingBudget?: number;\n}\n\n/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */\nexport declare interface GenerationConfigRoutingConfigAutoRoutingMode {\n /** The model routing preference. */\n modelRoutingPreference?:\n | 'UNKNOWN'\n | 'PRIORITIZE_QUALITY'\n | 'BALANCED'\n | 'PRIORITIZE_COST';\n}\n\n/** When manual routing is set, the specified model will be used directly. */\nexport declare interface GenerationConfigRoutingConfigManualRoutingMode {\n /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */\n modelName?: string;\n}\n\n/** The configuration for routing the request to a specific model. */\nexport declare interface GenerationConfigRoutingConfig {\n /** Automated routing. */\n autoMode?: GenerationConfigRoutingConfigAutoRoutingMode;\n /** Manual routing. */\n manualMode?: GenerationConfigRoutingConfigManualRoutingMode;\n}\n\n/** Optional model configuration parameters.\n\n For more information, see `Content generation parameters\n `_.\n */\nexport declare interface GenerateContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n For example, \"Answer as concisely as possible\" or \"Don't use technical\n terms in your response\".\n */\n systemInstruction?: ContentUnion;\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Number of response variations to return.\n */\n candidateCount?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** List of strings that tells the model to stop generating text if one\n of the strings is encountered in the response.\n */\n stopSequences?: string[];\n /** Whether to return the log probabilities of the tokens that were\n chosen by the model at each step.\n */\n responseLogprobs?: boolean;\n /** Number of top candidate tokens to return the log probabilities for\n at each generation step.\n */\n logprobs?: number;\n /** Positive values penalize tokens that already appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n presencePenalty?: number;\n /** Positive values penalize tokens that repeatedly appear in the\n generated text, increasing the probability of generating more diverse\n content.\n */\n frequencyPenalty?: number;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** Output response mimetype of the generated candidate text.\n Supported mimetype:\n - `text/plain`: (default) Text output.\n - `application/json`: JSON response in the candidates.\n The model needs to be prompted to output the appropriate response type,\n otherwise the behavior is undefined.\n This is a preview feature.\n */\n responseMimeType?: string;\n /** The `Schema` object allows the definition of input and output data types.\n These types can be objects, but also primitives and arrays.\n Represents a select subset of an [OpenAPI 3.0 schema\n object](https://spec.openapis.org/oas/v3.0.3#schema).\n If set, a compatible response_mime_type must also be set.\n Compatible mimetypes: `application/json`: Schema for JSON response.\n */\n responseSchema?: SchemaUnion;\n /** Optional. Output schema of the generated response.\n This is an alternative to `response_schema` that accepts [JSON\n Schema](https://json-schema.org/). If set, `response_schema` must be\n omitted, but `response_mime_type` is required. While the full JSON Schema\n may be sent, not all features are supported. Specifically, only the\n following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor`\n - `type` - `format` - `title` - `description` - `enum` (for strings and\n numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` -\n `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) -\n `properties` - `additionalProperties` - `required` The non-standard\n `propertyOrdering` property may also be set. Cyclic references are\n unrolled to a limited degree and, as such, may only be used within\n non-required properties. (Nullable properties are not sufficient.) If\n `$ref` is set on a sub-schema, no other properties, except for than those\n starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Configuration for model router requests.\n */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Configuration for model selection.\n */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Safety settings in the request to block unsafe content in the\n response.\n */\n safetySettings?: SafetySetting[];\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: ToolListUnion;\n /** Associates model output to a specific function call.\n */\n toolConfig?: ToolConfig;\n /** Labels with user-defined metadata to break down billed charges. */\n labels?: Record;\n /** Resource name of a context cache that can be used in subsequent\n requests.\n */\n cachedContent?: string;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return.\n */\n responseModalities?: string[];\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfigUnion;\n /** If enabled, audio timestamp will be included in the request to the\n model.\n */\n audioTimestamp?: boolean;\n /** The configuration for automatic function calling.\n */\n automaticFunctionCalling?: AutomaticFunctionCallingConfig;\n /** The thinking features configuration.\n */\n thinkingConfig?: ThinkingConfig;\n}\n\n/** Config for models.generate_content parameters. */\nexport declare interface GenerateContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Content of the request.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** A wrapper class for the http response. */\nexport class HttpResponse {\n /** Used to retain the processed HTTP headers in the response. */\n headers?: Record;\n /**\n * The original http response.\n */\n responseInternal: Response;\n\n constructor(response: Response) {\n // Process the headers.\n const headers: Record = {};\n for (const pair of response.headers.entries()) {\n headers[pair[0]] = pair[1];\n }\n this.headers = headers;\n\n // Keep the original response.\n this.responseInternal = response;\n }\n\n json(): Promise {\n return this.responseInternal.json();\n }\n}\n\n/** Callbacks for the live API. */\nexport interface LiveCallbacks {\n /**\n * Called when the websocket connection is established.\n */\n onopen?: (() => void) | null;\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */\nexport declare interface GoogleTypeDate {\n /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */\n day?: number;\n /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */\n month?: number;\n /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */\n year?: number;\n}\n\n/** Source attributions for content. */\nexport declare interface Citation {\n /** Output only. End index into the content. */\n endIndex?: number;\n /** Output only. License of the attribution. */\n license?: string;\n /** Output only. Publication date of the attribution. */\n publicationDate?: GoogleTypeDate;\n /** Output only. Start index into the content. */\n startIndex?: number;\n /** Output only. Title of the attribution. */\n title?: string;\n /** Output only. Url reference of the attribution. */\n uri?: string;\n}\n\n/** Citation information when the model quotes another source. */\nexport declare interface CitationMetadata {\n /** Contains citation information when the model directly quotes, at\n length, from another source. Can include traditional websites and code\n repositories.\n */\n citations?: Citation[];\n}\n\n/** Context for a single url retrieval. */\nexport declare interface UrlMetadata {\n /** The URL retrieved by the tool. */\n retrievedUrl?: string;\n /** Status of the url retrieval. */\n urlRetrievalStatus?: UrlRetrievalStatus;\n}\n\n/** Metadata related to url context retrieval tool. */\nexport declare interface UrlContextMetadata {\n /** List of url context. */\n urlMetadata?: UrlMetadata[];\n}\n\n/** Represents where the chunk starts and ends in the document. */\nexport declare interface RagChunkPageSpan {\n /** Page where chunk starts in the document. Inclusive. 1-indexed. */\n firstPage?: number;\n /** Page where chunk ends in the document. Inclusive. 1-indexed. */\n lastPage?: number;\n}\n\n/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */\nexport declare interface RagChunk {\n /** If populated, represents where the chunk starts and ends in the document. */\n pageSpan?: RagChunkPageSpan;\n /** The content of the chunk. */\n text?: string;\n}\n\n/** Chunk from context retrieved by the retrieval tools. */\nexport declare interface GroundingChunkRetrievedContext {\n /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */\n ragChunk?: RagChunk;\n /** Text of the attribution. */\n text?: string;\n /** Title of the attribution. */\n title?: string;\n /** URI reference of the attribution. */\n uri?: string;\n}\n\n/** Chunk from the web. */\nexport declare interface GroundingChunkWeb {\n /** Domain of the (original) URI. */\n domain?: string;\n /** Title of the chunk. */\n title?: string;\n /** URI reference of the chunk. */\n uri?: string;\n}\n\n/** Grounding chunk. */\nexport declare interface GroundingChunk {\n /** Grounding chunk from context retrieved by the retrieval tools. */\n retrievedContext?: GroundingChunkRetrievedContext;\n /** Grounding chunk from the web. */\n web?: GroundingChunkWeb;\n}\n\n/** Segment of the content. */\nexport declare interface Segment {\n /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */\n endIndex?: number;\n /** Output only. The index of a Part object within its parent Content object. */\n partIndex?: number;\n /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */\n startIndex?: number;\n /** Output only. The text corresponding to the segment from the response. */\n text?: string;\n}\n\n/** Grounding support. */\nexport declare interface GroundingSupport {\n /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */\n confidenceScores?: number[];\n /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */\n groundingChunkIndices?: number[];\n /** Segment of the content this support belongs to. */\n segment?: Segment;\n}\n\n/** Metadata related to retrieval in the grounding flow. */\nexport declare interface RetrievalMetadata {\n /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */\n googleSearchDynamicRetrievalScore?: number;\n}\n\n/** Google search entry point. */\nexport declare interface SearchEntryPoint {\n /** Optional. Web content snippet that can be embedded in a web page or an app webview. */\n renderedContent?: string;\n /** Optional. Base64 encoded JSON representing array of tuple.\n * @remarks Encoded as base64 string. */\n sdkBlob?: string;\n}\n\n/** Metadata returned to client when grounding is enabled. */\nexport declare interface GroundingMetadata {\n /** List of supporting references retrieved from specified grounding source. */\n groundingChunks?: GroundingChunk[];\n /** Optional. List of grounding support. */\n groundingSupports?: GroundingSupport[];\n /** Optional. Output only. Retrieval metadata. */\n retrievalMetadata?: RetrievalMetadata;\n /** Optional. Queries executed by the retrieval tools. */\n retrievalQueries?: string[];\n /** Optional. Google search entry for the following-up web searches. */\n searchEntryPoint?: SearchEntryPoint;\n /** Optional. Web search queries for the following-up web search. */\n webSearchQueries?: string[];\n}\n\n/** Candidate for the logprobs token and score. */\nexport declare interface LogprobsResultCandidate {\n /** The candidate's log probability. */\n logProbability?: number;\n /** The candidate's token string value. */\n token?: string;\n /** The candidate's token id value. */\n tokenId?: number;\n}\n\n/** Candidates with top log probabilities at each decoding step. */\nexport declare interface LogprobsResultTopCandidates {\n /** Sorted by log probability in descending order. */\n candidates?: LogprobsResultCandidate[];\n}\n\n/** Logprobs Result */\nexport declare interface LogprobsResult {\n /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */\n chosenCandidates?: LogprobsResultCandidate[];\n /** Length = total number of decoding steps. */\n topCandidates?: LogprobsResultTopCandidates[];\n}\n\n/** Safety rating corresponding to the generated content. */\nexport declare interface SafetyRating {\n /** Output only. Indicates whether the content was filtered out because of this rating. */\n blocked?: boolean;\n /** Output only. Harm category. */\n category?: HarmCategory;\n /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */\n overwrittenThreshold?: HarmBlockThreshold;\n /** Output only. Harm probability levels in the content. */\n probability?: HarmProbability;\n /** Output only. Harm probability score. */\n probabilityScore?: number;\n /** Output only. Harm severity levels in the content. */\n severity?: HarmSeverity;\n /** Output only. Harm severity score. */\n severityScore?: number;\n}\n\n/** A response candidate generated from the model. */\nexport declare interface Candidate {\n /** Contains the multi-part content of the response.\n */\n content?: Content;\n /** Source attribution of the generated content.\n */\n citationMetadata?: CitationMetadata;\n /** Describes the reason the model stopped generating tokens.\n */\n finishMessage?: string;\n /** Number of tokens for this candidate.\n */\n tokenCount?: number;\n /** The reason why the model stopped generating tokens.\n If empty, the model has not stopped generating the tokens.\n */\n finishReason?: FinishReason;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n /** Output only. Average log probability score of the candidate. */\n avgLogprobs?: number;\n /** Output only. Metadata specifies sources used to ground generated content. */\n groundingMetadata?: GroundingMetadata;\n /** Output only. Index of the candidate. */\n index?: number;\n /** Output only. Log-likelihood scores for the response tokens and top tokens */\n logprobsResult?: LogprobsResult;\n /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Content filter results for a prompt sent in the request. */\nexport class GenerateContentResponsePromptFeedback {\n /** Output only. Blocked reason. */\n blockReason?: BlockedReason;\n /** Output only. A readable block reason message. */\n blockReasonMessage?: string;\n /** Output only. Safety ratings. */\n safetyRatings?: SafetyRating[];\n}\n\n/** Represents token counting info for a single modality. */\nexport declare interface ModalityTokenCount {\n /** The modality associated with this token count. */\n modality?: MediaModality;\n /** Number of tokens. */\n tokenCount?: number;\n}\n\n/** Usage metadata about response(s). */\nexport class GenerateContentResponseUsageMetadata {\n /** Output only. List of modalities of the cached content in the request input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens in the cached part in the input (the cached content). */\n cachedContentTokenCount?: number;\n /** Number of tokens in the response(s). */\n candidatesTokenCount?: number;\n /** Output only. List of modalities that were returned in the response. */\n candidatesTokensDetails?: ModalityTokenCount[];\n /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Output only. List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** Output only. Number of tokens present in thoughts output. */\n thoughtsTokenCount?: number;\n /** Output only. Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Output only. List of modalities that were processed for tool-use request inputs. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Total token count for prompt, response candidates, and tool-use prompts (if present). */\n totalTokenCount?: number;\n /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Response message for PredictionService.GenerateContent. */\nexport class GenerateContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Response variations returned by the model.\n */\n candidates?: Candidate[];\n /** Timestamp when the request is made to the server.\n */\n createTime?: string;\n /** Identifier for each response.\n */\n responseId?: string;\n /** The history of automatic function calling.\n */\n automaticFunctionCallingHistory?: Content[];\n /** Output only. The model version used to generate the response. */\n modelVersion?: string;\n /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */\n promptFeedback?: GenerateContentResponsePromptFeedback;\n /** Usage metadata about the response(s). */\n usageMetadata?: GenerateContentResponseUsageMetadata;\n /**\n * Returns the concatenation of all text parts from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the text from the first\n * one will be returned.\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n * If there are thought parts in the response, the concatenation of all text\n * parts excluding the thought parts will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'Why is the sky blue?',\n * });\n *\n * console.debug(response.text);\n * ```\n */\n get text(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning text from the first one.',\n );\n }\n let text = '';\n let anyTextPartText = false;\n const nonTextParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartText = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartText ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the first candidate\n * in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the inline data from the\n * first one will be returned. If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning data from the first one.',\n );\n }\n let data = '';\n const nonDataParts = [];\n for (const part of this.candidates?.[0]?.content?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'inlineData' &&\n (fieldValue !== null || fieldValue !== undefined)\n ) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n\n /**\n * Returns the function calls from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the function calls from\n * the first one will be returned.\n * If there are no function calls in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const controlLightFunctionDeclaration: FunctionDeclaration = {\n * name: 'controlLight',\n * parameters: {\n * type: Type.OBJECT,\n * description: 'Set the brightness and color temperature of a room light.',\n * properties: {\n * brightness: {\n * type: Type.NUMBER,\n * description:\n * 'Light level from 0 to 100. Zero is off and 100 is full brightness.',\n * },\n * colorTemperature: {\n * type: Type.STRING,\n * description:\n * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.',\n * },\n * },\n * required: ['brightness', 'colorTemperature'],\n * };\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'Dim the lights so the room feels cozy and warm.',\n * config: {\n * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}],\n * toolConfig: {\n * functionCallingConfig: {\n * mode: FunctionCallingConfigMode.ANY,\n * allowedFunctionNames: ['controlLight'],\n * },\n * },\n * },\n * });\n * console.debug(JSON.stringify(response.functionCalls));\n * ```\n */\n get functionCalls(): FunctionCall[] | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning function calls from the first one.',\n );\n }\n const functionCalls = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.functionCall)\n .map((part) => part.functionCall)\n .filter(\n (functionCall): functionCall is FunctionCall =>\n functionCall !== undefined,\n );\n if (functionCalls?.length === 0) {\n return undefined;\n }\n return functionCalls;\n }\n /**\n * Returns the first executable code from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the executable code from\n * the first one will be returned.\n * If there are no executable code in the response, undefined will be\n * returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.executableCode);\n * ```\n */\n get executableCode(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning executable code from the first one.',\n );\n }\n const executableCode = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.executableCode)\n .map((part) => part.executableCode)\n .filter(\n (executableCode): executableCode is ExecutableCode =>\n executableCode !== undefined,\n );\n if (executableCode?.length === 0) {\n return undefined;\n }\n\n return executableCode?.[0]?.code;\n }\n /**\n * Returns the first code execution result from the first candidate in the response.\n *\n * @remarks\n * If there are multiple candidates in the response, the code execution result from\n * the first one will be returned.\n * If there are no code execution result in the response, undefined will be returned.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents:\n * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.'\n * config: {\n * tools: [{codeExecution: {}}],\n * },\n * });\n *\n * console.debug(response.codeExecutionResult);\n * ```\n */\n get codeExecutionResult(): string | undefined {\n if (this.candidates?.[0]?.content?.parts?.length === 0) {\n return undefined;\n }\n if (this.candidates && this.candidates.length > 1) {\n console.warn(\n 'there are multiple candidates in the response, returning code execution result from the first one.',\n );\n }\n const codeExecutionResult = this.candidates?.[0]?.content?.parts\n ?.filter((part) => part.codeExecutionResult)\n .map((part) => part.codeExecutionResult)\n .filter(\n (codeExecutionResult): codeExecutionResult is CodeExecutionResult =>\n codeExecutionResult !== undefined,\n );\n if (codeExecutionResult?.length === 0) {\n return undefined;\n }\n return codeExecutionResult?.[0]?.output;\n }\n}\n\nexport type ReferenceImage =\n | RawReferenceImage\n | MaskReferenceImage\n | ControlReferenceImage\n | StyleReferenceImage\n | SubjectReferenceImage;\n\n/** Parameters for the request to edit an image. */\nexport declare interface EditImageParameters {\n /** The model to use. */\n model: string;\n /** A text description of the edit to apply to the image. */\n prompt: string;\n /** The reference images for Imagen 3 editing. */\n referenceImages: ReferenceImage[];\n /** Configuration for editing. */\n config?: EditImageConfig;\n}\n\n/** Optional parameters for the embed_content method. */\nexport declare interface EmbedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Type of task for which the embedding will be used.\n */\n taskType?: string;\n /** Title for the text. Only applicable when TaskType is\n `RETRIEVAL_DOCUMENT`.\n */\n title?: string;\n /** Reduced dimension for the output embedding. If set,\n excessive values in the output embedding are truncated from the end.\n Supported by newer models since 2024 only. You cannot set this value if\n using the earlier model (`models/embedding-001`).\n */\n outputDimensionality?: number;\n /** Vertex API only. The MIME type of the input.\n */\n mimeType?: string;\n /** Vertex API only. Whether to silently truncate inputs longer than\n the max sequence length. If this option is set to false, oversized inputs\n will lead to an INVALID_ARGUMENT error, similar to other text APIs.\n */\n autoTruncate?: boolean;\n}\n\n/** Parameters for the embed_content method. */\nexport declare interface EmbedContentParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The content to embed. Only the `parts.text` fields will be counted.\n */\n contents: ContentListUnion;\n /** Configuration that contains optional parameters.\n */\n config?: EmbedContentConfig;\n}\n\n/** Statistics of the input text associated with the result of content embedding. */\nexport declare interface ContentEmbeddingStatistics {\n /** Vertex API only. If the input text was truncated due to having\n a length longer than the allowed maximum input.\n */\n truncated?: boolean;\n /** Vertex API only. Number of tokens of the input text.\n */\n tokenCount?: number;\n}\n\n/** The embedding generated from an input content. */\nexport declare interface ContentEmbedding {\n /** A list of floats representing an embedding.\n */\n values?: number[];\n /** Vertex API only. Statistics of the input text associated with this\n embedding.\n */\n statistics?: ContentEmbeddingStatistics;\n}\n\n/** Request-level metadata for the Vertex Embed Content API. */\nexport declare interface EmbedContentMetadata {\n /** Vertex API only. The total number of billable characters included\n in the request.\n */\n billableCharacterCount?: number;\n}\n\n/** Response for the embed_content method. */\nexport class EmbedContentResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The embeddings for each request, in the same order as provided in\n the batch request.\n */\n embeddings?: ContentEmbedding[];\n /** Vertex API only. Metadata about the request.\n */\n metadata?: EmbedContentMetadata;\n}\n\n/** The config for generating an images. */\nexport declare interface GenerateImagesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** The size of the largest dimension of the generated image.\n Supported sizes are 1K and 2K (not supported for Imagen 3 models).\n */\n imageSize?: string;\n /** Whether to use the prompt rewriting logic.\n */\n enhancePrompt?: boolean;\n}\n\n/** The parameters for generating images. */\nexport declare interface GenerateImagesParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Text prompt that typically describes the images to output.\n */\n prompt: string;\n /** Configuration for generating images.\n */\n config?: GenerateImagesConfig;\n}\n\n/** An image. */\nexport declare interface Image {\n /** The Cloud Storage URI of the image. ``Image`` can contain a value\n for this field or the ``image_bytes`` field but not both.\n */\n gcsUri?: string;\n /** The image bytes data. ``Image`` can contain a value for this field\n or the ``gcs_uri`` field but not both.\n \n * @remarks Encoded as base64 string. */\n imageBytes?: string;\n /** The MIME type of the image. */\n mimeType?: string;\n}\n\n/** Safety attributes of a GeneratedImage or the user-provided prompt. */\nexport declare interface SafetyAttributes {\n /** List of RAI categories.\n */\n categories?: string[];\n /** List of scores of each categories.\n */\n scores?: number[];\n /** Internal use only.\n */\n contentType?: string;\n}\n\n/** An output image. */\nexport declare interface GeneratedImage {\n /** The output image data.\n */\n image?: Image;\n /** Responsible AI filter reason if the image is filtered out of the\n response.\n */\n raiFilteredReason?: string;\n /** Safety attributes of the image. Lists of RAI categories and their\n scores of each content.\n */\n safetyAttributes?: SafetyAttributes;\n /** The rewritten prompt used for the image generation if the prompt\n enhancer is enabled.\n */\n enhancedPrompt?: string;\n}\n\n/** The output images response. */\nexport class GenerateImagesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** List of generated images.\n */\n generatedImages?: GeneratedImage[];\n /** Safety attributes of the positive prompt. Only populated if\n ``include_safety_attributes`` is set to True.\n */\n positivePromptSafetyAttributes?: SafetyAttributes;\n}\n\n/** Configuration for a Mask reference image. */\nexport declare interface MaskReferenceConfig {\n /** Prompts the model to generate a mask instead of you needing to\n provide one (unless MASK_MODE_USER_PROVIDED is used). */\n maskMode?: MaskReferenceMode;\n /** A list of up to 5 class ids to use for semantic segmentation.\n Automatically creates an image mask based on specific objects. */\n segmentationClasses?: number[];\n /** Dilation percentage of the mask provided.\n Float between 0 and 1. */\n maskDilation?: number;\n}\n\n/** Configuration for a Control reference image. */\nexport declare interface ControlReferenceConfig {\n /** The type of control reference image to use. */\n controlType?: ControlReferenceType;\n /** Defaults to False. When set to True, the control image will be\n computed by the model based on the control type. When set to False,\n the control image must be provided by the user. */\n enableControlImageComputation?: boolean;\n}\n\n/** Configuration for a Style reference image. */\nexport declare interface StyleReferenceConfig {\n /** A text description of the style to use for the generated image. */\n styleDescription?: string;\n}\n\n/** Configuration for a Subject reference image. */\nexport declare interface SubjectReferenceConfig {\n /** The subject type of a subject reference image. */\n subjectType?: SubjectReferenceType;\n /** Subject description for the image. */\n subjectDescription?: string;\n}\n\n/** Configuration for editing an image. */\nexport declare interface EditImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage URI used to store the generated images.\n */\n outputGcsUri?: string;\n /** Description of what to discourage in the generated images.\n */\n negativePrompt?: string;\n /** Number of images to generate.\n */\n numberOfImages?: number;\n /** Aspect ratio of the generated images. Supported values are\n \"1:1\", \"3:4\", \"4:3\", \"9:16\", and \"16:9\".\n */\n aspectRatio?: string;\n /** Controls how much the model adheres to the text prompt. Large\n values increase output and prompt alignment, but may compromise image\n quality.\n */\n guidanceScale?: number;\n /** Random seed for image generation. This is not available when\n ``add_watermark`` is set to true.\n */\n seed?: number;\n /** Filter level for safety filtering.\n */\n safetyFilterLevel?: SafetyFilterLevel;\n /** Allows generation of people by the model.\n */\n personGeneration?: PersonGeneration;\n /** Whether to report the safety scores of each generated image and\n the positive prompt in the response.\n */\n includeSafetyAttributes?: boolean;\n /** Whether to include the Responsible AI filter reason if the image\n is filtered out of the response.\n */\n includeRaiReason?: boolean;\n /** Language of the text in the prompt.\n */\n language?: ImagePromptLanguage;\n /** MIME type of the generated image.\n */\n outputMimeType?: string;\n /** Compression quality of the generated image (for ``image/jpeg``\n only).\n */\n outputCompressionQuality?: number;\n /** Whether to add a watermark to the generated images.\n */\n addWatermark?: boolean;\n /** Describes the editing mode for the request. */\n editMode?: EditMode;\n /** The number of sampling steps. A higher value has better image\n quality, while a lower value has better latency. */\n baseSteps?: number;\n}\n\n/** Response for the request to edit an image. */\nexport class EditImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\nexport class UpscaleImageResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Generated images. */\n generatedImages?: GeneratedImage[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface GetModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\nexport declare interface GetModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: GetModelConfig;\n}\n\n/** An endpoint where you deploy models. */\nexport declare interface Endpoint {\n /** Resource name of the endpoint. */\n name?: string;\n /** ID of the model that's deployed to the endpoint. */\n deployedModelId?: string;\n}\n\n/** A tuned machine learning model. */\nexport declare interface TunedModelInfo {\n /** ID of the base model that you want to tune. */\n baseModel?: string;\n /** Date and time when the base model was created. */\n createTime?: string;\n /** Date and time when the base model was last updated. */\n updateTime?: string;\n}\n\n/** Describes the machine learning model version checkpoint. */\nexport declare interface Checkpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n}\n\n/** A trained machine learning model. */\nexport declare interface Model {\n /** Resource name of the model. */\n name?: string;\n /** Display name of the model. */\n displayName?: string;\n /** Description of the model. */\n description?: string;\n /** Version ID of the model. A new version is committed when a new\n model version is uploaded or trained under an existing model ID. The\n version ID is an auto-incrementing decimal number in string\n representation. */\n version?: string;\n /** List of deployed models created from this base model. Note that a\n model could have been deployed to endpoints in different locations. */\n endpoints?: Endpoint[];\n /** Labels with user-defined metadata to organize your models. */\n labels?: Record;\n /** Information about the tuned model from the base model. */\n tunedModelInfo?: TunedModelInfo;\n /** The maximum number of input tokens that the model can handle. */\n inputTokenLimit?: number;\n /** The maximum number of output tokens that the model can generate. */\n outputTokenLimit?: number;\n /** List of actions that are supported by the model. */\n supportedActions?: string[];\n /** The default checkpoint id of a model version.\n */\n defaultCheckpointId?: string;\n /** The checkpoints of the model. */\n checkpoints?: Checkpoint[];\n}\n\nexport declare interface ListModelsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n /** Set true to list base models, false to list tuned models. */\n queryBase?: boolean;\n}\n\nexport declare interface ListModelsParameters {\n config?: ListModelsConfig;\n}\n\nexport class ListModelsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n models?: Model[];\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n displayName?: string;\n description?: string;\n defaultCheckpointId?: string;\n}\n\n/** Configuration for updating a tuned model. */\nexport declare interface UpdateModelParameters {\n model: string;\n config?: UpdateModelConfig;\n}\n\n/** Configuration for deleting a tuned model. */\nexport declare interface DeleteModelConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for deleting a tuned model. */\nexport declare interface DeleteModelParameters {\n model: string;\n /** Optional parameters for the request. */\n config?: DeleteModelConfig;\n}\n\nexport class DeleteModelResponse {}\n\n/** Config for thinking features. */\nexport declare interface GenerationConfigThinkingConfig {\n /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */\n includeThoughts?: boolean;\n /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */\n thinkingBudget?: number;\n}\n\n/** Generation config. */\nexport declare interface GenerationConfig {\n /** Optional. Config for model selection. */\n modelSelectionConfig?: ModelSelectionConfig;\n /** Optional. If enabled, audio timestamp will be included in the request to the model. */\n audioTimestamp?: boolean;\n /** Optional. Number of candidates to generate. */\n candidateCount?: number;\n /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** Optional. Frequency penalties. */\n frequencyPenalty?: number;\n /** Optional. Logit probabilities. */\n logprobs?: number;\n /** Optional. The maximum number of output tokens to generate per message. */\n maxOutputTokens?: number;\n /** Optional. If specified, the media resolution specified will be used. */\n mediaResolution?: MediaResolution;\n /** Optional. Positive penalties. */\n presencePenalty?: number;\n /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */\n responseJsonSchema?: unknown;\n /** Optional. If true, export the logprobs results in response. */\n responseLogprobs?: boolean;\n /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */\n responseMimeType?: string;\n /** Optional. The modalities of the response. */\n responseModalities?: Modality[];\n /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */\n responseSchema?: Schema;\n /** Optional. Routing configuration. */\n routingConfig?: GenerationConfigRoutingConfig;\n /** Optional. Seed. */\n seed?: number;\n /** Optional. The speech generation config. */\n speechConfig?: SpeechConfig;\n /** Optional. Stop sequences. */\n stopSequences?: string[];\n /** Optional. Controls the randomness of predictions. */\n temperature?: number;\n /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */\n thinkingConfig?: GenerationConfigThinkingConfig;\n /** Optional. If specified, top-k sampling will be used. */\n topK?: number;\n /** Optional. If specified, nucleus sampling will be used. */\n topP?: number;\n}\n\n/** Config for the count_tokens method. */\nexport declare interface CountTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Instructions for the model to steer it toward better performance.\n */\n systemInstruction?: ContentUnion;\n /** Code that enables the system to interact with external systems to\n perform an action outside of the knowledge and scope of the model.\n */\n tools?: Tool[];\n /** Configuration that the model uses to generate the response. Not\n supported by the Gemini Developer API.\n */\n generationConfig?: GenerationConfig;\n}\n\n/** Parameters for counting tokens. */\nexport declare interface CountTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Configuration for counting tokens. */\n config?: CountTokensConfig;\n}\n\n/** Response for counting tokens. */\nexport class CountTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Total number of tokens. */\n totalTokens?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n}\n\n/** Optional parameters for computing tokens. */\nexport declare interface ComputeTokensConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for computing tokens. */\nexport declare interface ComputeTokensParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** Input content. */\n contents: ContentListUnion;\n /** Optional parameters for the request.\n */\n config?: ComputeTokensConfig;\n}\n\n/** Tokens info with a list of tokens and the corresponding list of token ids. */\nexport declare interface TokensInfo {\n /** Optional. Optional fields for the role from the corresponding Content. */\n role?: string;\n /** A list of token ids from the input. */\n tokenIds?: string[];\n /** A list of tokens from the input.\n * @remarks Encoded as base64 string. */\n tokens?: string[];\n}\n\n/** Response for computing tokens. */\nexport class ComputeTokensResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */\n tokensInfo?: TokensInfo[];\n}\n\n/** A generated video. */\nexport declare interface Video {\n /** Path to another storage. */\n uri?: string;\n /** Video bytes.\n * @remarks Encoded as base64 string. */\n videoBytes?: string;\n /** Video encoding, for example \"video/mp4\". */\n mimeType?: string;\n}\n\n/** Configuration for generating videos. */\nexport declare interface GenerateVideosConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Number of output videos. */\n numberOfVideos?: number;\n /** The gcs bucket where to save the generated videos. */\n outputGcsUri?: string;\n /** Frames per second for video generation. */\n fps?: number;\n /** Duration of the clip for video generation in seconds. */\n durationSeconds?: number;\n /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */\n seed?: number;\n /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */\n aspectRatio?: string;\n /** The resolution for the generated video. 720p and 1080p are supported. */\n resolution?: string;\n /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */\n personGeneration?: string;\n /** The pubsub topic where to publish the video generation progress. */\n pubsubTopic?: string;\n /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */\n negativePrompt?: string;\n /** Whether to use the prompt rewriting logic. */\n enhancePrompt?: boolean;\n /** Whether to generate audio along with the video. */\n generateAudio?: boolean;\n /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */\n lastFrame?: Image;\n /** Compression quality of the generated videos. */\n compressionQuality?: VideoCompressionQuality;\n}\n\n/** Class that represents the parameters for generating videos. */\nexport declare interface GenerateVideosParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** The text prompt for generating the videos. Optional for image to video use cases. */\n prompt?: string;\n /** The input image for generating the videos.\n Optional if prompt or video is provided. */\n image?: Image;\n /** The input video for video extension use cases.\n Optional if prompt or image is provided. */\n video?: Video;\n /** Configuration for generating videos. */\n config?: GenerateVideosConfig;\n}\n\n/** A generated video. */\nexport declare interface GeneratedVideo {\n /** The output video */\n video?: Video;\n}\n\n/** Response with generated videos. */\nexport class GenerateVideosResponse {\n /** List of the generated videos */\n generatedVideos?: GeneratedVideo[];\n /** Returns if any videos were filtered due to RAI policies. */\n raiMediaFilteredCount?: number;\n /** Returns rai failure reasons if any. */\n raiMediaFilteredReasons?: string[];\n}\n\n/** Optional parameters for tunings.get method. */\nexport declare interface GetTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the get method. */\nexport declare interface GetTuningJobParameters {\n name: string;\n /** Optional parameters for the request. */\n config?: GetTuningJobConfig;\n}\n\n/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */\nexport declare interface TunedModelCheckpoint {\n /** The ID of the checkpoint.\n */\n checkpointId?: string;\n /** The epoch of the checkpoint.\n */\n epoch?: string;\n /** The step of the checkpoint.\n */\n step?: string;\n /** The Endpoint resource name that the checkpoint is deployed to.\n Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`.\n */\n endpoint?: string;\n}\n\nexport declare interface TunedModel {\n /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */\n model?: string;\n /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */\n endpoint?: string;\n /** The checkpoints associated with this TunedModel.\n This field is only populated for tuning jobs that enable intermediate\n checkpoints. */\n checkpoints?: TunedModelCheckpoint[];\n}\n\n/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */\nexport declare interface GoogleRpcStatus {\n /** The status code, which should be an enum value of google.rpc.Code. */\n code?: number;\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */\n message?: string;\n}\n\n/** Hyperparameters for SFT. */\nexport declare interface SupervisedHyperParameters {\n /** Optional. Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Supervised Tuning for first party models. */\nexport declare interface SupervisedTuningSpec {\n /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */\n exportLastCheckpointOnly?: boolean;\n /** Optional. Hyperparameters for SFT. */\n hyperParameters?: SupervisedHyperParameters;\n /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n trainingDatasetUri?: string;\n /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */\n validationDatasetUri?: string;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface DatasetDistributionDistributionBucket {\n /** Output only. Number of values in the bucket. */\n count?: string;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Distribution computed over a tuning dataset. */\nexport declare interface DatasetDistribution {\n /** Output only. Defines the histogram bucket. */\n buckets?: DatasetDistributionDistributionBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: number;\n}\n\n/** Statistics computed over a tuning dataset. */\nexport declare interface DatasetStats {\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: DatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: DatasetDistribution;\n}\n\n/** Statistics computed for datasets used for distillation. */\nexport declare interface DistillationDataStats {\n /** Output only. Statistics computed for the training dataset. */\n trainingDatasetStats?: DatasetStats;\n}\n\n/** Dataset bucket used to create a histogram for the distribution given a population of values. */\nexport declare interface SupervisedTuningDatasetDistributionDatasetBucket {\n /** Output only. Number of values in the bucket. */\n count?: number;\n /** Output only. Left bound of the bucket. */\n left?: number;\n /** Output only. Right bound of the bucket. */\n right?: number;\n}\n\n/** Dataset distribution for Supervised Tuning. */\nexport declare interface SupervisedTuningDatasetDistribution {\n /** Output only. Sum of a given population of values that are billable. */\n billableSum?: string;\n /** Output only. Defines the histogram bucket. */\n buckets?: SupervisedTuningDatasetDistributionDatasetBucket[];\n /** Output only. The maximum of the population values. */\n max?: number;\n /** Output only. The arithmetic mean of the values in the population. */\n mean?: number;\n /** Output only. The median of the values in the population. */\n median?: number;\n /** Output only. The minimum of the population values. */\n min?: number;\n /** Output only. The 5th percentile of the values in the population. */\n p5?: number;\n /** Output only. The 95th percentile of the values in the population. */\n p95?: number;\n /** Output only. Sum of a given population of values. */\n sum?: string;\n}\n\n/** Tuning data statistics for Supervised Tuning. */\nexport declare interface SupervisedTuningDataStats {\n /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */\n droppedExampleReasons?: string[];\n /** Output only. Number of billable characters in the tuning dataset. */\n totalBillableCharacterCount?: string;\n /** Output only. Number of billable tokens in the tuning dataset. */\n totalBillableTokenCount?: string;\n /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */\n totalTruncatedExampleCount?: string;\n /** Output only. Number of tuning characters in the tuning dataset. */\n totalTuningCharacterCount?: string;\n /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */\n truncatedExampleIndices?: string[];\n /** Output only. Number of examples in the tuning dataset. */\n tuningDatasetExampleCount?: string;\n /** Output only. Number of tuning steps for this Tuning Job. */\n tuningStepCount?: string;\n /** Output only. Sample user messages in the training dataset uri. */\n userDatasetExamples?: Content[];\n /** Output only. Dataset distributions for the user input tokens. */\n userInputTokenDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the messages per example. */\n userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution;\n /** Output only. Dataset distributions for the user output tokens. */\n userOutputTokenDistribution?: SupervisedTuningDatasetDistribution;\n}\n\n/** The tuning data statistic values for TuningJob. */\nexport declare interface TuningDataStats {\n /** Output only. Statistics for distillation. */\n distillationDataStats?: DistillationDataStats;\n /** The SFT Tuning data stats. */\n supervisedTuningDataStats?: SupervisedTuningDataStats;\n}\n\n/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */\nexport declare interface EncryptionSpec {\n /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */\n kmsKeyName?: string;\n}\n\n/** Tuning spec for Partner models. */\nexport declare interface PartnerModelTuningSpec {\n /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */\n hyperParameters?: Record;\n /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** Hyperparameters for Distillation. */\nexport declare interface DistillationHyperParameters {\n /** Optional. Adapter size for distillation. */\n adapterSize?: AdapterSize;\n /** Optional. Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: string;\n /** Optional. Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n}\n\n/** Tuning Spec for Distillation. */\nexport declare interface DistillationSpec {\n /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseTeacherModel?: string;\n /** Optional. Hyperparameters for Distillation. */\n hyperParameters?: DistillationHyperParameters;\n /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */\n pipelineRootDirectory?: string;\n /** The student model that is being tuned, e.g., \"google/gemma-2b-1.1-it\". Deprecated. Use base_model instead. */\n studentModel?: string;\n /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDatasetUri?: string;\n /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */\n tunedTeacherModelSource?: string;\n /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDatasetUri?: string;\n}\n\n/** A tuning job. */\nexport declare interface TuningJob {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */\n name?: string;\n /** Output only. The detailed state of the job. */\n state?: JobState;\n /** Output only. Time when the TuningJob was created. */\n createTime?: string;\n /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */\n endTime?: string;\n /** Output only. Time when the TuningJob was most recently updated. */\n updateTime?: string;\n /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */\n error?: GoogleRpcStatus;\n /** Optional. The description of the TuningJob. */\n description?: string;\n /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */\n baseModel?: string;\n /** Output only. The tuned model resources associated with this TuningJob. */\n tunedModel?: TunedModel;\n /** Tuning Spec for Supervised Fine Tuning. */\n supervisedTuningSpec?: SupervisedTuningSpec;\n /** Output only. The tuning data statistics associated with this TuningJob. */\n tuningDataStats?: TuningDataStats;\n /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */\n encryptionSpec?: EncryptionSpec;\n /** Tuning Spec for open sourced and third party Partner models. */\n partnerModelTuningSpec?: PartnerModelTuningSpec;\n /** Tuning Spec for Distillation. */\n distillationSpec?: DistillationSpec;\n /** Output only. The Experiment associated with this TuningJob. */\n experiment?: string;\n /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */\n labels?: Record;\n /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */\n pipelineJob?: string;\n /** Output only. Reserved for future use. */\n satisfiesPzi?: boolean;\n /** Output only. Reserved for future use. */\n satisfiesPzs?: boolean;\n /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */\n serviceAccount?: string;\n /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n}\n\n/** Configuration for the list tuning jobs method. */\nexport declare interface ListTuningJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Parameters for the list tuning jobs method. */\nexport declare interface ListTuningJobsParameters {\n config?: ListTuningJobsConfig;\n}\n\n/** Response for the list tuning jobs method. */\nexport class ListTuningJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */\n nextPageToken?: string;\n /** List of TuningJobs in the requested page. */\n tuningJobs?: TuningJob[];\n}\n\nexport declare interface TuningExample {\n /** Text model input. */\n textInput?: string;\n /** The expected model output. */\n output?: string;\n}\n\n/** Supervised fine-tuning training dataset. */\nexport declare interface TuningDataset {\n /** GCS URI of the file containing training dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n /** Inline examples with simple input/output text. */\n examples?: TuningExample[];\n}\n\nexport declare interface TuningValidationDataset {\n /** GCS URI of the file containing validation dataset in JSONL format. */\n gcsUri?: string;\n /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */\n vertexDatasetResource?: string;\n}\n\n/** Supervised fine-tuning job creation request - optional fields. */\nexport declare interface CreateTuningJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n validationDataset?: TuningValidationDataset;\n /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */\n tunedModelDisplayName?: string;\n /** The description of the TuningJob */\n description?: string;\n /** Number of complete passes the model makes over the entire training dataset during training. */\n epochCount?: number;\n /** Multiplier for adjusting the default learning rate. */\n learningRateMultiplier?: number;\n /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */\n exportLastCheckpointOnly?: boolean;\n /** Adapter size for tuning. */\n adapterSize?: AdapterSize;\n /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */\n batchSize?: number;\n /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */\n learningRate?: number;\n}\n\n/** Supervised fine-tuning job creation parameters - optional fields. */\nexport declare interface CreateTuningJobParameters {\n /** The base model that is being tuned, e.g., \"gemini-1.0-pro-002\". */\n baseModel: string;\n /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */\n trainingDataset: TuningDataset;\n /** Configuration for the tuning job. */\n config?: CreateTuningJobConfig;\n}\n\n/** A long-running operation. */\nexport declare interface TuningOperation {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n}\n\n/** Optional configuration for cached content creation. */\nexport declare interface CreateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n /** The user-generated meaningful display name of the cached content.\n */\n displayName?: string;\n /** The content to cache.\n */\n contents?: ContentListUnion;\n /** Developer set system instruction.\n */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n */\n tools?: Tool[];\n /** Configuration for the tools to use. This config is shared for all tools.\n */\n toolConfig?: ToolConfig;\n /** The Cloud KMS resource identifier of the customer managed\n encryption key used to protect a resource.\n The key needs to be in the same region as where the compute resource is\n created. See\n https://cloud.google.com/vertex-ai/docs/general/cmek for more\n details. If this is set, then all created CachedContent objects\n will be encrypted with the provided encryption key.\n Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key}\n */\n kmsKeyName?: string;\n}\n\n/** Parameters for caches.create method. */\nexport declare interface CreateCachedContentParameters {\n /** ID of the model to use. Example: gemini-2.0-flash */\n model: string;\n /** Configuration that contains optional parameters.\n */\n config?: CreateCachedContentConfig;\n}\n\n/** Metadata on the usage of the cached content. */\nexport declare interface CachedContentUsageMetadata {\n /** Duration of audio in seconds. */\n audioDurationSeconds?: number;\n /** Number of images. */\n imageCount?: number;\n /** Number of text characters. */\n textCount?: number;\n /** Total number of tokens that the cached content consumes. */\n totalTokenCount?: number;\n /** Duration of video in seconds. */\n videoDurationSeconds?: number;\n}\n\n/** A resource used in LLM queries for users to explicitly specify what to cache. */\nexport declare interface CachedContent {\n /** The server-generated resource name of the cached content. */\n name?: string;\n /** The user-generated meaningful display name of the cached content. */\n displayName?: string;\n /** The name of the publisher model to use for cached content. */\n model?: string;\n /** Creation time of the cache entry. */\n createTime?: string;\n /** When the cache entry was last updated in UTC time. */\n updateTime?: string;\n /** Expiration time of the cached content. */\n expireTime?: string;\n /** Metadata on the usage of the cached content. */\n usageMetadata?: CachedContentUsageMetadata;\n}\n\n/** Optional parameters for caches.get method. */\nexport declare interface GetCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.get method. */\nexport declare interface GetCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: GetCachedContentConfig;\n}\n\n/** Optional parameters for caches.delete method. */\nexport declare interface DeleteCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for caches.delete method. */\nexport declare interface DeleteCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Optional parameters for the request.\n */\n config?: DeleteCachedContentConfig;\n}\n\n/** Empty response for caches.delete method. */\nexport class DeleteCachedContentResponse {}\n\n/** Optional parameters for caches.update method. */\nexport declare interface UpdateCachedContentConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: \"3.5s\". */\n ttl?: string;\n /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */\n expireTime?: string;\n}\n\nexport declare interface UpdateCachedContentParameters {\n /** The server-generated resource name of the cached content.\n */\n name: string;\n /** Configuration that contains optional parameters.\n */\n config?: UpdateCachedContentConfig;\n}\n\n/** Config for caches.list method. */\nexport declare interface ListCachedContentsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Parameters for caches.list method. */\nexport declare interface ListCachedContentsParameters {\n /** Configuration that contains optional parameters.\n */\n config?: ListCachedContentsConfig;\n}\n\nexport class ListCachedContentsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n /** List of cached contents.\n */\n cachedContents?: CachedContent[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface ListFilesConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n}\n\n/** Generates the parameters for the list method. */\nexport declare interface ListFilesParameters {\n /** Used to override the default configuration. */\n config?: ListFilesConfig;\n}\n\n/** Status of a File that uses a common error model. */\nexport declare interface FileStatus {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: Record[];\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n message?: string;\n /** The status code. 0 for OK, 1 for CANCELLED */\n code?: number;\n}\n\n/** A file uploaded to the API. */\nexport declare interface File {\n /** The `File` resource name. The ID (name excluding the \"files/\" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */\n name?: string;\n /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */\n displayName?: string;\n /** Output only. MIME type of the file. */\n mimeType?: string;\n /** Output only. Size of the file in bytes. */\n sizeBytes?: string;\n /** Output only. The timestamp of when the `File` was created. */\n createTime?: string;\n /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */\n expirationTime?: string;\n /** Output only. The timestamp of when the `File` was last updated. */\n updateTime?: string;\n /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */\n sha256Hash?: string;\n /** Output only. The URI of the `File`. */\n uri?: string;\n /** Output only. The URI of the `File`, only set for downloadable (generated) files. */\n downloadUri?: string;\n /** Output only. Processing state of the File. */\n state?: FileState;\n /** Output only. The source of the `File`. */\n source?: FileSource;\n /** Output only. Metadata for a video. */\n videoMetadata?: Record;\n /** Output only. Error status if File processing failed. */\n error?: FileStatus;\n}\n\n/** Response for the list files method. */\nexport class ListFilesResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n /** A token to retrieve next page of results. */\n nextPageToken?: string;\n /** The list of files. */\n files?: File[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface CreateFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the private _create method. */\nexport declare interface CreateFileParameters {\n /** The file to be uploaded.\n mime_type: (Required) The MIME type of the file. Must be provided.\n name: (Optional) The name of the file in the destination (e.g.\n 'files/sample-image').\n display_name: (Optional) The display name of the file.\n */\n file: File;\n /** Used to override the default configuration. */\n config?: CreateFileConfig;\n}\n\n/** Response for the create file method. */\nexport class CreateFileResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n}\n\n/** Used to override the default configuration. */\nexport declare interface GetFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface GetFileParameters {\n /** The name identifier for the file to retrieve. */\n name: string;\n /** Used to override the default configuration. */\n config?: GetFileConfig;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DeleteFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Generates the parameters for the get method. */\nexport declare interface DeleteFileParameters {\n /** The name identifier for the file to be deleted. */\n name: string;\n /** Used to override the default configuration. */\n config?: DeleteFileConfig;\n}\n\n/** Response for the delete file method. */\nexport class DeleteFileResponse {}\n\n/** Config for inlined request. */\nexport declare interface InlinedRequest {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model?: string;\n /** Content of the request.\n */\n contents?: ContentListUnion;\n /** Configuration that contains optional model parameters.\n */\n config?: GenerateContentConfig;\n}\n\n/** Config for `src` parameter. */\nexport declare interface BatchJobSource {\n /** Storage format of the input files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URIs to input files.\n */\n gcsUri?: string[];\n /** The BigQuery URI to input table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the input data\n (e.g. \"files/12345\").\n */\n fileName?: string;\n /** The Gemini Developer API's inlined input data to run batch job.\n */\n inlinedRequests?: InlinedRequest[];\n}\n\n/** Job error. */\nexport declare interface JobError {\n /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */\n details?: string[];\n /** The status code. */\n code?: number;\n /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */\n message?: string;\n}\n\n/** Config for `inlined_responses` parameter. */\nexport class InlinedResponse {\n /** The response to the request.\n */\n response?: GenerateContentResponse;\n /** The error encountered while processing the request.\n */\n error?: JobError;\n}\n\n/** Config for `des` parameter. */\nexport declare interface BatchJobDestination {\n /** Storage format of the output files. Must be one of:\n 'jsonl', 'bigquery'.\n */\n format?: string;\n /** The Google Cloud Storage URI to the output file.\n */\n gcsUri?: string;\n /** The BigQuery URI to the output table.\n */\n bigqueryUri?: string;\n /** The Gemini Developer API's file resource name of the output data\n (e.g. \"files/12345\"). The file will be a JSONL file with a single response\n per line. The responses will be GenerateContentResponse messages formatted\n as JSON. The responses will be written in the same order as the input\n requests.\n */\n fileName?: string;\n /** The responses to the requests in the batch. Returned when the batch was\n built using inlined requests. The responses will be in the same order as\n the input requests.\n */\n inlinedResponses?: InlinedResponse[];\n}\n\n/** Config for optional parameters. */\nexport declare interface CreateBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The user-defined name of this BatchJob.\n */\n displayName?: string;\n /** GCS or BigQuery URI prefix for the output predictions. Example:\n \"gs://path/to/output/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n dest?: BatchJobDestinationUnion;\n}\n\n/** Config for batches.create parameters. */\nexport declare interface CreateBatchJobParameters {\n /** The name of the model to produces the predictions via the BatchJob.\n */\n model?: string;\n /** GCS URI(-s) or BigQuery URI to your input data to run batch job.\n Example: \"gs://path/to/input/data\" or \"bq://projectId.bqDatasetId.bqTableId\".\n */\n src: BatchJobSourceUnion;\n /** Optional parameters for creating a BatchJob.\n */\n config?: CreateBatchJobConfig;\n}\n\n/** Config for batches.create return value. */\nexport declare interface BatchJob {\n /** The resource name of the BatchJob. Output only.\".\n */\n name?: string;\n /** The display name of the BatchJob.\n */\n displayName?: string;\n /** The state of the BatchJob.\n */\n state?: JobState;\n /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */\n error?: JobError;\n /** The time when the BatchJob was created.\n */\n createTime?: string;\n /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */\n startTime?: string;\n /** The time when the BatchJob was completed.\n */\n endTime?: string;\n /** The time when the BatchJob was last updated.\n */\n updateTime?: string;\n /** The name of the model that produces the predictions via the BatchJob.\n */\n model?: string;\n /** Configuration for the input data.\n */\n src?: BatchJobSource;\n /** Configuration for the output data.\n */\n dest?: BatchJobDestination;\n}\n\n/** Optional parameters. */\nexport declare interface GetBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.get parameters. */\nexport declare interface GetBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: GetBatchJobConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CancelBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.cancel parameters. */\nexport declare interface CancelBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: CancelBatchJobConfig;\n}\n\n/** Config for optional parameters. */\nexport declare interface ListBatchJobsConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n pageSize?: number;\n pageToken?: string;\n filter?: string;\n}\n\n/** Config for batches.list parameters. */\nexport declare interface ListBatchJobsParameters {\n config?: ListBatchJobsConfig;\n}\n\n/** Config for batches.list return value. */\nexport class ListBatchJobsResponse {\n /** Used to retain the full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n nextPageToken?: string;\n batchJobs?: BatchJob[];\n}\n\n/** Optional parameters for models.get method. */\nexport declare interface DeleteBatchJobConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Config for batches.delete parameters. */\nexport declare interface DeleteBatchJobParameters {\n /** A fully-qualified BatchJob resource name or ID.\n Example: \"projects/.../locations/.../batchPredictionJobs/456\"\n or \"456\" when project and location are initialized in the client.\n */\n name: string;\n /** Optional parameters for the request. */\n config?: DeleteBatchJobConfig;\n}\n\n/** The return value of delete operation. */\nexport declare interface DeleteResourceJob {\n name?: string;\n done?: boolean;\n error?: JobError;\n}\n\nexport declare interface GetOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the GET method. */\nexport declare interface GetOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\nexport declare interface FetchPredictOperationConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters for the fetchPredictOperation method. */\nexport declare interface FetchPredictOperationParameters {\n /** The server-assigned name for the operation. */\n operationName: string;\n resourceName: string;\n /** Used to override the default configuration. */\n config?: FetchPredictOperationConfig;\n}\n\nexport declare interface TestTableItem {\n /** The name of the test. This is used to derive the replay id. */\n name?: string;\n /** The parameters to the test. Use pydantic models. */\n parameters?: Record;\n /** Expects an exception for MLDev matching the string. */\n exceptionIfMldev?: string;\n /** Expects an exception for Vertex matching the string. */\n exceptionIfVertex?: string;\n /** Use if you don't want to use the default replay id which is derived from the test name. */\n overrideReplayId?: string;\n /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */\n hasUnion?: boolean;\n /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */\n skipInApiMode?: string;\n /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */\n ignoreKeys?: string[];\n}\n\nexport declare interface TestTableFile {\n comment?: string;\n testMethod?: string;\n parameterNames?: string[];\n testTable?: TestTableItem[];\n}\n\n/** Represents a single request in a replay. */\nexport declare interface ReplayRequest {\n method?: string;\n url?: string;\n headers?: Record;\n bodySegments?: Record[];\n}\n\n/** Represents a single response in a replay. */\nexport class ReplayResponse {\n statusCode?: number;\n headers?: Record;\n bodySegments?: Record[];\n sdkResponseSegments?: Record[];\n}\n\n/** Represents a single interaction, request and response in a replay. */\nexport declare interface ReplayInteraction {\n request?: ReplayRequest;\n response?: ReplayResponse;\n}\n\n/** Represents a recorded session. */\nexport declare interface ReplayFile {\n replayId?: string;\n interactions?: ReplayInteraction[];\n}\n\n/** Used to override the default configuration. */\nexport declare interface UploadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */\n name?: string;\n /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */\n mimeType?: string;\n /** Optional display name of the file. */\n displayName?: string;\n}\n\n/** Used to override the default configuration. */\nexport declare interface DownloadFileConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n}\n\n/** Parameters used to download a file. */\nexport declare interface DownloadFileParameters {\n /** The file to download. It can be a file name, a file object or a generated video. */\n file: DownloadableFileUnion;\n /** Location where the file should be downloaded to. */\n downloadPath: string;\n /** Configuration to for the download operation. */\n config?: DownloadFileConfig;\n}\n\n/** Configuration for upscaling an image.\n\n For more information on this configuration, refer to\n the `Imagen API reference documentation\n `_.\n */\nexport declare interface UpscaleImageConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** Whether to include a reason for filtered-out images in the\n response. */\n includeRaiReason?: boolean;\n /** The image format that the output should be saved as. */\n outputMimeType?: string;\n /** The level of compression if the ``output_mime_type`` is\n ``image/jpeg``. */\n outputCompressionQuality?: number;\n /** Whether to add an image enhancing step before upscaling.\n It is expected to suppress the noise and JPEG compression artifacts\n from the input image. */\n enhanceInputImage?: boolean;\n /** With a higher image preservation factor, the original image\n pixels are more respected. With a lower image preservation factor, the\n output image will have be more different from the input image, but\n with finer details and less noise. */\n imagePreservationFactor?: number;\n}\n\n/** User-facing config UpscaleImageParameters. */\nexport declare interface UpscaleImageParameters {\n /** The model to use. */\n model: string;\n /** The input image to upscale. */\n image: Image;\n /** The factor to upscale the image (x2 or x4). */\n upscaleFactor: string;\n /** Configuration for upscaling. */\n config?: UpscaleImageConfig;\n}\n\n/** A raw reference image.\n\n A raw reference image represents the base image to edit, provided by the user.\n It can optionally be provided in addition to a mask reference image or\n a style reference image.\n */\nexport class RawReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_RAW',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n };\n return referenceImageAPI;\n }\n}\n\n/** A mask reference image.\n\n This encapsulates either a mask image provided by the user and configs for\n the user provided mask, or only config parameters for the model to generate\n a mask.\n\n A mask image is an image whose non-zero values indicate where to edit the base\n image. If the user provides a mask image, the mask must be in the same\n dimensions as the raw image.\n */\nexport class MaskReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the mask reference image. */\n config?: MaskReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_MASK',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n maskImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A control reference image.\n\n The image of the control reference image is either a control image provided\n by the user, or a regular image which the backend will use to generate a\n control image of. In the case of the latter, the\n enable_control_image_computation field in the config should be set to True.\n\n A control image is an image that represents a sketch image of areas for the\n model to fill in based on the prompt.\n */\nexport class ControlReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the control reference image. */\n config?: ControlReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_CONTROL',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n controlImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A style reference image.\n\n This encapsulates a style reference image provided by the user, and\n additionally optional config parameters for the style reference image.\n\n A raw reference image can also be provided as a destination for the style to\n be applied to.\n */\nexport class StyleReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the style reference image. */\n config?: StyleReferenceConfig;\n /** Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_STYLE',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n styleImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\n/** A subject reference image.\n\n This encapsulates a subject reference image provided by the user, and\n additionally optional config parameters for the subject reference image.\n\n A raw reference image can also be provided as a destination for the subject to\n be applied to.\n */\nexport class SubjectReferenceImage {\n /** The reference image for the editing operation. */\n referenceImage?: Image;\n /** The id of the reference image. */\n referenceId?: number;\n /** The type of the reference image. Only set by the SDK. */\n referenceType?: string;\n /** Configuration for the subject reference image. */\n config?: SubjectReferenceConfig;\n /* Internal method to convert to ReferenceImageAPIInternal. */\n toReferenceImageAPI(): ReferenceImageAPIInternal {\n const referenceImageAPI = {\n referenceType: 'REFERENCE_TYPE_SUBJECT',\n referenceImage: this.referenceImage,\n referenceId: this.referenceId,\n subjectImageConfig: this.config,\n };\n return referenceImageAPI;\n }\n}\n\nexport /** Sent in response to a `LiveGenerateContentSetup` message from the client. */\ndeclare interface LiveServerSetupComplete {\n /** The session id of the live session. */\n sessionId?: string;\n}\n\n/** Audio transcription in Server Conent. */\nexport declare interface Transcription {\n /** Transcription text.\n */\n text?: string;\n /** The bool indicates the end of the transcription.\n */\n finished?: boolean;\n}\n\n/** Incremental server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time. Clients\n may choose to buffer and play it out in real time.\n */\nexport declare interface LiveServerContent {\n /** The content that the model has generated as part of the current conversation with the user. */\n modelTurn?: Content;\n /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */\n turnComplete?: boolean;\n /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */\n interrupted?: boolean;\n /** Metadata returned to client when grounding is enabled. */\n groundingMetadata?: GroundingMetadata;\n /** If true, indicates that the model is done generating. When model is\n interrupted while generating there will be no generation_complete message\n in interrupted turn, it will go through interrupted > turn_complete.\n When model assumes realtime playback there will be delay between\n generation_complete and turn_complete that is caused by model\n waiting for playback to finish. If true, indicates that the model\n has finished generating all content. This is a signal to the client\n that it can stop sending messages. */\n generationComplete?: boolean;\n /** Input transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn. */\n inputTranscription?: Transcription;\n /** Output transcription. The transcription is independent to the model\n turn which means it doesn’t imply any ordering between transcription and\n model turn.\n */\n outputTranscription?: Transcription;\n /** Metadata related to url context retrieval tool. */\n urlContextMetadata?: UrlContextMetadata;\n}\n\n/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\nexport declare interface LiveServerToolCall {\n /** The function call to be executed. */\n functionCalls?: FunctionCall[];\n}\n\n/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled.\n\n If there were side-effects to those tool calls, clients may attempt to undo\n the tool calls. This message occurs only in cases where the clients interrupt\n server turns.\n */\nexport declare interface LiveServerToolCallCancellation {\n /** The ids of the tool calls to be cancelled. */\n ids?: string[];\n}\n\n/** Usage metadata about response(s). */\nexport declare interface UsageMetadata {\n /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */\n promptTokenCount?: number;\n /** Number of tokens in the cached part of the prompt (the cached content). */\n cachedContentTokenCount?: number;\n /** Total number of tokens across all the generated response candidates. */\n responseTokenCount?: number;\n /** Number of tokens present in tool-use prompt(s). */\n toolUsePromptTokenCount?: number;\n /** Number of tokens of thoughts for thinking models. */\n thoughtsTokenCount?: number;\n /** Total token count for prompt, response candidates, and tool-use prompts(if present). */\n totalTokenCount?: number;\n /** List of modalities that were processed in the request input. */\n promptTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the cache input. */\n cacheTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were returned in the response. */\n responseTokensDetails?: ModalityTokenCount[];\n /** List of modalities that were processed in the tool-use prompt. */\n toolUsePromptTokensDetails?: ModalityTokenCount[];\n /** Traffic type. This shows whether a request consumes Pay-As-You-Go\n or Provisioned Throughput quota. */\n trafficType?: TrafficType;\n}\n\n/** Server will not be able to service client soon. */\nexport declare interface LiveServerGoAway {\n /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */\n timeLeft?: string;\n}\n\n/** Update of the session resumption state.\n\n Only sent if `session_resumption` was set in the connection config.\n */\nexport declare interface LiveServerSessionResumptionUpdate {\n /** New handle that represents state that can be resumed. Empty if `resumable`=false. */\n newHandle?: string;\n /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */\n resumable?: boolean;\n /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set.\n\nPresence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM).\n\nNote: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */\n lastConsumedClientMessageIndex?: string;\n}\n\n/** Response message for API call. */\nexport class LiveServerMessage {\n /** Sent in response to a `LiveClientSetup` message from the client. */\n setupComplete?: LiveServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveServerContent;\n /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */\n toolCall?: LiveServerToolCall;\n /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */\n toolCallCancellation?: LiveServerToolCallCancellation;\n /** Usage metadata about model response(s). */\n usageMetadata?: UsageMetadata;\n /** Server will disconnect soon. */\n goAway?: LiveServerGoAway;\n /** Update of the session resumption state. */\n sessionResumptionUpdate?: LiveServerSessionResumptionUpdate;\n /**\n * Returns the concatenation of all text parts from the server content if present.\n *\n * @remarks\n * If there are non-text parts in the response, the concatenation of all text\n * parts will be returned, and a warning will be logged.\n */\n get text(): string | undefined {\n let text = '';\n let anyTextPartFound = false;\n const nonTextParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (\n fieldName !== 'text' &&\n fieldName !== 'thought' &&\n fieldValue !== null\n ) {\n nonTextParts.push(fieldName);\n }\n }\n if (typeof part.text === 'string') {\n if (typeof part.thought === 'boolean' && part.thought) {\n continue;\n }\n anyTextPartFound = true;\n text += part.text;\n }\n }\n if (nonTextParts.length > 0) {\n console.warn(\n `there are non-text parts ${nonTextParts} in the response, returning concatenation of all text parts. Please refer to the non text parts for a full response from model.`,\n );\n }\n // part.text === '' is different from part.text is null\n return anyTextPartFound ? text : undefined;\n }\n\n /**\n * Returns the concatenation of all inline data parts from the server content if present.\n *\n * @remarks\n * If there are non-inline data parts in the\n * response, the concatenation of all inline data parts will be returned, and\n * a warning will be logged.\n */\n get data(): string | undefined {\n let data = '';\n const nonDataParts = [];\n for (const part of this.serverContent?.modelTurn?.parts ?? []) {\n for (const [fieldName, fieldValue] of Object.entries(part)) {\n if (fieldName !== 'inlineData' && fieldValue !== null) {\n nonDataParts.push(fieldName);\n }\n }\n if (part.inlineData && typeof part.inlineData.data === 'string') {\n data += atob(part.inlineData.data);\n }\n }\n if (nonDataParts.length > 0) {\n console.warn(\n `there are non-data parts ${nonDataParts} in the response, returning concatenation of all data parts. Please refer to the non data parts for a full response from model.`,\n );\n }\n return data.length > 0 ? btoa(data) : undefined;\n }\n}\n\n/** Parameters for the get method of the operations module. */\nexport declare interface OperationGetParameters> {\n /** The operation to be retrieved. */\n operation: U;\n /** Used to override the default configuration. */\n config?: GetOperationConfig;\n}\n\n/** Parameters of the fromAPIResponse method of the Operation class. */\nexport declare interface OperationFromAPIResponseParameters {\n /** The API response to be converted to an Operation. */\n apiResponse: Record;\n /** Whether the API response is from Vertex AI. */\n isVertexAI: boolean;\n}\n\n/** A long-running operation. */\nexport declare interface Operation {\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: T;\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation;\n}\n\n/** A video generation long-running operation. */\nexport class GenerateVideosOperation\n implements Operation\n{\n /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */\n name?: string;\n /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */\n metadata?: Record;\n /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */\n done?: boolean;\n /** The error result of the operation in case of failure or cancellation. */\n error?: Record;\n /** The response if the operation is successful. */\n response?: GenerateVideosResponse;\n /** The full HTTP response. */\n sdkHttpResponse?: HttpResponse;\n\n /**\n * Instantiates an Operation of the same type as the one being called with the fields set from the API response.\n * @internal\n */\n _fromAPIResponse({\n apiResponse,\n isVertexAI,\n }: OperationFromAPIResponseParameters): Operation {\n const operation = new GenerateVideosOperation();\n operation.name = apiResponse['name'] as string | undefined;\n operation.metadata = apiResponse['metadata'] as\n | Record\n | undefined;\n operation.done = apiResponse['done'] as boolean | undefined;\n operation.error = apiResponse['error'] as\n | Record\n | undefined;\n\n if (isVertexAI) {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const responseVideos = response['videos'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n return {\n video: {\n uri: generatedVideo['gcsUri'] as string | undefined,\n videoBytes: generatedVideo['bytesBase64Encoded']\n ? tBytes(generatedVideo['bytesBase64Encoded'] as string)\n : undefined,\n mimeType: generatedVideo['mimeType'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n } else {\n const response = apiResponse['response'] as\n | Record\n | undefined;\n if (response) {\n const operationResponse = new GenerateVideosResponse();\n const generatedVideoResponse = response['generateVideoResponse'] as\n | Record\n | undefined;\n const responseVideos = generatedVideoResponse?.['generatedSamples'] as\n | Array>\n | undefined;\n operationResponse.generatedVideos = responseVideos?.map(\n (generatedVideo) => {\n const video = generatedVideo['video'] as\n | Record\n | undefined;\n return {\n video: {\n uri: video?.['uri'] as string | undefined,\n videoBytes: video?.['encodedVideo']\n ? tBytes(video?.['encodedVideo'] as string)\n : undefined,\n mimeType: generatedVideo['encoding'] as string | undefined,\n } as Video,\n } as GeneratedVideo;\n },\n );\n operationResponse.raiMediaFilteredCount = response[\n 'raiMediaFilteredCount'\n ] as number | undefined;\n operationResponse.raiMediaFilteredReasons = response[\n 'raiMediaFilteredReasons'\n ] as string[] | undefined;\n operation.response = operationResponse;\n }\n }\n return operation;\n }\n}\n\n/** Configures automatic detection of activity. */\nexport declare interface AutomaticActivityDetection {\n /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */\n disabled?: boolean;\n /** Determines how likely speech is to be detected. */\n startOfSpeechSensitivity?: StartSensitivity;\n /** Determines how likely detected speech is ended. */\n endOfSpeechSensitivity?: EndSensitivity;\n /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */\n prefixPaddingMs?: number;\n /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */\n silenceDurationMs?: number;\n}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface RealtimeInputConfig {\n /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */\n automaticActivityDetection?: AutomaticActivityDetection;\n /** Defines what effect activity has. */\n activityHandling?: ActivityHandling;\n /** Defines which input is included in the user's turn. */\n turnCoverage?: TurnCoverage;\n}\n\n/** Configuration of session resumption mechanism.\n\n Included in `LiveConnectConfig.session_resumption`. If included server\n will send `LiveServerSessionResumptionUpdate` messages.\n */\nexport declare interface SessionResumptionConfig {\n /** Session resumption handle of previous session (session to restore).\n\nIf not present new session will be started. */\n handle?: string;\n /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */\n transparent?: boolean;\n}\n\n/** Context window will be truncated by keeping only suffix of it.\n\n Context window will always be cut at start of USER role turn. System\n instructions and `BidiGenerateContentSetup.prefix_turns` will not be\n subject to the sliding window mechanism, they will always stay at the\n beginning of context window.\n */\nexport declare interface SlidingWindow {\n /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */\n targetTokens?: string;\n}\n\n/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */\nexport declare interface ContextWindowCompressionConfig {\n /** Number of tokens (before running turn) that triggers context window compression mechanism. */\n triggerTokens?: string;\n /** Sliding window compression mechanism. */\n slidingWindow?: SlidingWindow;\n}\n\n/** The audio transcription configuration in Setup. */\nexport declare interface AudioTranscriptionConfig {}\n\n/** Config for proactivity features. */\nexport declare interface ProactivityConfig {\n /** If enabled, the model can reject responding to the last prompt. For\n example, this allows the model to ignore out of context speech or to stay\n silent if the user did not make a request, yet. */\n proactiveAudio?: boolean;\n}\n\n/** Message contains configuration that will apply for the duration of the streaming session. */\nexport declare interface LiveClientSetup {\n /** \n The fully qualified name of the publisher model or tuned model endpoint to\n use.\n */\n model?: string;\n /** The generation configuration for the session.\n Note: only a subset of fields are supported.\n */\n generationConfig?: GenerationConfig;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures session resumption mechanism.\n\n If included server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Incremental update of the current conversation delivered from the client.\n\n All the content here will unconditionally be appended to the conversation\n history and used as part of the prompt to the model to generate content.\n\n A message here will interrupt any current model generation.\n */\nexport declare interface LiveClientContent {\n /** The content appended to the current conversation with the model.\n\n For single-turn queries, this is a single instance. For multi-turn\n queries, this is a repeated field that contains conversation history and\n latest request.\n */\n turns?: Content[];\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Marks the start of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityStart {}\n\n/** Marks the end of user activity.\n\n This can only be sent if automatic (i.e. server-side) activity detection is\n disabled.\n */\nexport declare interface ActivityEnd {}\n\n/** User input that is sent in real time.\n\n This is different from `LiveClientContent` in a few ways:\n\n - Can be sent continuously without interruption to model generation.\n - If there is a need to mix data interleaved across the\n `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to\n optimize for best response, but there are no guarantees.\n - End of turn is not explicitly specified, but is rather derived from user\n activity (for example, end of speech).\n - Even before the end of turn, the data is processed incrementally\n to optimize for a fast start of the response from the model.\n - Is always assumed to be the user's input (cannot be used to populate\n conversation history).\n */\nexport declare interface LiveClientRealtimeInput {\n /** Inlined bytes data for media input. */\n mediaChunks?: Blob[];\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: Blob;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Parameters for sending realtime input to the live API. */\nexport declare interface LiveSendRealtimeInputParameters {\n /** Realtime input to send to the session. */\n media?: BlobImageUnion;\n /** The realtime audio input stream. */\n audio?: Blob;\n /** \nIndicates that the audio stream has ended, e.g. because the microphone was\nturned off.\n\nThis should only be sent when automatic activity detection is enabled\n(which is the default).\n\nThe client can reopen the stream by sending an audio message.\n */\n audioStreamEnd?: boolean;\n /** The realtime video input stream. */\n video?: BlobImageUnion;\n /** The realtime text input stream. */\n text?: string;\n /** Marks the start of user activity. */\n activityStart?: ActivityStart;\n /** Marks the end of user activity. */\n activityEnd?: ActivityEnd;\n}\n\n/** Client generated response to a `ToolCall` received from the server.\n\n Individual `FunctionResponse` objects are matched to the respective\n `FunctionCall` objects by the `id` field.\n\n Note that in the unary and server-streaming GenerateContent APIs function\n calling happens by exchanging the `Content` parts, while in the bidi\n GenerateContent APIs function calling happens over this dedicated set of\n messages.\n */\nexport class LiveClientToolResponse {\n /** The response to the function calls. */\n functionResponses?: FunctionResponse[];\n}\n\n/** Messages sent by the client in the API call. */\nexport declare interface LiveClientMessage {\n /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */\n setup?: LiveClientSetup;\n /** Incremental update of the current conversation delivered from the client. */\n clientContent?: LiveClientContent;\n /** User input that is sent in real time. */\n realtimeInput?: LiveClientRealtimeInput;\n /** Response to a `ToolCallMessage` received from the server. */\n toolResponse?: LiveClientToolResponse;\n}\n\n/** Session config for the API connection. */\nexport declare interface LiveConnectConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** The generation configuration for the session. */\n generationConfig?: GenerationConfig;\n /** The requested modalities of the response. Represents the set of\n modalities that the model can return. Defaults to AUDIO if not specified.\n */\n responseModalities?: Modality[];\n /** Value that controls the degree of randomness in token selection.\n Lower temperatures are good for prompts that require a less open-ended or\n creative response, while higher temperatures can lead to more diverse or\n creative results.\n */\n temperature?: number;\n /** Tokens are selected from the most to least probable until the sum\n of their probabilities equals this value. Use a lower value for less\n random responses and a higher value for more random responses.\n */\n topP?: number;\n /** For each token selection step, the ``top_k`` tokens with the\n highest probabilities are sampled. Then tokens are further filtered based\n on ``top_p`` with the final token selected using temperature sampling. Use\n a lower number for less random responses and a higher number for more\n random responses.\n */\n topK?: number;\n /** Maximum number of tokens that can be generated in the response.\n */\n maxOutputTokens?: number;\n /** If specified, the media resolution specified will be used.\n */\n mediaResolution?: MediaResolution;\n /** When ``seed`` is fixed to a specific number, the model makes a best\n effort to provide the same response for repeated requests. By default, a\n random number is used.\n */\n seed?: number;\n /** The speech generation configuration.\n */\n speechConfig?: SpeechConfig;\n /** If enabled, the model will detect emotions and adapt its responses accordingly. */\n enableAffectiveDialog?: boolean;\n /** The user provided system instructions for the model.\n Note: only text should be used in parts and content in each part will be\n in a separate paragraph. */\n systemInstruction?: ContentUnion;\n /** A list of `Tools` the model may use to generate the next response.\n\n A `Tool` is a piece of code that enables the system to interact with\n external systems to perform an action, or set of actions, outside of\n knowledge and scope of the model. */\n tools?: ToolListUnion;\n /** Configures session resumption mechanism.\n\nIf included the server will send SessionResumptionUpdate messages. */\n sessionResumption?: SessionResumptionConfig;\n /** The transcription of the input aligns with the input audio language.\n */\n inputAudioTranscription?: AudioTranscriptionConfig;\n /** The transcription of the output aligns with the language code\n specified for the output audio.\n */\n outputAudioTranscription?: AudioTranscriptionConfig;\n /** Configures the realtime input behavior in BidiGenerateContent. */\n realtimeInputConfig?: RealtimeInputConfig;\n /** Configures context window compression mechanism.\n\n If included, server will compress context window to fit into given length. */\n contextWindowCompression?: ContextWindowCompressionConfig;\n /** Configures the proactivity of the model. This allows the model to respond proactively to\n the input and to ignore irrelevant input. */\n proactivity?: ProactivityConfig;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveConnectParameters {\n /** ID of the model to use. For a list of models, see `Google models\n `_. */\n model: string;\n /** callbacks */\n callbacks: LiveCallbacks;\n /** Optional configuration parameters for the request.\n */\n config?: LiveConnectConfig;\n}\n\n/** Parameters for initializing a new chat session.\n\n These parameters are used when creating a chat session with the\n `chats.create()` method.\n */\nexport declare interface CreateChatParameters {\n /** The name of the model to use for the chat session.\n\n For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API\n docs to find the available models.\n */\n model: string;\n /** Config for the entire chat session.\n\n This config applies to all requests within the session\n unless overridden by a per-request `config` in `SendMessageParameters`.\n */\n config?: GenerateContentConfig;\n /** The initial conversation history for the chat session.\n\n This allows you to start the chat with a pre-existing history. The history\n must be a list of `Content` alternating between 'user' and 'model' roles.\n It should start with a 'user' message.\n */\n history?: Content[];\n}\n\n/** Parameters for sending a message within a chat session.\n\n These parameters are used with the `chat.sendMessage()` method.\n */\nexport declare interface SendMessageParameters {\n /** The message to send to the model.\n\n The SDK will combine all parts into a single 'user' content to send to\n the model.\n */\n message: PartListUnion;\n /** Config for this specific request.\n\n Please note that the per-request config does not change the chat level\n config, nor inherit from it. If you intend to use some values from the\n chat's default config, you must explicitly copy them into this per-request\n config.\n */\n config?: GenerateContentConfig;\n}\n\n/** Parameters for sending client content to the live API. */\nexport declare interface LiveSendClientContentParameters {\n /** Client content to send to the session. */\n turns?: ContentListUnion;\n /** If true, indicates that the server content generation should start with\n the currently accumulated prompt. Otherwise, the server will await\n additional messages before starting generation. */\n turnComplete?: boolean;\n}\n\n/** Parameters for sending tool responses to the live API. */\nexport class LiveSendToolResponseParameters {\n /** Tool responses to send to the session. */\n functionResponses: FunctionResponse[] | FunctionResponse = [];\n}\n\n/** Message to be sent by the system when connecting to the API. */\nexport declare interface LiveMusicClientSetup {\n /** The model's resource name. Format: `models/{model}`. */\n model?: string;\n}\n\n/** Maps a prompt to a relative weight to steer music generation. */\nexport declare interface WeightedPrompt {\n /** Text prompt. */\n text?: string;\n /** Weight of the prompt. The weight is used to control the relative\n importance of the prompt. Higher weights are more important than lower\n weights.\n\n Weight must not be 0. Weights of all weighted_prompts in this\n LiveMusicClientContent message will be normalized. */\n weight?: number;\n}\n\n/** User input to start or steer the music. */\nexport declare interface LiveMusicClientContent {\n /** Weighted prompts as the model input. */\n weightedPrompts?: WeightedPrompt[];\n}\n\n/** Configuration for music generation. */\nexport declare interface LiveMusicGenerationConfig {\n /** Controls the variance in audio generation. Higher values produce\n higher variance. Range is [0.0, 3.0]. */\n temperature?: number;\n /** Controls how the model selects tokens for output. Samples the topK\n tokens with the highest probabilities. Range is [1, 1000]. */\n topK?: number;\n /** Seeds audio generation. If not set, the request uses a randomly\n generated seed. */\n seed?: number;\n /** Controls how closely the model follows prompts.\n Higher guidance follows more closely, but will make transitions more\n abrupt. Range is [0.0, 6.0]. */\n guidance?: number;\n /** Beats per minute. Range is [60, 200]. */\n bpm?: number;\n /** Density of sounds. Range is [0.0, 1.0]. */\n density?: number;\n /** Brightness of the music. Range is [0.0, 1.0]. */\n brightness?: number;\n /** Scale of the generated music. */\n scale?: Scale;\n /** Whether the audio output should contain bass. */\n muteBass?: boolean;\n /** Whether the audio output should contain drums. */\n muteDrums?: boolean;\n /** Whether the audio output should contain only bass and drums. */\n onlyBassAndDrums?: boolean;\n}\n\n/** Messages sent by the client in the LiveMusicClientMessage call. */\nexport declare interface LiveMusicClientMessage {\n /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`.\n Clients should wait for a `LiveMusicSetupComplete` message before\n sending any additional messages. */\n setup?: LiveMusicClientSetup;\n /** User input to influence music generation. */\n clientContent?: LiveMusicClientContent;\n /** Configuration for music generation. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n /** Playback control signal for the music generation. */\n playbackControl?: LiveMusicPlaybackControl;\n}\n\n/** Sent in response to a `LiveMusicClientSetup` message from the client. */\nexport declare interface LiveMusicServerSetupComplete {}\n\n/** Prompts and config used for generating this audio chunk. */\nexport declare interface LiveMusicSourceMetadata {\n /** Weighted prompts for generating this audio chunk. */\n clientContent?: LiveMusicClientContent;\n /** Music generation config for generating this audio chunk. */\n musicGenerationConfig?: LiveMusicGenerationConfig;\n}\n\n/** Representation of an audio chunk. */\nexport declare interface AudioChunk {\n /** Raw bytes of audio data.\n * @remarks Encoded as base64 string. */\n data?: string;\n /** MIME type of the audio chunk. */\n mimeType?: string;\n /** Prompts and config used for generating this audio chunk. */\n sourceMetadata?: LiveMusicSourceMetadata;\n}\n\n/** Server update generated by the model in response to client messages.\n\n Content is generated as quickly as possible, and not in real time.\n Clients may choose to buffer and play it out in real time.\n */\nexport declare interface LiveMusicServerContent {\n /** The audio chunks that the model has generated. */\n audioChunks?: AudioChunk[];\n}\n\n/** A prompt that was filtered with the reason. */\nexport declare interface LiveMusicFilteredPrompt {\n /** The text prompt that was filtered. */\n text?: string;\n /** The reason the prompt was filtered. */\n filteredReason?: string;\n}\n\n/** Response message for the LiveMusicClientMessage call. */\nexport class LiveMusicServerMessage {\n /** Message sent in response to a `LiveMusicClientSetup` message from the client.\n Clients should wait for this message before sending any additional messages. */\n setupComplete?: LiveMusicServerSetupComplete;\n /** Content generated by the model in response to client messages. */\n serverContent?: LiveMusicServerContent;\n /** A prompt that was filtered with the reason. */\n filteredPrompt?: LiveMusicFilteredPrompt;\n /**\n * Returns the first audio chunk from the server content, if present.\n *\n * @remarks\n * If there are no audio chunks in the response, undefined will be returned.\n */\n get audioChunk(): AudioChunk | undefined {\n if (\n this.serverContent &&\n this.serverContent.audioChunks &&\n this.serverContent.audioChunks.length > 0\n ) {\n return this.serverContent.audioChunks[0];\n }\n return undefined;\n }\n}\n\n/** Callbacks for the realtime music API. */\nexport interface LiveMusicCallbacks {\n /**\n * Called when a message is received from the server.\n */\n onmessage: (e: LiveMusicServerMessage) => void;\n /**\n * Called when an error occurs.\n */\n onerror?: ((e: ErrorEvent) => void) | null;\n /**\n * Called when the websocket connection is closed.\n */\n onclose?: ((e: CloseEvent) => void) | null;\n}\n\n/** Parameters for the upload file method. */\nexport interface UploadFileParameters {\n /** The string path to the file to be uploaded or a Blob object. */\n file: string | globalThis.Blob;\n /** Configuration that contains optional parameters. */\n config?: UploadFileConfig;\n}\n\n/**\n * CallableTool is an invokable tool that can be executed with external\n * application (e.g., via Model Context Protocol) or local functions with\n * function calling.\n */\nexport interface CallableTool {\n /**\n * Returns tool that can be called by Gemini.\n */\n tool(): Promise;\n /**\n * Executes the callable tool with the given function call arguments and\n * returns the response parts from the tool execution.\n */\n callTool(functionCalls: FunctionCall[]): Promise;\n}\n\n/**\n * CallableToolConfig is the configuration for a callable tool.\n */\nexport interface CallableToolConfig {\n /**\n * Specifies the model's behavior after invoking this tool.\n */\n behavior?: Behavior;\n /**\n * Timeout for remote calls in milliseconds. Note this timeout applies only to\n * tool remote calls, and not making HTTP requests to the API. */\n timeout?: number;\n}\n\n/** Parameters for connecting to the live API. */\nexport declare interface LiveMusicConnectParameters {\n /** The model's resource name. */\n model: string;\n /** Callbacks invoked on server events. */\n callbacks: LiveMusicCallbacks;\n}\n\n/** Parameters for setting config for the live music API. */\nexport declare interface LiveMusicSetConfigParameters {\n /** Configuration for music generation. */\n musicGenerationConfig: LiveMusicGenerationConfig;\n}\n\n/** Parameters for setting weighted prompts for the live music API. */\nexport declare interface LiveMusicSetWeightedPromptsParameters {\n /** A map of text prompts to weights to use for the generation request. */\n weightedPrompts: WeightedPrompt[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface AuthToken {\n /** The name of the auth token. */\n name?: string;\n}\n\n/** Config for LiveConnectConstraints for Auth Token creation. */\nexport declare interface LiveConnectConstraints {\n /** ID of the model to configure in the ephemeral token for Live API.\n For a list of models, see `Gemini models\n `. */\n model?: string;\n /** Configuration specific to Live API connections created using this token. */\n config?: LiveConnectConfig;\n}\n\n/** Optional parameters. */\nexport declare interface CreateAuthTokenConfig {\n /** Used to override HTTP request options. */\n httpOptions?: HttpOptions;\n /** Abort signal which can be used to cancel the request.\n\n NOTE: AbortSignal is a client-only operation. Using it to cancel an\n operation will not cancel the request in the service. You will still\n be charged usage for any applicable operations.\n */\n abortSignal?: AbortSignal;\n /** An optional time after which, when using the resulting token,\n messages in Live API sessions will be rejected. (Gemini may\n preemptively close the session after this time.)\n\n If not set then this defaults to 30 minutes in the future. If set, this\n value must be less than 20 hours in the future. */\n expireTime?: string;\n /** The time after which new Live API sessions using the token\n resulting from this request will be rejected.\n\n If not set this defaults to 60 seconds in the future. If set, this value\n must be less than 20 hours in the future. */\n newSessionExpireTime?: string;\n /** The number of times the token can be used. If this value is zero\n then no limit is applied. Default is 1. Resuming a Live API session does\n not count as a use. */\n uses?: number;\n /** Configuration specific to Live API connections created using this token. */\n liveConnectConstraints?: LiveConnectConstraints;\n /** Additional fields to lock in the effective LiveConnectParameters. */\n lockAdditionalFields?: string[];\n}\n\n/** Config for auth_tokens.create parameters. */\nexport declare interface CreateAuthTokenParameters {\n /** Optional parameters for the request. */\n config?: CreateAuthTokenConfig;\n}\n\nexport type BlobImageUnion = Blob;\n\nexport type PartUnion = Part | string;\n\nexport type PartListUnion = PartUnion[] | PartUnion;\n\nexport type ContentUnion = Content | PartUnion[] | PartUnion;\n\nexport type ContentListUnion = Content | Content[] | PartUnion | PartUnion[];\n\nexport type SchemaUnion = Schema | unknown;\n\nexport type SpeechConfigUnion = SpeechConfig | string;\n\nexport type ToolUnion = Tool | CallableTool;\n\nexport type ToolListUnion = ToolUnion[];\n\nexport type DownloadableFileUnion = string | File | GeneratedVideo | Video;\n\nexport type BatchJobSourceUnion = BatchJobSource | InlinedRequest[] | string;\n\nexport type BatchJobDestinationUnion = BatchJobDestination | string;\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {ApiClient} from './_api_client.js';\nimport * as baseTransformers from './_base_transformers.js';\nimport * as types from './types.js';\n\nexport function tModel(apiClient: ApiClient, model: string | unknown): string {\n if (!model || typeof model !== 'string') {\n throw new Error('model is required and must be a string');\n }\n\n if (apiClient.isVertexAI()) {\n if (\n model.startsWith('publishers/') ||\n model.startsWith('projects/') ||\n model.startsWith('models/')\n ) {\n return model;\n } else if (model.indexOf('/') >= 0) {\n const parts = model.split('/', 2);\n return `publishers/${parts[0]}/models/${parts[1]}`;\n } else {\n return `publishers/google/models/${model}`;\n }\n } else {\n if (model.startsWith('models/') || model.startsWith('tunedModels/')) {\n return model;\n } else {\n return `models/${model}`;\n }\n }\n}\n\nexport function tCachesModel(\n apiClient: ApiClient,\n model: string | unknown,\n): string {\n const transformedModel = tModel(apiClient, model as string);\n if (!transformedModel) {\n return '';\n }\n\n if (transformedModel.startsWith('publishers/') && apiClient.isVertexAI()) {\n // vertex caches only support model name start with projects.\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/${transformedModel}`;\n } else if (transformedModel.startsWith('models/') && apiClient.isVertexAI()) {\n return `projects/${apiClient.getProject()}/locations/${apiClient.getLocation()}/publishers/google/${transformedModel}`;\n } else {\n return transformedModel;\n }\n}\n\nexport function tBlobs(\n blobs: types.BlobImageUnion | types.BlobImageUnion[],\n): types.Blob[] {\n if (Array.isArray(blobs)) {\n return blobs.map((blob) => tBlob(blob));\n } else {\n return [tBlob(blobs)];\n }\n}\n\nexport function tBlob(blob: types.BlobImageUnion): types.Blob {\n if (typeof blob === 'object' && blob !== null) {\n return blob;\n }\n\n throw new Error(\n `Could not parse input as Blob. Unsupported blob type: ${typeof blob}`,\n );\n}\n\nexport function tImageBlob(blob: types.BlobImageUnion): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('image/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tAudioBlob(blob: types.Blob): types.Blob {\n const transformedBlob = tBlob(blob);\n if (\n transformedBlob.mimeType &&\n transformedBlob.mimeType.startsWith('audio/')\n ) {\n return transformedBlob;\n }\n throw new Error(`Unsupported mime type: ${transformedBlob.mimeType!}`);\n}\n\nexport function tPart(origin?: types.PartUnion | null): types.Part {\n if (origin === null || origin === undefined) {\n throw new Error('PartUnion is required');\n }\n if (typeof origin === 'object') {\n return origin;\n }\n if (typeof origin === 'string') {\n return {text: origin};\n }\n throw new Error(`Unsupported part type: ${typeof origin}`);\n}\n\nexport function tParts(origin?: types.PartListUnion | null): types.Part[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('PartListUnion is required');\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tPart(item as types.PartUnion)!);\n }\n return [tPart(origin)!];\n}\n\nfunction _isContent(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'parts' in origin &&\n Array.isArray(origin.parts)\n );\n}\n\nfunction _isFunctionCallPart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionCall' in origin\n );\n}\n\nfunction _isFunctionResponsePart(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'functionResponse' in origin\n );\n}\n\nexport function tContent(origin?: types.ContentUnion): types.Content {\n if (origin === null || origin === undefined) {\n throw new Error('ContentUnion is required');\n }\n if (_isContent(origin)) {\n // _isContent is a utility function that checks if the\n // origin is a Content.\n return origin as types.Content;\n }\n\n return {\n role: 'user',\n parts: tParts(origin as types.PartListUnion)!,\n };\n}\n\nexport function tContentsForEmbed(\n apiClient: ApiClient,\n origin: types.ContentListUnion,\n): types.ContentUnion[] {\n if (!origin) {\n return [];\n }\n if (apiClient.isVertexAI() && Array.isArray(origin)) {\n return origin.flatMap((item) => {\n const content = tContent(item as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n });\n } else if (apiClient.isVertexAI()) {\n const content = tContent(origin as types.ContentUnion);\n if (\n content.parts &&\n content.parts.length > 0 &&\n content.parts[0].text !== undefined\n ) {\n return [content.parts[0].text];\n }\n return [];\n }\n if (Array.isArray(origin)) {\n return origin.map((item) => tContent(item as types.ContentUnion)!);\n }\n return [tContent(origin as types.ContentUnion)!];\n}\n\nexport function tContents(origin?: types.ContentListUnion): types.Content[] {\n if (\n origin === null ||\n origin === undefined ||\n (Array.isArray(origin) && origin.length === 0)\n ) {\n throw new Error('contents are required');\n }\n if (!Array.isArray(origin)) {\n // If it's not an array, it's a single content or a single PartUnion.\n if (_isFunctionCallPart(origin) || _isFunctionResponsePart(origin)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them in a Content object, specifying the role for them',\n );\n }\n return [tContent(origin as types.ContentUnion)];\n }\n\n const result: types.Content[] = [];\n const accumulatedParts: types.PartUnion[] = [];\n const isContentArray = _isContent(origin[0]);\n\n for (const item of origin) {\n const isContent = _isContent(item);\n\n if (isContent != isContentArray) {\n throw new Error(\n 'Mixing Content and Parts is not supported, please group the parts into a the appropriate Content objects and specify the roles for them',\n );\n }\n\n if (isContent) {\n // `isContent` contains the result of _isContent, which is a utility\n // function that checks if the item is a Content.\n result.push(item as types.Content);\n } else if (_isFunctionCallPart(item) || _isFunctionResponsePart(item)) {\n throw new Error(\n 'To specify functionCall or functionResponse parts, please wrap them, and any other parts, in Content objects as appropriate, specifying the role for them',\n );\n } else {\n accumulatedParts.push(item as types.PartUnion);\n }\n }\n\n if (!isContentArray) {\n result.push({role: 'user', parts: tParts(accumulatedParts)});\n }\n return result;\n}\n\n/*\nTransform the type field from an array of types to an array of anyOf fields.\nExample:\n {type: ['STRING', 'NUMBER']}\nwill be transformed to\n {anyOf: [{type: 'STRING'}, {type: 'NUMBER'}]}\n*/\nfunction flattenTypeArrayToAnyOf(\n typeList: string[],\n resultingSchema: types.Schema,\n) {\n if (typeList.includes('null')) {\n resultingSchema['nullable'] = true;\n }\n const listWithoutNull = typeList.filter((type) => type !== 'null');\n\n if (listWithoutNull.length === 1) {\n resultingSchema['type'] = Object.values(types.Type).includes(\n listWithoutNull[0].toUpperCase() as types.Type,\n )\n ? (listWithoutNull[0].toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED;\n } else {\n resultingSchema['anyOf'] = [];\n for (const i of listWithoutNull) {\n resultingSchema['anyOf'].push({\n 'type': Object.values(types.Type).includes(\n i.toUpperCase() as types.Type,\n )\n ? (i.toUpperCase() as types.Type)\n : types.Type.TYPE_UNSPECIFIED,\n });\n }\n }\n}\n\nexport function processJsonSchema(\n _jsonSchema: types.Schema | Record,\n): types.Schema {\n const genAISchema: types.Schema = {};\n const schemaFieldNames = ['items'];\n const listSchemaFieldNames = ['anyOf'];\n const dictSchemaFieldNames = ['properties'];\n\n if (_jsonSchema['type'] && _jsonSchema['anyOf']) {\n throw new Error('type and anyOf cannot be both populated.');\n }\n\n /*\n This is to handle the nullable array or object. The _jsonSchema will\n be in the format of {anyOf: [{type: 'null'}, {type: 'object'}]}. The\n logic is to check if anyOf has 2 elements and one of the element is null,\n if so, the anyOf field is unnecessary, so we need to get rid of the anyOf\n field and make the schema nullable. Then use the other element as the new\n _jsonSchema for processing. This is because the backend doesn't have a null\n type.\n This has to be checked before we process any other fields.\n For example:\n const objectNullable = z.object({\n nullableArray: z.array(z.string()).nullable(),\n });\n Will have the raw _jsonSchema as:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n anyOf: [\n {type: 'null'},\n {\n type: 'array',\n items: {type: 'string'},\n },\n ],\n }\n },\n required: [ 'nullableArray' ],\n }\n Will result in following schema compatible with Gemini API:\n {\n type: 'OBJECT',\n properties: {\n nullableArray: {\n nullable: true,\n type: 'ARRAY',\n items: {type: 'string'},\n }\n },\n required: [ 'nullableArray' ],\n }\n */\n const incomingAnyOf = _jsonSchema['anyOf'] as Record[];\n if (incomingAnyOf != null && incomingAnyOf.length == 2) {\n if (incomingAnyOf[0]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![1];\n } else if (incomingAnyOf[1]!['type'] === 'null') {\n genAISchema['nullable'] = true;\n _jsonSchema = incomingAnyOf![0];\n }\n }\n\n if (_jsonSchema['type'] instanceof Array) {\n flattenTypeArrayToAnyOf(_jsonSchema['type'], genAISchema);\n }\n\n for (const [fieldName, fieldValue] of Object.entries(_jsonSchema)) {\n // Skip if the fieldvalue is undefined or null.\n if (fieldValue == null) {\n continue;\n }\n\n if (fieldName == 'type') {\n if (fieldValue === 'null') {\n throw new Error(\n 'type: null can not be the only possible type for the field.',\n );\n }\n if (fieldValue instanceof Array) {\n // we have already handled the type field with array of types in the\n // beginning of this function.\n continue;\n }\n genAISchema['type'] = Object.values(types.Type).includes(\n fieldValue.toUpperCase() as types.Type,\n )\n ? fieldValue.toUpperCase()\n : types.Type.TYPE_UNSPECIFIED;\n } else if (schemaFieldNames.includes(fieldName)) {\n (genAISchema as Record)[fieldName] =\n processJsonSchema(fieldValue);\n } else if (listSchemaFieldNames.includes(fieldName)) {\n const listSchemaFieldValue: Array = [];\n for (const item of fieldValue) {\n if (item['type'] == 'null') {\n genAISchema['nullable'] = true;\n continue;\n }\n listSchemaFieldValue.push(\n processJsonSchema(item as Record),\n );\n }\n (genAISchema as Record)[fieldName] =\n listSchemaFieldValue;\n } else if (dictSchemaFieldNames.includes(fieldName)) {\n const dictSchemaFieldValue: Record = {};\n for (const [key, value] of Object.entries(\n fieldValue as Record,\n )) {\n dictSchemaFieldValue[key] = processJsonSchema(\n value as Record,\n );\n }\n (genAISchema as Record)[fieldName] =\n dictSchemaFieldValue;\n } else {\n // additionalProperties is not included in JSONSchema, skipping it.\n if (fieldName === 'additionalProperties') {\n continue;\n }\n (genAISchema as Record)[fieldName] = fieldValue;\n }\n }\n return genAISchema;\n}\n\n// we take the unknown in the schema field because we want enable user to pass\n// the output of major schema declaration tools without casting. Tools such as\n// zodToJsonSchema, typebox, zodToJsonSchema function can return JsonSchema7Type\n// or object, see details in\n// https://github.com/StefanTerdell/zod-to-json-schema/blob/70525efe555cd226691e093d171370a3b10921d1/src/zodToJsonSchema.ts#L7\n// typebox can return unknown, see details in\n// https://github.com/sinclairzx81/typebox/blob/5a5431439f7d5ca6b494d0d18fbfd7b1a356d67c/src/type/create/type.ts#L35\n// Note: proper json schemas with the $schema field set never arrive to this\n// transformer. Schemas with $schema are routed to the equivalent API json\n// schema field.\nexport function tSchema(schema: types.Schema | unknown): types.Schema {\n return processJsonSchema(schema as types.Schema);\n}\n\nexport function tSpeechConfig(\n speechConfig: types.SpeechConfigUnion,\n): types.SpeechConfig {\n if (typeof speechConfig === 'object') {\n return speechConfig;\n } else if (typeof speechConfig === 'string') {\n return {\n voiceConfig: {\n prebuiltVoiceConfig: {\n voiceName: speechConfig,\n },\n },\n };\n } else {\n throw new Error(`Unsupported speechConfig type: ${typeof speechConfig}`);\n }\n}\n\nexport function tLiveSpeechConfig(\n speechConfig: types.SpeechConfig | object,\n): types.SpeechConfig {\n if ('multiSpeakerVoiceConfig' in speechConfig) {\n throw new Error(\n 'multiSpeakerVoiceConfig is not supported in the live API.',\n );\n }\n return speechConfig;\n}\n\nexport function tTool(tool: types.Tool): types.Tool {\n if (tool.functionDeclarations) {\n for (const functionDeclaration of tool.functionDeclarations) {\n if (functionDeclaration.parameters) {\n if (!Object.keys(functionDeclaration.parameters).includes('$schema')) {\n functionDeclaration.parameters = processJsonSchema(\n functionDeclaration.parameters,\n );\n } else {\n if (!functionDeclaration.parametersJsonSchema) {\n functionDeclaration.parametersJsonSchema =\n functionDeclaration.parameters;\n delete functionDeclaration.parameters;\n }\n }\n }\n if (functionDeclaration.response) {\n if (!Object.keys(functionDeclaration.response).includes('$schema')) {\n functionDeclaration.response = processJsonSchema(\n functionDeclaration.response,\n );\n } else {\n if (!functionDeclaration.responseJsonSchema) {\n functionDeclaration.responseJsonSchema =\n functionDeclaration.response;\n delete functionDeclaration.response;\n }\n }\n }\n }\n }\n return tool;\n}\n\nexport function tTools(tools: types.ToolListUnion | unknown): types.Tool[] {\n // Check if the incoming type is defined.\n if (tools === undefined || tools === null) {\n throw new Error('tools is required');\n }\n if (!Array.isArray(tools)) {\n throw new Error('tools is required and must be an array of Tools');\n }\n const result: types.Tool[] = [];\n for (const tool of tools) {\n result.push(tool as types.Tool);\n }\n return result;\n}\n\n/**\n * Prepends resource name with project, location, resource_prefix if needed.\n *\n * @param client The API client.\n * @param resourceName The resource name.\n * @param resourcePrefix The resource prefix.\n * @param splitsAfterPrefix The number of splits after the prefix.\n * @returns The completed resource name.\n *\n * Examples:\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/bar/locations/us-west1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'projects/foo/locations/us-central1/cachedContents/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = True\n * client.project = 'bar'\n * client.location = 'us-west1'\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns: 'projects/foo/locations/us-central1/cachedContents/123'\n * ```\n *\n * ```\n * resource_name = '123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * returns 'cachedContents/123'\n * ```\n *\n * ```\n * resource_name = 'some/wrong/cachedContents/resource/name/123'\n * resource_prefix = 'cachedContents'\n * splits_after_prefix = 1\n * client.vertexai = False\n * # client.vertexai = True\n * _resource_name(client, resource_name, resource_prefix, splits_after_prefix)\n * -> 'some/wrong/resource/name/123'\n * ```\n */\nfunction resourceName(\n client: ApiClient,\n resourceName: string,\n resourcePrefix: string,\n splitsAfterPrefix: number = 1,\n): string {\n const shouldAppendPrefix =\n !resourceName.startsWith(`${resourcePrefix}/`) &&\n resourceName.split('/').length === splitsAfterPrefix;\n if (client.isVertexAI()) {\n if (resourceName.startsWith('projects/')) {\n return resourceName;\n } else if (resourceName.startsWith('locations/')) {\n return `projects/${client.getProject()}/${resourceName}`;\n } else if (resourceName.startsWith(`${resourcePrefix}/`)) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourceName}`;\n } else if (shouldAppendPrefix) {\n return `projects/${client.getProject()}/locations/${client.getLocation()}/${resourcePrefix}/${resourceName}`;\n } else {\n return resourceName;\n }\n }\n if (shouldAppendPrefix) {\n return `${resourcePrefix}/${resourceName}`;\n }\n return resourceName;\n}\n\nexport function tCachedContentName(\n apiClient: ApiClient,\n name: string | unknown,\n): string {\n if (typeof name !== 'string') {\n throw new Error('name must be a string');\n }\n return resourceName(apiClient, name, 'cachedContents');\n}\n\nexport function tTuningJobStatus(status: string | unknown): string {\n switch (status) {\n case 'STATE_UNSPECIFIED':\n return 'JOB_STATE_UNSPECIFIED';\n case 'CREATING':\n return 'JOB_STATE_RUNNING';\n case 'ACTIVE':\n return 'JOB_STATE_SUCCEEDED';\n case 'FAILED':\n return 'JOB_STATE_FAILED';\n default:\n return status as string;\n }\n}\n\nexport function tBytes(fromImageBytes: string | unknown): string {\n return baseTransformers.tBytes(fromImageBytes);\n}\n\nfunction _isFile(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'name' in origin\n );\n}\n\nexport function isGeneratedVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'video' in origin\n );\n}\n\nexport function isVideo(origin: unknown): boolean {\n return (\n origin !== null &&\n origin !== undefined &&\n typeof origin === 'object' &&\n 'uri' in origin\n );\n}\n\nexport function tFileName(\n fromName: string | types.File | types.GeneratedVideo | types.Video,\n): string | undefined {\n let name: string | undefined;\n\n if (_isFile(fromName)) {\n name = (fromName as types.File).name;\n }\n if (isVideo(fromName)) {\n name = (fromName as types.Video).uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (isGeneratedVideo(fromName)) {\n name = (fromName as types.GeneratedVideo).video?.uri;\n if (name === undefined) {\n return undefined;\n }\n }\n if (typeof fromName === 'string') {\n name = fromName;\n }\n\n if (name === undefined) {\n throw new Error('Could not extract file name from the provided input.');\n }\n\n if (name.startsWith('https://')) {\n const suffix = name.split('files/')[1];\n const match = suffix.match(/[a-z0-9]+/);\n if (match === null) {\n throw new Error(`Could not extract file name from URI ${name}`);\n }\n name = match[0];\n } else if (name.startsWith('files/')) {\n name = name.split('files/')[1];\n }\n return name;\n}\n\nexport function tModelsUrl(\n apiClient: ApiClient,\n baseModels: boolean | unknown,\n): string {\n let res: string;\n if (apiClient.isVertexAI()) {\n res = baseModels ? 'publishers/google/models' : 'models';\n } else {\n res = baseModels ? 'models' : 'tunedModels';\n }\n return res;\n}\n\nexport function tExtractModels(response: unknown): Record[] {\n for (const key of ['models', 'tunedModels', 'publisherModels']) {\n if (hasField(response, key)) {\n return (response as Record)[key] as Record<\n string,\n unknown\n >[];\n }\n }\n return [];\n}\n\nfunction hasField(data: unknown, fieldName: string): boolean {\n return data !== null && typeof data === 'object' && fieldName in data;\n}\n\nexport function mcpToGeminiTool(\n mcpTool: McpTool,\n config: types.CallableToolConfig = {},\n): types.Tool {\n const mcpToolSchema = mcpTool as Record;\n const functionDeclaration: Record = {\n name: mcpToolSchema['name'],\n description: mcpToolSchema['description'],\n parametersJsonSchema: mcpToolSchema['inputSchema'],\n };\n if (config.behavior) {\n functionDeclaration['behavior'] = config.behavior;\n }\n\n const geminiTool = {\n functionDeclarations: [\n functionDeclaration as unknown as types.FunctionDeclaration,\n ],\n };\n\n return geminiTool;\n}\n\n/**\n * Converts a list of MCP tools to a single Gemini tool with a list of function\n * declarations.\n */\nexport function mcpToolsToGeminiTool(\n mcpTools: McpTool[],\n config: types.CallableToolConfig = {},\n): types.Tool {\n const functionDeclarations: types.FunctionDeclaration[] = [];\n const toolNames = new Set();\n for (const mcpTool of mcpTools) {\n const mcpToolName = mcpTool.name as string;\n if (toolNames.has(mcpToolName)) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n toolNames.add(mcpToolName);\n const geminiTool = mcpToGeminiTool(mcpTool, config);\n if (geminiTool.functionDeclarations) {\n functionDeclarations.push(...geminiTool.functionDeclarations);\n }\n }\n\n return {functionDeclarations: functionDeclarations};\n}\n\n// Transforms a source input into a BatchJobSource object with validation.\nexport function tBatchJobSource(\n apiClient: ApiClient,\n src: string | types.InlinedRequest[] | types.BatchJobSource,\n): types.BatchJobSource {\n if (typeof src !== 'string' && !Array.isArray(src)) {\n if (apiClient && apiClient.isVertexAI()) {\n if (src.gcsUri && src.bigqueryUri) {\n throw new Error('Only one of `gcsUri` or `bigqueryUri` can be set.');\n } else if (!src.gcsUri && !src.bigqueryUri) {\n throw new Error('One of `gcsUri` or `bigqueryUri` must be set.');\n }\n } else {\n // Logic for non-Vertex AI client (inlined_requests, file_name)\n if (src.inlinedRequests && src.fileName) {\n throw new Error(\n 'Only one of `inlinedRequests` or `fileName` can be set.',\n );\n } else if (!src.inlinedRequests && !src.fileName) {\n throw new Error('One of `inlinedRequests` or `fileName` must be set.');\n }\n }\n return src;\n }\n // If src is an array (list in Python)\n else if (Array.isArray(src)) {\n return {inlinedRequests: src};\n } else if (typeof src === 'string') {\n if (src.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: [src], // GCS URI is expected as an array\n };\n } else if (src.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: src,\n };\n } else if (src.startsWith('files/')) {\n return {\n fileName: src,\n };\n }\n }\n throw new Error(`Unsupported source: ${src}`);\n}\n\nexport function tBatchJobDestination(\n dest: string | types.BatchJobDestination,\n): types.BatchJobDestination {\n if (typeof dest !== 'string') {\n return dest as types.BatchJobDestination;\n }\n const destString = dest as string;\n if (destString.startsWith('gs://')) {\n return {\n format: 'jsonl',\n gcsUri: destString,\n };\n } else if (destString.startsWith('bq://')) {\n return {\n format: 'bigquery',\n bigqueryUri: destString,\n };\n } else {\n throw new Error(`Unsupported destination: ${destString}`);\n }\n}\n\nexport function tBatchJobName(apiClient: ApiClient, name: unknown): string {\n const nameString = name as string;\n if (!apiClient.isVertexAI()) {\n const mldevPattern = /batches\\/[^/]+$/;\n\n if (mldevPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n }\n\n const vertexPattern =\n /^projects\\/[^/]+\\/locations\\/[^/]+\\/batchPredictionJobs\\/[^/]+$/;\n\n if (vertexPattern.test(nameString)) {\n return nameString.split('/').pop() as string;\n } else if (/^\\d+$/.test(nameString)) {\n return nameString;\n } else {\n throw new Error(`Invalid batch job name: ${nameString}.`);\n }\n}\n\nexport function tJobState(state: unknown): string {\n const stateString = state as string;\n if (stateString === 'BATCH_STATE_UNSPECIFIED') {\n return 'JOB_STATE_UNSPECIFIED';\n } else if (stateString === 'BATCH_STATE_PENDING') {\n return 'JOB_STATE_PENDING';\n } else if (stateString === 'BATCH_STATE_SUCCEEDED') {\n return 'JOB_STATE_SUCCEEDED';\n } else if (stateString === 'BATCH_STATE_FAILED') {\n return 'JOB_STATE_FAILED';\n } else if (stateString === 'BATCH_STATE_CANCELLED') {\n return 'JOB_STATE_CANCELLED';\n } else {\n return stateString;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function inlinedRequestToMldev(\n apiClient: ApiClient,\n fromObject: types.InlinedRequest,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['request', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['request', 'contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['request', 'generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToMldev(\n apiClient: ApiClient,\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['format']) !== undefined) {\n throw new Error('format parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['bigqueryUri']) !== undefined) {\n throw new Error('bigqueryUri parameter is not supported in Gemini API.');\n }\n\n const fromFileName = common.getValueByPath(fromObject, ['fileName']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedRequests = common.getValueByPath(fromObject, [\n 'inlinedRequests',\n ]);\n if (fromInlinedRequests != null) {\n let transformedList = fromInlinedRequests;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedRequestToMldev(apiClient, item);\n });\n }\n common.setValueByPath(toObject, ['requests', 'requests'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToMldev(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['batch', 'displayName'],\n fromDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['dest']) !== undefined) {\n throw new Error('dest parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['batch', 'inputConfig'],\n batchJobSourceToMldev(apiClient, t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToMldev(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n if (common.getValueByPath(fromObject, ['filter']) !== undefined) {\n throw new Error('filter parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToMldev(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceToVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['instancesFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsSource', 'uris'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigquerySource', 'inputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedRequests']) !== undefined) {\n throw new Error('inlinedRequests parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationToVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['predictionsFormat'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(\n toObject,\n ['gcsDestination', 'outputUriPrefix'],\n fromGcsUri,\n );\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, ['bigqueryUri']);\n if (fromBigqueryUri != null) {\n common.setValueByPath(\n toObject,\n ['bigqueryDestination', 'outputUri'],\n fromBigqueryUri,\n );\n }\n\n if (common.getValueByPath(fromObject, ['fileName']) !== undefined) {\n throw new Error('fileName parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['inlinedResponses']) !== undefined) {\n throw new Error(\n 'inlinedResponses parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobConfigToVertex(\n fromObject: types.CreateBatchJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['dest']);\n if (parentObject !== undefined && fromDest != null) {\n common.setValueByPath(\n parentObject,\n ['outputConfig'],\n batchJobDestinationToVertex(t.tBatchJobDestination(fromDest)),\n );\n }\n\n return toObject;\n}\n\nexport function createBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], t.tModel(apiClient, fromModel));\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['src']);\n if (fromSrc != null) {\n common.setValueByPath(\n toObject,\n ['inputConfig'],\n batchJobSourceToVertex(t.tBatchJobSource(apiClient, fromSrc)),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createBatchJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function cancelBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CancelBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsConfigToVertex(\n fromObject: types.ListBatchJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listBatchJobsParametersToVertex(\n fromObject: types.ListBatchJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listBatchJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteBatchJobParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteBatchJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tBatchJobName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function jobErrorFromMldev(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function inlinedResponseFromMldev(\n fromObject: types.InlinedResponse,\n): Record {\n const toObject: Record = {};\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateContentResponseFromMldev(\n fromResponse as types.GenerateContentResponse,\n ),\n );\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromMldev(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFileName = common.getValueByPath(fromObject, ['responsesFile']);\n if (fromFileName != null) {\n common.setValueByPath(toObject, ['fileName'], fromFileName);\n }\n\n const fromInlinedResponses = common.getValueByPath(fromObject, [\n 'inlinedResponses',\n 'inlinedResponses',\n ]);\n if (fromInlinedResponses != null) {\n let transformedList = fromInlinedResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return inlinedResponseFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['inlinedResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function batchJobFromMldev(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, [\n 'metadata',\n 'displayName',\n ]);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['metadata', 'state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'createTime',\n ]);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'endTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, [\n 'metadata',\n 'updateTime',\n ]);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['metadata', 'model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromDest = common.getValueByPath(fromObject, ['metadata', 'output']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromMldev(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromMldev(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, ['operations']);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromMldev(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function jobErrorFromVertex(\n fromObject: types.JobError,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n return toObject;\n}\n\nexport function batchJobSourceFromVertex(\n fromObject: types.BatchJobSource,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['instancesFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsSource', 'uris']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigquerySource',\n 'inputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobDestinationFromVertex(\n fromObject: types.BatchJobDestination,\n): Record {\n const toObject: Record = {};\n\n const fromFormat = common.getValueByPath(fromObject, ['predictionsFormat']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromGcsUri = common.getValueByPath(fromObject, [\n 'gcsDestination',\n 'outputUriPrefix',\n ]);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromBigqueryUri = common.getValueByPath(fromObject, [\n 'bigqueryDestination',\n 'outputUri',\n ]);\n if (fromBigqueryUri != null) {\n common.setValueByPath(toObject, ['bigqueryUri'], fromBigqueryUri);\n }\n\n return toObject;\n}\n\nexport function batchJobFromVertex(\n fromObject: types.BatchJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tJobState(fromState));\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromSrc = common.getValueByPath(fromObject, ['inputConfig']);\n if (fromSrc != null) {\n common.setValueByPath(toObject, ['src'], batchJobSourceFromVertex(fromSrc));\n }\n\n const fromDest = common.getValueByPath(fromObject, ['outputConfig']);\n if (fromDest != null) {\n common.setValueByPath(\n toObject,\n ['dest'],\n batchJobDestinationFromVertex(fromDest),\n );\n }\n\n return toObject;\n}\n\nexport function listBatchJobsResponseFromVertex(\n fromObject: types.ListBatchJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromBatchJobs = common.getValueByPath(fromObject, [\n 'batchPredictionJobs',\n ]);\n if (fromBatchJobs != null) {\n let transformedList = fromBatchJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return batchJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['batchJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteResourceJobFromVertex(\n fromObject: types.DeleteResourceJob,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], jobErrorFromVertex(fromError));\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Pagers for the GenAI List APIs.\n */\n\nimport * as types from '../src/types';\n\nexport enum PagedItem {\n PAGED_ITEM_BATCH_JOBS = 'batchJobs',\n PAGED_ITEM_MODELS = 'models',\n PAGED_ITEM_TUNING_JOBS = 'tuningJobs',\n PAGED_ITEM_FILES = 'files',\n PAGED_ITEM_CACHED_CONTENTS = 'cachedContents',\n}\n\ninterface PagedItemConfig {\n config?: {\n pageToken?: string;\n pageSize?: number;\n };\n}\n\ninterface PagedItemResponse {\n nextPageToken?: string;\n sdkHttpResponse?: types.HttpResponse;\n batchJobs?: T[];\n models?: T[];\n tuningJobs?: T[];\n files?: T[];\n cachedContents?: T[];\n}\n\n/**\n * Pager class for iterating through paginated results.\n */\nexport class Pager implements AsyncIterable {\n private nameInternal!: PagedItem;\n private pageInternal: T[] = [];\n private paramsInternal: PagedItemConfig = {};\n private pageInternalSize!: number;\n private sdkHttpResponseInternal?: types.HttpResponse;\n protected requestInternal!: (\n params: PagedItemConfig,\n ) => Promise>;\n protected idxInternal!: number;\n\n constructor(\n name: PagedItem,\n request: (params: PagedItemConfig) => Promise>,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.requestInternal = request;\n this.init(name, response, params);\n }\n\n private init(\n name: PagedItem,\n response: PagedItemResponse,\n params: PagedItemConfig,\n ) {\n this.nameInternal = name;\n this.pageInternal = response[this.nameInternal] || [];\n\n this.sdkHttpResponseInternal = response?.sdkHttpResponse;\n this.idxInternal = 0;\n let requestParams: PagedItemConfig = {config: {}};\n if (!params || Object.keys(params).length === 0) {\n requestParams = {config: {}};\n } else if (typeof params === 'object') {\n requestParams = {...params};\n } else {\n requestParams = params;\n }\n if (requestParams['config']) {\n requestParams['config']['pageToken'] = response['nextPageToken'];\n }\n this.paramsInternal = requestParams;\n this.pageInternalSize =\n requestParams['config']?.['pageSize'] ?? this.pageInternal.length;\n }\n\n private initNextPage(response: PagedItemResponse): void {\n this.init(this.nameInternal, response, this.paramsInternal);\n }\n\n /**\n * Returns the current page, which is a list of items.\n *\n * @remarks\n * The first page is retrieved when the pager is created. The returned list of\n * items could be a subset of the entire list.\n */\n get page(): T[] {\n return this.pageInternal;\n }\n\n /**\n * Returns the type of paged item (for example, ``batch_jobs``).\n */\n get name(): PagedItem {\n return this.nameInternal;\n }\n\n /**\n * Returns the length of the page fetched each time by this pager.\n *\n * @remarks\n * The number of items in the page is less than or equal to the page length.\n */\n get pageSize(): number {\n return this.pageInternalSize;\n }\n\n /**\n * Returns the headers of the API response.\n */\n get sdkHttpResponse(): types.HttpResponse | undefined {\n return this.sdkHttpResponseInternal;\n }\n\n /**\n * Returns the parameters when making the API request for the next page.\n *\n * @remarks\n * Parameters contain a set of optional configs that can be\n * used to customize the API request. For example, the `pageToken` parameter\n * contains the token to request the next page.\n */\n get params(): PagedItemConfig {\n return this.paramsInternal;\n }\n\n /**\n * Returns the total number of items in the current page.\n */\n get pageLength(): number {\n return this.pageInternal.length;\n }\n\n /**\n * Returns the item at the given index.\n */\n getItem(index: number): T {\n return this.pageInternal[index];\n }\n\n /**\n * Returns an async iterator that support iterating through all items\n * retrieved from the API.\n *\n * @remarks\n * The iterator will automatically fetch the next page if there are more items\n * to fetch from the API.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * for await (const file of pager) {\n * console.log(file.name);\n * }\n * ```\n */\n [Symbol.asyncIterator](): AsyncIterator {\n return {\n next: async () => {\n if (this.idxInternal >= this.pageLength) {\n if (this.hasNextPage()) {\n await this.nextPage();\n } else {\n return {value: undefined, done: true};\n }\n }\n const item = this.getItem(this.idxInternal);\n this.idxInternal += 1;\n return {value: item, done: false};\n },\n return: async () => {\n return {value: undefined, done: true};\n },\n };\n }\n\n /**\n * Fetches the next page of items. This makes a new API request.\n *\n * @throws {Error} If there are no more pages to fetch.\n *\n * @example\n *\n * ```ts\n * const pager = await ai.files.list({config: {pageSize: 10}});\n * let page = pager.page;\n * while (true) {\n * for (const file of page) {\n * console.log(file.name);\n * }\n * if (!pager.hasNextPage()) {\n * break;\n * }\n * page = await pager.nextPage();\n * }\n * ```\n */\n async nextPage(): Promise {\n if (!this.hasNextPage()) {\n throw new Error('No more pages to fetch.');\n }\n const response = await this.requestInternal(this.params);\n this.initNextPage(response);\n return this.page;\n }\n\n /**\n * Returns true if there are more pages to fetch from the API.\n */\n hasNextPage(): boolean {\n if (this.params['config']?.['pageToken'] !== undefined) {\n return true;\n }\n return false;\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_batches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Batches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n * @example\n * ```ts\n * const response = await ai.batches.create({\n * model: 'gemini-2.0-flash',\n * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'},\n * config: {\n * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'},\n * }\n * });\n * console.log(response);\n * ```\n */\n create = async (\n params: types.CreateBatchJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n const timestamp = Date.now();\n const timestampStr = timestamp.toString();\n if (Array.isArray(params.src)) {\n throw new Error(\n 'InlinedRequest[] is not supported in Vertex AI. Please use ' +\n 'Google Cloud Storage URI or BigQuery URI instead.',\n );\n }\n params.config = params.config || {};\n if (params.config.displayName === undefined) {\n params.config.displayName = 'genaiBatchJob_${timestampStr}';\n }\n if (params.config.dest === undefined && typeof params.src === 'string') {\n if (params.src.startsWith('gs://') && params.src.endsWith('.jsonl')) {\n params.config.dest = `${params.src.slice(0, -6)}/dest`;\n } else if (params.src.startsWith('bq://')) {\n params.config.dest =\n `${params.src}_dest_${timestampStr}` as unknown as string;\n } else {\n throw new Error('Unsupported source:' + params.src);\n }\n }\n }\n return await this.createInternal(params);\n };\n\n /**\n * Lists batch job configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of batch jobs.\n *\n * @example\n * ```ts\n * const batchJobs = await ai.batches.list({config: {'pageSize': 2}});\n * for await (const batchJob of batchJobs) {\n * console.log(batchJob);\n * }\n * ```\n */\n list = async (\n params: types.ListBatchJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_BATCH_JOBS,\n (x: types.ListBatchJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Internal method to create batch job.\n *\n * @param params - The parameters for create batch job request.\n * @return The created batch job.\n *\n */\n private async createInternal(\n params: types.CreateBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.createBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchGenerateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Gets batch job configurations.\n *\n * @param params - The parameters for the get request.\n * @return The batch job.\n *\n * @example\n * ```ts\n * await ai.batches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(params: types.GetBatchJobParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromVertex(apiResponse);\n\n return resp as types.BatchJob;\n });\n } else {\n const body = converters.getBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.batchJobFromMldev(apiResponse);\n\n return resp as types.BatchJob;\n });\n }\n }\n\n /**\n * Cancels a batch job.\n *\n * @param params - The parameters for the cancel request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.cancel({name: '...'}); // The server-generated resource name.\n * ```\n */\n async cancel(params: types.CancelBatchJobParameters): Promise {\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.cancelBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n } else {\n const body = converters.cancelBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}:cancel',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n await this.apiClient.request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n });\n }\n }\n\n private async listInternal(\n params: types.ListBatchJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listBatchJobsParametersToVertex(params);\n path = common.formatMap(\n 'batchPredictionJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listBatchJobsParametersToMldev(params);\n path = common.formatMap(\n 'batches',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListBatchJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listBatchJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListBatchJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Deletes a batch job.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.batches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteBatchJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteBatchJobParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batchPredictionJobs/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromVertex(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n } else {\n const body = converters.deleteBatchJobParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'batches/{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.deleteResourceJobFromMldev(apiResponse);\n\n return resp as types.DeleteResourceJob;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToMldev(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['kmsKeyName']) !== undefined) {\n throw new Error('kmsKeyName parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToMldev(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToMldev(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToMldev(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentConfigToVertex(\n fromObject: types.CreateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (parentObject !== undefined && fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['contents'], transformedList);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromKmsKeyName = common.getValueByPath(fromObject, ['kmsKeyName']);\n if (parentObject !== undefined && fromKmsKeyName != null) {\n common.setValueByPath(\n parentObject,\n ['encryption_spec', 'kmsKeyName'],\n fromKmsKeyName,\n );\n }\n\n return toObject;\n}\n\nexport function createCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CreateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['model'],\n t.tCachesModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentConfigToVertex(\n fromObject: types.UpdateCachedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTtl = common.getValueByPath(fromObject, ['ttl']);\n if (parentObject !== undefined && fromTtl != null) {\n common.setValueByPath(parentObject, ['ttl'], fromTtl);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n return toObject;\n}\n\nexport function updateCachedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateCachedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tCachedContentName(apiClient, fromName),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateCachedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function listCachedContentsConfigToVertex(\n fromObject: types.ListCachedContentsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listCachedContentsParametersToVertex(\n fromObject: types.ListCachedContentsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listCachedContentsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function cachedContentFromMldev(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromMldev(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n\nexport function cachedContentFromVertex(\n fromObject: types.CachedContent,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (fromExpireTime != null) {\n common.setValueByPath(toObject, ['expireTime'], fromExpireTime);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function deleteCachedContentResponseFromVertex(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function listCachedContentsResponseFromVertex(\n fromObject: types.ListCachedContentsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromCachedContents = common.getValueByPath(fromObject, [\n 'cachedContents',\n ]);\n if (fromCachedContents != null) {\n let transformedList = fromCachedContents;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return cachedContentFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cachedContents'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_caches_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Caches extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists cached content configurations.\n *\n * @param params - The parameters for the list request.\n * @return The paginated results of the list of cached contents.\n *\n * @example\n * ```ts\n * const cachedContents = await ai.caches.list({config: {'pageSize': 2}});\n * for await (const cachedContent of cachedContents) {\n * console.log(cachedContent);\n * }\n * ```\n */\n list = async (\n params: types.ListCachedContentsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_CACHED_CONTENTS,\n (x: types.ListCachedContentsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a cached contents resource.\n *\n * @remarks\n * Context caching is only supported for specific models. See [Gemini\n * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac)\n * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models)\n * for more information.\n *\n * @param params - The parameters for the create request.\n * @return The created cached content.\n *\n * @example\n * ```ts\n * const contents = ...; // Initialize the content to cache.\n * const response = await ai.caches.create({\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'contents': contents,\n * 'displayName': 'test cache',\n * 'systemInstruction': 'What is the sum of the two pdfs?',\n * 'ttl': '86400s',\n * }\n * });\n * ```\n */\n async create(\n params: types.CreateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.createCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Gets cached content configurations.\n *\n * @param params - The parameters for the get request.\n * @return The cached content.\n *\n * @example\n * ```ts\n * await ai.caches.get({name: '...'}); // The server-generated resource name.\n * ```\n */\n async get(\n params: types.GetCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.getCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n /**\n * Deletes cached content.\n *\n * @param params - The parameters for the delete request.\n * @return The empty response returned by the API.\n *\n * @example\n * ```ts\n * await ai.caches.delete({name: '...'}); // The server-generated resource name.\n * ```\n */\n async delete(\n params: types.DeleteCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromVertex();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteCachedContentResponseFromMldev();\n const typedResp = new types.DeleteCachedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates cached content configurations.\n *\n * @param params - The parameters for the update request.\n * @return The updated cached content.\n *\n * @example\n * ```ts\n * const response = await ai.caches.update({\n * name: '...', // The server-generated resource name.\n * config: {'ttl': '7600s'}\n * });\n * ```\n */\n async update(\n params: types.UpdateCachedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateCachedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromVertex(apiResponse);\n\n return resp as types.CachedContent;\n });\n } else {\n const body = converters.updateCachedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.cachedContentFromMldev(apiResponse);\n\n return resp as types.CachedContent;\n });\n }\n }\n\n private async listInternal(\n params: types.ListCachedContentsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listCachedContentsParametersToVertex(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromVertex(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listCachedContentsParametersToMldev(params);\n path = common.formatMap(\n 'cachedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListCachedContentsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp =\n converters.listCachedContentsResponseFromMldev(apiResponse);\n const typedResp = new types.ListCachedContentsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as t from './_transformers.js';\nimport {Models} from './models.js';\nimport * as types from './types.js';\n\n/**\n * Returns true if the response is valid, false otherwise.\n */\nfunction isValidResponse(response: types.GenerateContentResponse): boolean {\n if (response.candidates == undefined || response.candidates.length === 0) {\n return false;\n }\n const content = response.candidates[0]?.content;\n if (content === undefined) {\n return false;\n }\n return isValidContent(content);\n}\n\nfunction isValidContent(content: types.Content): boolean {\n if (content.parts === undefined || content.parts.length === 0) {\n return false;\n }\n for (const part of content.parts) {\n if (part === undefined || Object.keys(part).length === 0) {\n return false;\n }\n if (!part.thought && part.text !== undefined && part.text === '') {\n return false;\n }\n }\n return true;\n}\n\n/**\n * Validates the history contains the correct roles.\n *\n * @throws Error if the history does not start with a user turn.\n * @throws Error if the history contains an invalid role.\n */\nfunction validateHistory(history: types.Content[]) {\n // Empty history is valid.\n if (history.length === 0) {\n return;\n }\n for (const content of history) {\n if (content.role !== 'user' && content.role !== 'model') {\n throw new Error(`Role must be user or model, but got ${content.role}.`);\n }\n }\n}\n\n/**\n * Extracts the curated (valid) history from a comprehensive history.\n *\n * @remarks\n * The model may sometimes generate invalid or empty contents(e.g., due to safty\n * filters or recitation). Extracting valid turns from the history\n * ensures that subsequent requests could be accpeted by the model.\n */\nfunction extractCuratedHistory(\n comprehensiveHistory: types.Content[],\n): types.Content[] {\n if (comprehensiveHistory === undefined || comprehensiveHistory.length === 0) {\n return [];\n }\n const curatedHistory: types.Content[] = [];\n const length = comprehensiveHistory.length;\n let i = 0;\n while (i < length) {\n if (comprehensiveHistory[i].role === 'user') {\n curatedHistory.push(comprehensiveHistory[i]);\n i++;\n } else {\n const modelOutput: types.Content[] = [];\n let isValid = true;\n while (i < length && comprehensiveHistory[i].role === 'model') {\n modelOutput.push(comprehensiveHistory[i]);\n if (isValid && !isValidContent(comprehensiveHistory[i])) {\n isValid = false;\n }\n i++;\n }\n if (isValid) {\n curatedHistory.push(...modelOutput);\n } else {\n // Remove the last user input when model content is invalid.\n curatedHistory.pop();\n }\n }\n }\n return curatedHistory;\n}\n\n/**\n * A utility class to create a chat session.\n */\nexport class Chats {\n private readonly modelsModule: Models;\n private readonly apiClient: ApiClient;\n\n constructor(modelsModule: Models, apiClient: ApiClient) {\n this.modelsModule = modelsModule;\n this.apiClient = apiClient;\n }\n\n /**\n * Creates a new chat session.\n *\n * @remarks\n * The config in the params will be used for all requests within the chat\n * session unless overridden by a per-request `config` in\n * @see {@link types.SendMessageParameters#config}.\n *\n * @param params - Parameters for creating a chat session.\n * @returns A new chat session.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({\n * model: 'gemini-2.0-flash'\n * config: {\n * temperature: 0.5,\n * maxOutputTokens: 1024,\n * }\n * });\n * ```\n */\n create(params: types.CreateChatParameters) {\n return new Chat(\n this.apiClient,\n this.modelsModule,\n params.model,\n params.config,\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n structuredClone(params.history),\n );\n }\n}\n\n/**\n * Chat session that enables sending messages to the model with previous\n * conversation context.\n *\n * @remarks\n * The session maintains all the turns between user and model.\n */\nexport class Chat {\n // A promise to represent the current state of the message being sent to the\n // model.\n private sendPromise: Promise = Promise.resolve();\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly modelsModule: Models,\n private readonly model: string,\n private readonly config: types.GenerateContentConfig = {},\n private history: types.Content[] = [],\n ) {\n validateHistory(history);\n }\n\n /**\n * Sends a message to the model and returns the response.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessageStream} for streaming method.\n * @param params - parameters for sending messages within a chat session.\n * @returns The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessage({\n * message: 'Why is the sky blue?'\n * });\n * console.log(response.text);\n * ```\n */\n async sendMessage(\n params: types.SendMessageParameters,\n ): Promise {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const responsePromise = this.modelsModule.generateContent({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n this.sendPromise = (async () => {\n const response = await responsePromise;\n const outputContent = response.candidates?.[0]?.content;\n\n // Because the AFC input contains the entire curated chat history in\n // addition to the new user input, we need to truncate the AFC history\n // to deduplicate the existing chat history.\n const fullAutomaticFunctionCallingHistory =\n response.automaticFunctionCallingHistory;\n const index = this.getHistory(true).length;\n\n let automaticFunctionCallingHistory: types.Content[] = [];\n if (fullAutomaticFunctionCallingHistory != null) {\n automaticFunctionCallingHistory =\n fullAutomaticFunctionCallingHistory.slice(index) ?? [];\n }\n\n const modelOutput = outputContent ? [outputContent] : [];\n this.recordHistory(\n inputContent,\n modelOutput,\n automaticFunctionCallingHistory,\n );\n return;\n })();\n await this.sendPromise.catch(() => {\n // Resets sendPromise to avoid subsequent calls failing\n this.sendPromise = Promise.resolve();\n });\n return responsePromise;\n }\n\n /**\n * Sends a message to the model and returns the response in chunks.\n *\n * @remarks\n * This method will wait for the previous message to be processed before\n * sending the next message.\n *\n * @see {@link Chat#sendMessage} for non-streaming method.\n * @param params - parameters for sending the message.\n * @return The model's response.\n *\n * @example\n * ```ts\n * const chat = ai.chats.create({model: 'gemini-2.0-flash'});\n * const response = await chat.sendMessageStream({\n * message: 'Why is the sky blue?'\n * });\n * for await (const chunk of response) {\n * console.log(chunk.text);\n * }\n * ```\n */\n async sendMessageStream(\n params: types.SendMessageParameters,\n ): Promise> {\n await this.sendPromise;\n const inputContent = t.tContent(params.message);\n const streamResponse = this.modelsModule.generateContentStream({\n model: this.model,\n contents: this.getHistory(true).concat(inputContent),\n config: params.config ?? this.config,\n });\n // Resolve the internal tracking of send completion promise - `sendPromise`\n // for both success and failure response. The actual failure is still\n // propagated by the `await streamResponse`.\n this.sendPromise = streamResponse\n .then(() => undefined)\n .catch(() => undefined);\n const response = await streamResponse;\n const result = this.processStreamResponse(response, inputContent);\n return result;\n }\n\n /**\n * Returns the chat history.\n *\n * @remarks\n * The history is a list of contents alternating between user and model.\n *\n * There are two types of history:\n * - The `curated history` contains only the valid turns between user and\n * model, which will be included in the subsequent requests sent to the model.\n * - The `comprehensive history` contains all turns, including invalid or\n * empty model outputs, providing a complete record of the history.\n *\n * The history is updated after receiving the response from the model,\n * for streaming response, it means receiving the last chunk of the response.\n *\n * The `comprehensive history` is returned by default. To get the `curated\n * history`, set the `curated` parameter to `true`.\n *\n * @param curated - whether to return the curated history or the comprehensive\n * history.\n * @return History contents alternating between user and model for the entire\n * chat session.\n */\n getHistory(curated: boolean = false): types.Content[] {\n const history = curated\n ? extractCuratedHistory(this.history)\n : this.history;\n // Deep copy the history to avoid mutating the history outside of the\n // chat session.\n return structuredClone(history);\n }\n\n private async *processStreamResponse(\n streamResponse: AsyncGenerator,\n inputContent: types.Content,\n ) {\n const outputContent: types.Content[] = [];\n for await (const chunk of streamResponse) {\n if (isValidResponse(chunk)) {\n const content = chunk.candidates?.[0]?.content;\n if (content !== undefined) {\n outputContent.push(content);\n }\n }\n yield chunk;\n }\n this.recordHistory(inputContent, outputContent);\n }\n\n private recordHistory(\n userInput: types.Content,\n modelOutput: types.Content[],\n automaticFunctionCallingHistory?: types.Content[],\n ) {\n let outputContents: types.Content[] = [];\n if (\n modelOutput.length > 0 &&\n modelOutput.every((content) => content.role !== undefined)\n ) {\n outputContents = modelOutput;\n } else {\n // Appends an empty content when model returns empty response, so that the\n // history is always alternating between user and model.\n outputContents.push({\n role: 'model',\n parts: [],\n } as types.Content);\n }\n if (\n automaticFunctionCallingHistory &&\n automaticFunctionCallingHistory.length > 0\n ) {\n this.history.push(\n ...extractCuratedHistory(automaticFunctionCallingHistory!),\n );\n } else {\n this.history.push(userInput);\n }\n this.history.push(...outputContents);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Details for errors from calling the API.\n */\nexport interface ApiErrorInfo {\n /** The error message. */\n message: string;\n /** The HTTP status code. */\n status: number;\n}\n\n/**\n * API errors raised by the GenAI API.\n */\nexport class ApiError extends Error {\n /** HTTP status code */\n status: number;\n\n constructor(options: ApiErrorInfo) {\n super(options.message);\n this.name = 'ApiError';\n this.status = options.status;\n Object.setPrototypeOf(this, ApiError.prototype);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function listFilesConfigToMldev(\n fromObject: types.ListFilesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n return toObject;\n}\n\nexport function listFilesParametersToMldev(\n fromObject: types.ListFilesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listFilesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function fileStatusToMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileToMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusToMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function createFileParametersToMldev(\n fromObject: types.CreateFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromFile = common.getValueByPath(fromObject, ['file']);\n if (fromFile != null) {\n common.setValueByPath(toObject, ['file'], fileToMldev(fromFile));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getFileParametersToMldev(\n fromObject: types.GetFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function deleteFileParametersToMldev(\n fromObject: types.DeleteFileParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'file'], t.tFileName(fromName));\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fileStatusFromMldev(\n fromObject: types.FileStatus,\n): Record {\n const toObject: Record = {};\n\n const fromDetails = common.getValueByPath(fromObject, ['details']);\n if (fromDetails != null) {\n common.setValueByPath(toObject, ['details'], fromDetails);\n }\n\n const fromMessage = common.getValueByPath(fromObject, ['message']);\n if (fromMessage != null) {\n common.setValueByPath(toObject, ['message'], fromMessage);\n }\n\n const fromCode = common.getValueByPath(fromObject, ['code']);\n if (fromCode != null) {\n common.setValueByPath(toObject, ['code'], fromCode);\n }\n\n return toObject;\n}\n\nexport function fileFromMldev(fromObject: types.File): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSizeBytes = common.getValueByPath(fromObject, ['sizeBytes']);\n if (fromSizeBytes != null) {\n common.setValueByPath(toObject, ['sizeBytes'], fromSizeBytes);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromExpirationTime = common.getValueByPath(fromObject, [\n 'expirationTime',\n ]);\n if (fromExpirationTime != null) {\n common.setValueByPath(toObject, ['expirationTime'], fromExpirationTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromSha256Hash = common.getValueByPath(fromObject, ['sha256Hash']);\n if (fromSha256Hash != null) {\n common.setValueByPath(toObject, ['sha256Hash'], fromSha256Hash);\n }\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromDownloadUri = common.getValueByPath(fromObject, ['downloadUri']);\n if (fromDownloadUri != null) {\n common.setValueByPath(toObject, ['downloadUri'], fromDownloadUri);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], fromState);\n }\n\n const fromSource = common.getValueByPath(fromObject, ['source']);\n if (fromSource != null) {\n common.setValueByPath(toObject, ['source'], fromSource);\n }\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(toObject, ['videoMetadata'], fromVideoMetadata);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fileStatusFromMldev(fromError));\n }\n\n return toObject;\n}\n\nexport function listFilesResponseFromMldev(\n fromObject: types.ListFilesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromFiles = common.getValueByPath(fromObject, ['files']);\n if (fromFiles != null) {\n let transformedList = fromFiles;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return fileFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['files'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createFileResponseFromMldev(\n fromObject: types.CreateFileResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n return toObject;\n}\n\nexport function deleteFileResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_files_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Files extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Lists all current project files from the service.\n *\n * @param params - The parameters for the list request\n * @return The paginated results of the list of files\n *\n * @example\n * The following code prints the names of all files from the service, the\n * size of each page is 10.\n *\n * ```ts\n * const listResponse = await ai.files.list({config: {'pageSize': 10}});\n * for await (const file of listResponse) {\n * console.log(file.name);\n * }\n * ```\n */\n list = async (\n params: types.ListFilesParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_FILES,\n (x: types.ListFilesParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Uploads a file asynchronously to the Gemini API.\n * This method is not available in Vertex AI.\n * Supported upload sources:\n * - Node.js: File path (string) or Blob object.\n * - Browser: Blob object (e.g., File).\n *\n * @remarks\n * The `mimeType` can be specified in the `config` parameter. If omitted:\n * - For file path (string) inputs, the `mimeType` will be inferred from the\n * file extension.\n * - For Blob object inputs, the `mimeType` will be set to the Blob's `type`\n * property.\n * Somex eamples for file extension to mimeType mapping:\n * .txt -> text/plain\n * .json -> application/json\n * .jpg -> image/jpeg\n * .png -> image/png\n * .mp3 -> audio/mpeg\n * .mp4 -> video/mp4\n *\n * This section can contain multiple paragraphs and code examples.\n *\n * @param params - Optional parameters specified in the\n * `types.UploadFileParameters` interface.\n * @see {@link types.UploadFileParameters#config} for the optional\n * config in the parameters.\n * @return A promise that resolves to a `types.File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n * the `mimeType` can be provided in the `params.config` parameter.\n * @throws An error occurs if a suitable upload location cannot be established.\n *\n * @example\n * The following code uploads a file to Gemini API.\n *\n * ```ts\n * const file = await ai.files.upload({file: 'file.txt', config: {\n * mimeType: 'text/plain',\n * }});\n * console.log(file.name);\n * ```\n */\n async upload(params: types.UploadFileParameters): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'Vertex AI does not support uploading files. You can share files through a GCS bucket.',\n );\n }\n\n return this.apiClient\n .uploadFile(params.file, params.config)\n .then((response) => {\n const file = converters.fileFromMldev(response);\n return file as types.File;\n });\n }\n\n /**\n * Downloads a remotely stored file asynchronously to a location specified in\n * the `params` object. This method only works on Node environment, to\n * download files in the browser, use a browser compliant method like an \n * tag.\n *\n * @param params - The parameters for the download request.\n *\n * @example\n * The following code downloads an example file named \"files/mehozpxf877d\" as\n * \"file.txt\".\n *\n * ```ts\n * await ai.files.download({file: file.name, downloadPath: 'file.txt'});\n * ```\n */\n\n async download(params: types.DownloadFileParameters): Promise {\n await this.apiClient.downloadFile(params);\n }\n\n private async listInternal(\n params: types.ListFilesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.listFilesParametersToMldev(params);\n path = common.formatMap('files', body['_url'] as Record);\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListFilesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listFilesResponseFromMldev(apiResponse);\n const typedResp = new types.ListFilesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async createInternal(\n params: types.CreateFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createFileParametersToMldev(params);\n path = common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.createFileResponseFromMldev(apiResponse);\n const typedResp = new types.CreateFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Retrieves the file information from the service.\n *\n * @param params - The parameters for the get request\n * @return The Promise that resolves to the types.File object requested.\n *\n * @example\n * ```ts\n * const config: GetFileParameters = {\n * name: fileName,\n * };\n * file = await ai.files.get(config);\n * console.log(file.name);\n * ```\n */\n async get(params: types.GetFileParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.getFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.fileFromMldev(apiResponse);\n\n return resp as types.File;\n });\n }\n }\n\n /**\n * Deletes a remotely stored file.\n *\n * @param params - The parameters for the delete request.\n * @return The DeleteFileResponse, the response for the delete method.\n *\n * @example\n * The following code deletes an example file named \"files/mehozpxf877d\".\n *\n * ```ts\n * await ai.files.delete({name: file.name});\n * ```\n */\n async delete(\n params: types.DeleteFileParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.deleteFileParametersToMldev(params);\n path = common.formatMap(\n 'files/{file}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteFileResponseFromMldev();\n const typedResp = new types.DeleteFileResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToMldev(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToMldev(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToMldev(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToMldev(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToMldev());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToMldev());\n }\n\n return toObject;\n}\n\nexport function functionResponseToMldev(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n const fromWillContinue = common.getValueByPath(fromObject, ['willContinue']);\n if (fromWillContinue != null) {\n common.setValueByPath(toObject, ['willContinue'], fromWillContinue);\n }\n\n const fromScheduling = common.getValueByPath(fromObject, ['scheduling']);\n if (fromScheduling != null) {\n common.setValueByPath(toObject, ['scheduling'], fromScheduling);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToMldev(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToMldev(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToMldev(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToMldev(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToMldev(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToMldev(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['setup', 'model'], fromModel);\n }\n\n const fromCallbacks = common.getValueByPath(fromObject, ['callbacks']);\n if (fromCallbacks != null) {\n common.setValueByPath(toObject, ['callbacks'], fromCallbacks);\n }\n\n return toObject;\n}\n\nexport function weightedPromptToMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToMldev(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigToMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToMldev(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientSetupToMldev(\n fromObject: types.LiveMusicClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentToMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToMldev(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveMusicClientSetupToMldev(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentToMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigToMldev(fromMusicGenerationConfig),\n );\n }\n\n const fromPlaybackControl = common.getValueByPath(fromObject, [\n 'playbackControl',\n ]);\n if (fromPlaybackControl != null) {\n common.setValueByPath(toObject, ['playbackControl'], fromPlaybackControl);\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToVertex(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n const fromTransparent = common.getValueByPath(fromObject, ['transparent']);\n if (fromTransparent != null) {\n common.setValueByPath(toObject, ['transparent'], fromTransparent);\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToVertex(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToVertex(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToVertex(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToVertex(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToVertex(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToVertex(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToVertex(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToVertex(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToVertex(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.LiveConnectParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function activityStartToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function activityEndToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function liveSendRealtimeInputParametersToVertex(\n fromObject: types.LiveSendRealtimeInputParameters,\n): Record {\n const toObject: Record = {};\n\n const fromMedia = common.getValueByPath(fromObject, ['media']);\n if (fromMedia != null) {\n common.setValueByPath(toObject, ['mediaChunks'], t.tBlobs(fromMedia));\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], t.tAudioBlob(fromAudio));\n }\n\n const fromAudioStreamEnd = common.getValueByPath(fromObject, [\n 'audioStreamEnd',\n ]);\n if (fromAudioStreamEnd != null) {\n common.setValueByPath(toObject, ['audioStreamEnd'], fromAudioStreamEnd);\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], t.tImageBlob(fromVideo));\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function liveClientSetupToVertex(\n fromObject: types.LiveClientSetup,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (fromGenerationConfig != null) {\n common.setValueByPath(toObject, ['generationConfig'], fromGenerationConfig);\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (fromSystemInstruction != null) {\n common.setValueByPath(\n toObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(toObject, ['tools'], transformedList);\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (fromRealtimeInputConfig != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInputConfig'],\n realtimeInputConfigToVertex(fromRealtimeInputConfig),\n );\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (fromSessionResumption != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumption'],\n sessionResumptionConfigToVertex(fromSessionResumption),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (fromContextWindowCompression != null) {\n common.setValueByPath(\n toObject,\n ['contextWindowCompression'],\n contextWindowCompressionConfigToVertex(fromContextWindowCompression),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (fromInputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (fromOutputAudioTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputAudioTranscription'],\n audioTranscriptionConfigToVertex(),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (fromProactivity != null) {\n common.setValueByPath(\n toObject,\n ['proactivity'],\n proactivityConfigToVertex(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveClientContentToVertex(\n fromObject: types.LiveClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromTurns = common.getValueByPath(fromObject, ['turns']);\n if (fromTurns != null) {\n let transformedList = fromTurns;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['turns'], transformedList);\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n return toObject;\n}\n\nexport function liveClientRealtimeInputToVertex(\n fromObject: types.LiveClientRealtimeInput,\n): Record {\n const toObject: Record = {};\n\n const fromMediaChunks = common.getValueByPath(fromObject, ['mediaChunks']);\n if (fromMediaChunks != null) {\n common.setValueByPath(toObject, ['mediaChunks'], fromMediaChunks);\n }\n\n const fromAudio = common.getValueByPath(fromObject, ['audio']);\n if (fromAudio != null) {\n common.setValueByPath(toObject, ['audio'], fromAudio);\n }\n\n if (common.getValueByPath(fromObject, ['audioStreamEnd']) !== undefined) {\n throw new Error('audioStreamEnd parameter is not supported in Vertex AI.');\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], fromVideo);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromActivityStart = common.getValueByPath(fromObject, [\n 'activityStart',\n ]);\n if (fromActivityStart != null) {\n common.setValueByPath(toObject, ['activityStart'], activityStartToVertex());\n }\n\n const fromActivityEnd = common.getValueByPath(fromObject, ['activityEnd']);\n if (fromActivityEnd != null) {\n common.setValueByPath(toObject, ['activityEnd'], activityEndToVertex());\n }\n\n return toObject;\n}\n\nexport function functionResponseToVertex(\n fromObject: types.FunctionResponse,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['willContinue']) !== undefined) {\n throw new Error('willContinue parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['scheduling']) !== undefined) {\n throw new Error('scheduling parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['data']) !== undefined) {\n throw new Error('data parameter is not supported in Vertex AI.');\n }\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n return toObject;\n}\n\nexport function liveClientToolResponseToVertex(\n fromObject: types.LiveClientToolResponse,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionResponses = common.getValueByPath(fromObject, [\n 'functionResponses',\n ]);\n if (fromFunctionResponses != null) {\n let transformedList = fromFunctionResponses;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionResponseToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionResponses'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveClientMessageToVertex(\n fromObject: types.LiveClientMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetup = common.getValueByPath(fromObject, ['setup']);\n if (fromSetup != null) {\n common.setValueByPath(\n toObject,\n ['setup'],\n liveClientSetupToVertex(fromSetup),\n );\n }\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveClientContentToVertex(fromClientContent),\n );\n }\n\n const fromRealtimeInput = common.getValueByPath(fromObject, [\n 'realtimeInput',\n ]);\n if (fromRealtimeInput != null) {\n common.setValueByPath(\n toObject,\n ['realtimeInput'],\n liveClientRealtimeInputToVertex(fromRealtimeInput),\n );\n }\n\n const fromToolResponse = common.getValueByPath(fromObject, ['toolResponse']);\n if (fromToolResponse != null) {\n common.setValueByPath(\n toObject,\n ['toolResponse'],\n liveClientToolResponseToVertex(fromToolResponse),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicConnectParametersToVertex(\n fromObject: types.LiveMusicConnectParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['model']) !== undefined) {\n throw new Error('model parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['callbacks']) !== undefined) {\n throw new Error('callbacks parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetWeightedPromptsParametersToVertex(\n fromObject: types.LiveMusicSetWeightedPromptsParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['weightedPrompts']) !== undefined) {\n throw new Error('weightedPrompts parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveMusicSetConfigParametersToVertex(\n fromObject: types.LiveMusicSetConfigParameters,\n): Record {\n const toObject: Record = {};\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicClientMessageToVertex(\n fromObject: types.LiveMusicClientMessage,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['setup']) !== undefined) {\n throw new Error('setup parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['clientContent']) !== undefined) {\n throw new Error('clientContent parameter is not supported in Vertex AI.');\n }\n\n if (\n common.getValueByPath(fromObject, ['musicGenerationConfig']) !== undefined\n ) {\n throw new Error(\n 'musicGenerationConfig parameter is not supported in Vertex AI.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['playbackControl']) !== undefined) {\n throw new Error('playbackControl parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromMldev(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromMldev(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromMldev(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromMldev(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromMldev(fromOutputTranscription),\n );\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromMldev(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromId = common.getValueByPath(fromObject, ['id']);\n if (fromId != null) {\n common.setValueByPath(toObject, ['id'], fromId);\n }\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromMldev(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromMldev(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromMldev(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromMldev(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'responseTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'responseTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromMldev(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromMldev(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromMldev(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromMldev(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromMldev(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromMldev(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromMldev(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromMldev(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromMldev(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerSetupCompleteFromMldev(): Record<\n string,\n unknown\n> {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function weightedPromptFromMldev(\n fromObject: types.WeightedPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromWeight = common.getValueByPath(fromObject, ['weight']);\n if (fromWeight != null) {\n common.setValueByPath(toObject, ['weight'], fromWeight);\n }\n\n return toObject;\n}\n\nexport function liveMusicClientContentFromMldev(\n fromObject: types.LiveMusicClientContent,\n): Record {\n const toObject: Record = {};\n\n const fromWeightedPrompts = common.getValueByPath(fromObject, [\n 'weightedPrompts',\n ]);\n if (fromWeightedPrompts != null) {\n let transformedList = fromWeightedPrompts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return weightedPromptFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['weightedPrompts'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicGenerationConfigFromMldev(\n fromObject: types.LiveMusicGenerationConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromGuidance = common.getValueByPath(fromObject, ['guidance']);\n if (fromGuidance != null) {\n common.setValueByPath(toObject, ['guidance'], fromGuidance);\n }\n\n const fromBpm = common.getValueByPath(fromObject, ['bpm']);\n if (fromBpm != null) {\n common.setValueByPath(toObject, ['bpm'], fromBpm);\n }\n\n const fromDensity = common.getValueByPath(fromObject, ['density']);\n if (fromDensity != null) {\n common.setValueByPath(toObject, ['density'], fromDensity);\n }\n\n const fromBrightness = common.getValueByPath(fromObject, ['brightness']);\n if (fromBrightness != null) {\n common.setValueByPath(toObject, ['brightness'], fromBrightness);\n }\n\n const fromScale = common.getValueByPath(fromObject, ['scale']);\n if (fromScale != null) {\n common.setValueByPath(toObject, ['scale'], fromScale);\n }\n\n const fromMuteBass = common.getValueByPath(fromObject, ['muteBass']);\n if (fromMuteBass != null) {\n common.setValueByPath(toObject, ['muteBass'], fromMuteBass);\n }\n\n const fromMuteDrums = common.getValueByPath(fromObject, ['muteDrums']);\n if (fromMuteDrums != null) {\n common.setValueByPath(toObject, ['muteDrums'], fromMuteDrums);\n }\n\n const fromOnlyBassAndDrums = common.getValueByPath(fromObject, [\n 'onlyBassAndDrums',\n ]);\n if (fromOnlyBassAndDrums != null) {\n common.setValueByPath(toObject, ['onlyBassAndDrums'], fromOnlyBassAndDrums);\n }\n\n return toObject;\n}\n\nexport function liveMusicSourceMetadataFromMldev(\n fromObject: types.LiveMusicSourceMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromClientContent = common.getValueByPath(fromObject, [\n 'clientContent',\n ]);\n if (fromClientContent != null) {\n common.setValueByPath(\n toObject,\n ['clientContent'],\n liveMusicClientContentFromMldev(fromClientContent),\n );\n }\n\n const fromMusicGenerationConfig = common.getValueByPath(fromObject, [\n 'musicGenerationConfig',\n ]);\n if (fromMusicGenerationConfig != null) {\n common.setValueByPath(\n toObject,\n ['musicGenerationConfig'],\n liveMusicGenerationConfigFromMldev(fromMusicGenerationConfig),\n );\n }\n\n return toObject;\n}\n\nexport function audioChunkFromMldev(\n fromObject: types.AudioChunk,\n): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n const fromSourceMetadata = common.getValueByPath(fromObject, [\n 'sourceMetadata',\n ]);\n if (fromSourceMetadata != null) {\n common.setValueByPath(\n toObject,\n ['sourceMetadata'],\n liveMusicSourceMetadataFromMldev(fromSourceMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerContentFromMldev(\n fromObject: types.LiveMusicServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromAudioChunks = common.getValueByPath(fromObject, ['audioChunks']);\n if (fromAudioChunks != null) {\n let transformedList = fromAudioChunks;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return audioChunkFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['audioChunks'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveMusicFilteredPromptFromMldev(\n fromObject: types.LiveMusicFilteredPrompt,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFilteredReason = common.getValueByPath(fromObject, [\n 'filteredReason',\n ]);\n if (fromFilteredReason != null) {\n common.setValueByPath(toObject, ['filteredReason'], fromFilteredReason);\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromMldev(\n fromObject: types.LiveMusicServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveMusicServerSetupCompleteFromMldev(),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveMusicServerContentFromMldev(fromServerContent),\n );\n }\n\n const fromFilteredPrompt = common.getValueByPath(fromObject, [\n 'filteredPrompt',\n ]);\n if (fromFilteredPrompt != null) {\n common.setValueByPath(\n toObject,\n ['filteredPrompt'],\n liveMusicFilteredPromptFromMldev(fromFilteredPrompt),\n );\n }\n\n return toObject;\n}\n\nexport function liveServerSetupCompleteFromVertex(\n fromObject: types.LiveServerSetupComplete,\n): Record {\n const toObject: Record = {};\n\n const fromSessionId = common.getValueByPath(fromObject, ['sessionId']);\n if (fromSessionId != null) {\n common.setValueByPath(toObject, ['sessionId'], fromSessionId);\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function transcriptionFromVertex(\n fromObject: types.Transcription,\n): Record {\n const toObject: Record = {};\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n const fromFinished = common.getValueByPath(fromObject, ['finished']);\n if (fromFinished != null) {\n common.setValueByPath(toObject, ['finished'], fromFinished);\n }\n\n return toObject;\n}\n\nexport function liveServerContentFromVertex(\n fromObject: types.LiveServerContent,\n): Record {\n const toObject: Record = {};\n\n const fromModelTurn = common.getValueByPath(fromObject, ['modelTurn']);\n if (fromModelTurn != null) {\n common.setValueByPath(\n toObject,\n ['modelTurn'],\n contentFromVertex(fromModelTurn),\n );\n }\n\n const fromTurnComplete = common.getValueByPath(fromObject, ['turnComplete']);\n if (fromTurnComplete != null) {\n common.setValueByPath(toObject, ['turnComplete'], fromTurnComplete);\n }\n\n const fromInterrupted = common.getValueByPath(fromObject, ['interrupted']);\n if (fromInterrupted != null) {\n common.setValueByPath(toObject, ['interrupted'], fromInterrupted);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromGenerationComplete = common.getValueByPath(fromObject, [\n 'generationComplete',\n ]);\n if (fromGenerationComplete != null) {\n common.setValueByPath(\n toObject,\n ['generationComplete'],\n fromGenerationComplete,\n );\n }\n\n const fromInputTranscription = common.getValueByPath(fromObject, [\n 'inputTranscription',\n ]);\n if (fromInputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['inputTranscription'],\n transcriptionFromVertex(fromInputTranscription),\n );\n }\n\n const fromOutputTranscription = common.getValueByPath(fromObject, [\n 'outputTranscription',\n ]);\n if (fromOutputTranscription != null) {\n common.setValueByPath(\n toObject,\n ['outputTranscription'],\n transcriptionFromVertex(fromOutputTranscription),\n );\n }\n\n return toObject;\n}\n\nexport function functionCallFromVertex(\n fromObject: types.FunctionCall,\n): Record {\n const toObject: Record = {};\n\n const fromArgs = common.getValueByPath(fromObject, ['args']);\n if (fromArgs != null) {\n common.setValueByPath(toObject, ['args'], fromArgs);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallFromVertex(\n fromObject: types.LiveServerToolCall,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCalls = common.getValueByPath(fromObject, [\n 'functionCalls',\n ]);\n if (fromFunctionCalls != null) {\n let transformedList = fromFunctionCalls;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionCallFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionCalls'], transformedList);\n }\n\n return toObject;\n}\n\nexport function liveServerToolCallCancellationFromVertex(\n fromObject: types.LiveServerToolCallCancellation,\n): Record {\n const toObject: Record = {};\n\n const fromIds = common.getValueByPath(fromObject, ['ids']);\n if (fromIds != null) {\n common.setValueByPath(toObject, ['ids'], fromIds);\n }\n\n return toObject;\n}\n\nexport function modalityTokenCountFromVertex(\n fromObject: types.ModalityTokenCount,\n): Record {\n const toObject: Record = {};\n\n const fromModality = common.getValueByPath(fromObject, ['modality']);\n if (fromModality != null) {\n common.setValueByPath(toObject, ['modality'], fromModality);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function usageMetadataFromVertex(\n fromObject: types.UsageMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromPromptTokenCount = common.getValueByPath(fromObject, [\n 'promptTokenCount',\n ]);\n if (fromPromptTokenCount != null) {\n common.setValueByPath(toObject, ['promptTokenCount'], fromPromptTokenCount);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n const fromResponseTokenCount = common.getValueByPath(fromObject, [\n 'candidatesTokenCount',\n ]);\n if (fromResponseTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['responseTokenCount'],\n fromResponseTokenCount,\n );\n }\n\n const fromToolUsePromptTokenCount = common.getValueByPath(fromObject, [\n 'toolUsePromptTokenCount',\n ]);\n if (fromToolUsePromptTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokenCount'],\n fromToolUsePromptTokenCount,\n );\n }\n\n const fromThoughtsTokenCount = common.getValueByPath(fromObject, [\n 'thoughtsTokenCount',\n ]);\n if (fromThoughtsTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['thoughtsTokenCount'],\n fromThoughtsTokenCount,\n );\n }\n\n const fromTotalTokenCount = common.getValueByPath(fromObject, [\n 'totalTokenCount',\n ]);\n if (fromTotalTokenCount != null) {\n common.setValueByPath(toObject, ['totalTokenCount'], fromTotalTokenCount);\n }\n\n const fromPromptTokensDetails = common.getValueByPath(fromObject, [\n 'promptTokensDetails',\n ]);\n if (fromPromptTokensDetails != null) {\n let transformedList = fromPromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['promptTokensDetails'], transformedList);\n }\n\n const fromCacheTokensDetails = common.getValueByPath(fromObject, [\n 'cacheTokensDetails',\n ]);\n if (fromCacheTokensDetails != null) {\n let transformedList = fromCacheTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['cacheTokensDetails'], transformedList);\n }\n\n const fromResponseTokensDetails = common.getValueByPath(fromObject, [\n 'candidatesTokensDetails',\n ]);\n if (fromResponseTokensDetails != null) {\n let transformedList = fromResponseTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['responseTokensDetails'], transformedList);\n }\n\n const fromToolUsePromptTokensDetails = common.getValueByPath(fromObject, [\n 'toolUsePromptTokensDetails',\n ]);\n if (fromToolUsePromptTokensDetails != null) {\n let transformedList = fromToolUsePromptTokensDetails;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modalityTokenCountFromVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['toolUsePromptTokensDetails'],\n transformedList,\n );\n }\n\n const fromTrafficType = common.getValueByPath(fromObject, ['trafficType']);\n if (fromTrafficType != null) {\n common.setValueByPath(toObject, ['trafficType'], fromTrafficType);\n }\n\n return toObject;\n}\n\nexport function liveServerGoAwayFromVertex(\n fromObject: types.LiveServerGoAway,\n): Record {\n const toObject: Record = {};\n\n const fromTimeLeft = common.getValueByPath(fromObject, ['timeLeft']);\n if (fromTimeLeft != null) {\n common.setValueByPath(toObject, ['timeLeft'], fromTimeLeft);\n }\n\n return toObject;\n}\n\nexport function liveServerSessionResumptionUpdateFromVertex(\n fromObject: types.LiveServerSessionResumptionUpdate,\n): Record {\n const toObject: Record = {};\n\n const fromNewHandle = common.getValueByPath(fromObject, ['newHandle']);\n if (fromNewHandle != null) {\n common.setValueByPath(toObject, ['newHandle'], fromNewHandle);\n }\n\n const fromResumable = common.getValueByPath(fromObject, ['resumable']);\n if (fromResumable != null) {\n common.setValueByPath(toObject, ['resumable'], fromResumable);\n }\n\n const fromLastConsumedClientMessageIndex = common.getValueByPath(fromObject, [\n 'lastConsumedClientMessageIndex',\n ]);\n if (fromLastConsumedClientMessageIndex != null) {\n common.setValueByPath(\n toObject,\n ['lastConsumedClientMessageIndex'],\n fromLastConsumedClientMessageIndex,\n );\n }\n\n return toObject;\n}\n\nexport function liveServerMessageFromVertex(\n fromObject: types.LiveServerMessage,\n): Record {\n const toObject: Record = {};\n\n const fromSetupComplete = common.getValueByPath(fromObject, [\n 'setupComplete',\n ]);\n if (fromSetupComplete != null) {\n common.setValueByPath(\n toObject,\n ['setupComplete'],\n liveServerSetupCompleteFromVertex(fromSetupComplete),\n );\n }\n\n const fromServerContent = common.getValueByPath(fromObject, [\n 'serverContent',\n ]);\n if (fromServerContent != null) {\n common.setValueByPath(\n toObject,\n ['serverContent'],\n liveServerContentFromVertex(fromServerContent),\n );\n }\n\n const fromToolCall = common.getValueByPath(fromObject, ['toolCall']);\n if (fromToolCall != null) {\n common.setValueByPath(\n toObject,\n ['toolCall'],\n liveServerToolCallFromVertex(fromToolCall),\n );\n }\n\n const fromToolCallCancellation = common.getValueByPath(fromObject, [\n 'toolCallCancellation',\n ]);\n if (fromToolCallCancellation != null) {\n common.setValueByPath(\n toObject,\n ['toolCallCancellation'],\n liveServerToolCallCancellationFromVertex(fromToolCallCancellation),\n );\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(\n toObject,\n ['usageMetadata'],\n usageMetadataFromVertex(fromUsageMetadata),\n );\n }\n\n const fromGoAway = common.getValueByPath(fromObject, ['goAway']);\n if (fromGoAway != null) {\n common.setValueByPath(\n toObject,\n ['goAway'],\n liveServerGoAwayFromVertex(fromGoAway),\n );\n }\n\n const fromSessionResumptionUpdate = common.getValueByPath(fromObject, [\n 'sessionResumptionUpdate',\n ]);\n if (fromSessionResumptionUpdate != null) {\n common.setValueByPath(\n toObject,\n ['sessionResumptionUpdate'],\n liveServerSessionResumptionUpdateFromVertex(fromSessionResumptionUpdate),\n );\n }\n\n return toObject;\n}\n\nexport function liveMusicServerMessageFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as _internal_types from '../_internal_types.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToMldev(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function safetySettingToMldev(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['method']) !== undefined) {\n throw new Error('method parameter is not supported in Gemini API.');\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToMldev(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToMldev(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToMldev(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToMldev(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToMldev(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToMldev(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToMldev(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToMldev(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToMldev(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n if (common.getValueByPath(fromObject, ['routingConfig']) !== undefined) {\n throw new Error('routingConfig parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['modelSelectionConfig']) !== undefined\n ) {\n throw new Error(\n 'modelSelectionConfig parameter is not supported in Gemini API.',\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToMldev(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToMldev(fromToolConfig),\n );\n }\n\n if (common.getValueByPath(fromObject, ['labels']) !== undefined) {\n throw new Error('labels parameter is not supported in Gemini API.');\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToMldev(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n if (common.getValueByPath(fromObject, ['audioTimestamp']) !== undefined) {\n throw new Error('audioTimestamp parameter is not supported in Gemini API.');\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToMldev(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToMldev(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'taskType'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['requests[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['requests[]', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['mimeType']) !== undefined) {\n throw new Error('mimeType parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['autoTruncate']) !== undefined) {\n throw new Error('autoTruncate parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToMldev(fromConfig, toObject),\n );\n }\n\n const fromModelForEmbedContent = common.getValueByPath(fromObject, ['model']);\n if (fromModelForEmbedContent !== undefined) {\n common.setValueByPath(\n toObject,\n ['requests[]', 'model'],\n t.tModel(apiClient, fromModelForEmbedContent),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToMldev(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['negativePrompt']) !== undefined) {\n throw new Error('negativePrompt parameter is not supported in Gemini API.');\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n if (common.getValueByPath(fromObject, ['addWatermark']) !== undefined) {\n throw new Error('addWatermark parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['imageSize']) !== undefined) {\n throw new Error('imageSize parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['enhancePrompt']) !== undefined) {\n throw new Error('enhancePrompt parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToMldev(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToMldev(\n fromObject: types.CountTokensConfig,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['systemInstruction']) !== undefined) {\n throw new Error(\n 'systemInstruction parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['tools']) !== undefined) {\n throw new Error('tools parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['generationConfig']) !== undefined) {\n throw new Error(\n 'generationConfig parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToMldev(fromConfig),\n );\n }\n\n return toObject;\n}\n\nexport function imageToMldev(fromObject: types.Image): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToMldev(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n if (common.getValueByPath(fromObject, ['outputGcsUri']) !== undefined) {\n throw new Error('outputGcsUri parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['fps']) !== undefined) {\n throw new Error('fps parameter is not supported in Gemini API.');\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n if (common.getValueByPath(fromObject, ['seed']) !== undefined) {\n throw new Error('seed parameter is not supported in Gemini API.');\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n if (common.getValueByPath(fromObject, ['resolution']) !== undefined) {\n throw new Error('resolution parameter is not supported in Gemini API.');\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n if (common.getValueByPath(fromObject, ['pubsubTopic']) !== undefined) {\n throw new Error('pubsubTopic parameter is not supported in Gemini API.');\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n if (common.getValueByPath(fromObject, ['generateAudio']) !== undefined) {\n throw new Error('generateAudio parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['lastFrame']) !== undefined) {\n throw new Error('lastFrame parameter is not supported in Gemini API.');\n }\n\n if (common.getValueByPath(fromObject, ['compressionQuality']) !== undefined) {\n throw new Error(\n 'compressionQuality parameter is not supported in Gemini API.',\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToMldev(fromImage),\n );\n }\n\n if (common.getValueByPath(fromObject, ['video']) !== undefined) {\n throw new Error('video parameter is not supported in Gemini API.');\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataToVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToVertex(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToVertex(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function schemaToVertex(\n fromObject: types.Schema,\n): Record {\n const toObject: Record = {};\n\n const fromAnyOf = common.getValueByPath(fromObject, ['anyOf']);\n if (fromAnyOf != null) {\n common.setValueByPath(toObject, ['anyOf'], fromAnyOf);\n }\n\n const fromDefault = common.getValueByPath(fromObject, ['default']);\n if (fromDefault != null) {\n common.setValueByPath(toObject, ['default'], fromDefault);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromEnum = common.getValueByPath(fromObject, ['enum']);\n if (fromEnum != null) {\n common.setValueByPath(toObject, ['enum'], fromEnum);\n }\n\n const fromExample = common.getValueByPath(fromObject, ['example']);\n if (fromExample != null) {\n common.setValueByPath(toObject, ['example'], fromExample);\n }\n\n const fromFormat = common.getValueByPath(fromObject, ['format']);\n if (fromFormat != null) {\n common.setValueByPath(toObject, ['format'], fromFormat);\n }\n\n const fromItems = common.getValueByPath(fromObject, ['items']);\n if (fromItems != null) {\n common.setValueByPath(toObject, ['items'], fromItems);\n }\n\n const fromMaxItems = common.getValueByPath(fromObject, ['maxItems']);\n if (fromMaxItems != null) {\n common.setValueByPath(toObject, ['maxItems'], fromMaxItems);\n }\n\n const fromMaxLength = common.getValueByPath(fromObject, ['maxLength']);\n if (fromMaxLength != null) {\n common.setValueByPath(toObject, ['maxLength'], fromMaxLength);\n }\n\n const fromMaxProperties = common.getValueByPath(fromObject, [\n 'maxProperties',\n ]);\n if (fromMaxProperties != null) {\n common.setValueByPath(toObject, ['maxProperties'], fromMaxProperties);\n }\n\n const fromMaximum = common.getValueByPath(fromObject, ['maximum']);\n if (fromMaximum != null) {\n common.setValueByPath(toObject, ['maximum'], fromMaximum);\n }\n\n const fromMinItems = common.getValueByPath(fromObject, ['minItems']);\n if (fromMinItems != null) {\n common.setValueByPath(toObject, ['minItems'], fromMinItems);\n }\n\n const fromMinLength = common.getValueByPath(fromObject, ['minLength']);\n if (fromMinLength != null) {\n common.setValueByPath(toObject, ['minLength'], fromMinLength);\n }\n\n const fromMinProperties = common.getValueByPath(fromObject, [\n 'minProperties',\n ]);\n if (fromMinProperties != null) {\n common.setValueByPath(toObject, ['minProperties'], fromMinProperties);\n }\n\n const fromMinimum = common.getValueByPath(fromObject, ['minimum']);\n if (fromMinimum != null) {\n common.setValueByPath(toObject, ['minimum'], fromMinimum);\n }\n\n const fromNullable = common.getValueByPath(fromObject, ['nullable']);\n if (fromNullable != null) {\n common.setValueByPath(toObject, ['nullable'], fromNullable);\n }\n\n const fromPattern = common.getValueByPath(fromObject, ['pattern']);\n if (fromPattern != null) {\n common.setValueByPath(toObject, ['pattern'], fromPattern);\n }\n\n const fromProperties = common.getValueByPath(fromObject, ['properties']);\n if (fromProperties != null) {\n common.setValueByPath(toObject, ['properties'], fromProperties);\n }\n\n const fromPropertyOrdering = common.getValueByPath(fromObject, [\n 'propertyOrdering',\n ]);\n if (fromPropertyOrdering != null) {\n common.setValueByPath(toObject, ['propertyOrdering'], fromPropertyOrdering);\n }\n\n const fromRequired = common.getValueByPath(fromObject, ['required']);\n if (fromRequired != null) {\n common.setValueByPath(toObject, ['required'], fromRequired);\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (fromTitle != null) {\n common.setValueByPath(toObject, ['title'], fromTitle);\n }\n\n const fromType = common.getValueByPath(fromObject, ['type']);\n if (fromType != null) {\n common.setValueByPath(toObject, ['type'], fromType);\n }\n\n return toObject;\n}\n\nexport function modelSelectionConfigToVertex(\n fromObject: types.ModelSelectionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFeatureSelectionPreference = common.getValueByPath(fromObject, [\n 'featureSelectionPreference',\n ]);\n if (fromFeatureSelectionPreference != null) {\n common.setValueByPath(\n toObject,\n ['featureSelectionPreference'],\n fromFeatureSelectionPreference,\n );\n }\n\n return toObject;\n}\n\nexport function safetySettingToVertex(\n fromObject: types.SafetySetting,\n): Record {\n const toObject: Record = {};\n\n const fromMethod = common.getValueByPath(fromObject, ['method']);\n if (fromMethod != null) {\n common.setValueByPath(toObject, ['method'], fromMethod);\n }\n\n const fromCategory = common.getValueByPath(fromObject, ['category']);\n if (fromCategory != null) {\n common.setValueByPath(toObject, ['category'], fromCategory);\n }\n\n const fromThreshold = common.getValueByPath(fromObject, ['threshold']);\n if (fromThreshold != null) {\n common.setValueByPath(toObject, ['threshold'], fromThreshold);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToVertex(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['behavior']) !== undefined) {\n throw new Error('behavior parameter is not supported in Vertex AI.');\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToVertex(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToVertex(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToVertex(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToVertex(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToVertex(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToVertex(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function enterpriseWebSearchToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function apiKeyConfigToVertex(\n fromObject: types.ApiKeyConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyString = common.getValueByPath(fromObject, ['apiKeyString']);\n if (fromApiKeyString != null) {\n common.setValueByPath(toObject, ['apiKeyString'], fromApiKeyString);\n }\n\n return toObject;\n}\n\nexport function authConfigToVertex(\n fromObject: types.AuthConfig,\n): Record {\n const toObject: Record = {};\n\n const fromApiKeyConfig = common.getValueByPath(fromObject, ['apiKeyConfig']);\n if (fromApiKeyConfig != null) {\n common.setValueByPath(\n toObject,\n ['apiKeyConfig'],\n apiKeyConfigToVertex(fromApiKeyConfig),\n );\n }\n\n const fromAuthType = common.getValueByPath(fromObject, ['authType']);\n if (fromAuthType != null) {\n common.setValueByPath(toObject, ['authType'], fromAuthType);\n }\n\n const fromGoogleServiceAccountConfig = common.getValueByPath(fromObject, [\n 'googleServiceAccountConfig',\n ]);\n if (fromGoogleServiceAccountConfig != null) {\n common.setValueByPath(\n toObject,\n ['googleServiceAccountConfig'],\n fromGoogleServiceAccountConfig,\n );\n }\n\n const fromHttpBasicAuthConfig = common.getValueByPath(fromObject, [\n 'httpBasicAuthConfig',\n ]);\n if (fromHttpBasicAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['httpBasicAuthConfig'],\n fromHttpBasicAuthConfig,\n );\n }\n\n const fromOauthConfig = common.getValueByPath(fromObject, ['oauthConfig']);\n if (fromOauthConfig != null) {\n common.setValueByPath(toObject, ['oauthConfig'], fromOauthConfig);\n }\n\n const fromOidcConfig = common.getValueByPath(fromObject, ['oidcConfig']);\n if (fromOidcConfig != null) {\n common.setValueByPath(toObject, ['oidcConfig'], fromOidcConfig);\n }\n\n return toObject;\n}\n\nexport function googleMapsToVertex(\n fromObject: types.GoogleMaps,\n): Record {\n const toObject: Record = {};\n\n const fromAuthConfig = common.getValueByPath(fromObject, ['authConfig']);\n if (fromAuthConfig != null) {\n common.setValueByPath(\n toObject,\n ['authConfig'],\n authConfigToVertex(fromAuthConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolToVertex(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n const fromRetrieval = common.getValueByPath(fromObject, ['retrieval']);\n if (fromRetrieval != null) {\n common.setValueByPath(toObject, ['retrieval'], fromRetrieval);\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToVertex(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToVertex(fromGoogleSearchRetrieval),\n );\n }\n\n const fromEnterpriseWebSearch = common.getValueByPath(fromObject, [\n 'enterpriseWebSearch',\n ]);\n if (fromEnterpriseWebSearch != null) {\n common.setValueByPath(\n toObject,\n ['enterpriseWebSearch'],\n enterpriseWebSearchToVertex(),\n );\n }\n\n const fromGoogleMaps = common.getValueByPath(fromObject, ['googleMaps']);\n if (fromGoogleMaps != null) {\n common.setValueByPath(\n toObject,\n ['googleMaps'],\n googleMapsToVertex(fromGoogleMaps),\n );\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToVertex());\n }\n\n if (common.getValueByPath(fromObject, ['computerUse']) !== undefined) {\n throw new Error('computerUse parameter is not supported in Vertex AI.');\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function functionCallingConfigToVertex(\n fromObject: types.FunctionCallingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromAllowedFunctionNames = common.getValueByPath(fromObject, [\n 'allowedFunctionNames',\n ]);\n if (fromAllowedFunctionNames != null) {\n common.setValueByPath(\n toObject,\n ['allowedFunctionNames'],\n fromAllowedFunctionNames,\n );\n }\n\n return toObject;\n}\n\nexport function latLngToVertex(\n fromObject: types.LatLng,\n): Record {\n const toObject: Record = {};\n\n const fromLatitude = common.getValueByPath(fromObject, ['latitude']);\n if (fromLatitude != null) {\n common.setValueByPath(toObject, ['latitude'], fromLatitude);\n }\n\n const fromLongitude = common.getValueByPath(fromObject, ['longitude']);\n if (fromLongitude != null) {\n common.setValueByPath(toObject, ['longitude'], fromLongitude);\n }\n\n return toObject;\n}\n\nexport function retrievalConfigToVertex(\n fromObject: types.RetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromLatLng = common.getValueByPath(fromObject, ['latLng']);\n if (fromLatLng != null) {\n common.setValueByPath(toObject, ['latLng'], latLngToVertex(fromLatLng));\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function toolConfigToVertex(\n fromObject: types.ToolConfig,\n): Record {\n const toObject: Record = {};\n\n const fromFunctionCallingConfig = common.getValueByPath(fromObject, [\n 'functionCallingConfig',\n ]);\n if (fromFunctionCallingConfig != null) {\n common.setValueByPath(\n toObject,\n ['functionCallingConfig'],\n functionCallingConfigToVertex(fromFunctionCallingConfig),\n );\n }\n\n const fromRetrievalConfig = common.getValueByPath(fromObject, [\n 'retrievalConfig',\n ]);\n if (fromRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['retrievalConfig'],\n retrievalConfigToVertex(fromRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function prebuiltVoiceConfigToVertex(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToVertex(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToVertex(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speechConfigToVertex(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToVertex(fromVoiceConfig),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['multiSpeakerVoiceConfig']) !== undefined\n ) {\n throw new Error(\n 'multiSpeakerVoiceConfig parameter is not supported in Vertex AI.',\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function thinkingConfigToVertex(\n fromObject: types.ThinkingConfig,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeThoughts = common.getValueByPath(fromObject, [\n 'includeThoughts',\n ]);\n if (fromIncludeThoughts != null) {\n common.setValueByPath(toObject, ['includeThoughts'], fromIncludeThoughts);\n }\n\n const fromThinkingBudget = common.getValueByPath(fromObject, [\n 'thinkingBudget',\n ]);\n if (fromThinkingBudget != null) {\n common.setValueByPath(toObject, ['thinkingBudget'], fromThinkingBudget);\n }\n\n return toObject;\n}\n\nexport function generateContentConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (fromTemperature != null) {\n common.setValueByPath(toObject, ['temperature'], fromTemperature);\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (fromTopP != null) {\n common.setValueByPath(toObject, ['topP'], fromTopP);\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (fromTopK != null) {\n common.setValueByPath(toObject, ['topK'], fromTopK);\n }\n\n const fromCandidateCount = common.getValueByPath(fromObject, [\n 'candidateCount',\n ]);\n if (fromCandidateCount != null) {\n common.setValueByPath(toObject, ['candidateCount'], fromCandidateCount);\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (fromMaxOutputTokens != null) {\n common.setValueByPath(toObject, ['maxOutputTokens'], fromMaxOutputTokens);\n }\n\n const fromStopSequences = common.getValueByPath(fromObject, [\n 'stopSequences',\n ]);\n if (fromStopSequences != null) {\n common.setValueByPath(toObject, ['stopSequences'], fromStopSequences);\n }\n\n const fromResponseLogprobs = common.getValueByPath(fromObject, [\n 'responseLogprobs',\n ]);\n if (fromResponseLogprobs != null) {\n common.setValueByPath(toObject, ['responseLogprobs'], fromResponseLogprobs);\n }\n\n const fromLogprobs = common.getValueByPath(fromObject, ['logprobs']);\n if (fromLogprobs != null) {\n common.setValueByPath(toObject, ['logprobs'], fromLogprobs);\n }\n\n const fromPresencePenalty = common.getValueByPath(fromObject, [\n 'presencePenalty',\n ]);\n if (fromPresencePenalty != null) {\n common.setValueByPath(toObject, ['presencePenalty'], fromPresencePenalty);\n }\n\n const fromFrequencyPenalty = common.getValueByPath(fromObject, [\n 'frequencyPenalty',\n ]);\n if (fromFrequencyPenalty != null) {\n common.setValueByPath(toObject, ['frequencyPenalty'], fromFrequencyPenalty);\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (fromSeed != null) {\n common.setValueByPath(toObject, ['seed'], fromSeed);\n }\n\n const fromResponseMimeType = common.getValueByPath(fromObject, [\n 'responseMimeType',\n ]);\n if (fromResponseMimeType != null) {\n common.setValueByPath(toObject, ['responseMimeType'], fromResponseMimeType);\n }\n\n const fromResponseSchema = common.getValueByPath(fromObject, [\n 'responseSchema',\n ]);\n if (fromResponseSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseSchema'],\n schemaToVertex(t.tSchema(fromResponseSchema)),\n );\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n const fromRoutingConfig = common.getValueByPath(fromObject, [\n 'routingConfig',\n ]);\n if (fromRoutingConfig != null) {\n common.setValueByPath(toObject, ['routingConfig'], fromRoutingConfig);\n }\n\n const fromModelSelectionConfig = common.getValueByPath(fromObject, [\n 'modelSelectionConfig',\n ]);\n if (fromModelSelectionConfig != null) {\n common.setValueByPath(\n toObject,\n ['modelConfig'],\n modelSelectionConfigToVertex(fromModelSelectionConfig),\n );\n }\n\n const fromSafetySettings = common.getValueByPath(fromObject, [\n 'safetySettings',\n ]);\n if (parentObject !== undefined && fromSafetySettings != null) {\n let transformedList = fromSafetySettings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return safetySettingToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['safetySettings'], transformedList);\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromToolConfig = common.getValueByPath(fromObject, ['toolConfig']);\n if (parentObject !== undefined && fromToolConfig != null) {\n common.setValueByPath(\n parentObject,\n ['toolConfig'],\n toolConfigToVertex(fromToolConfig),\n );\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (parentObject !== undefined && fromLabels != null) {\n common.setValueByPath(parentObject, ['labels'], fromLabels);\n }\n\n const fromCachedContent = common.getValueByPath(fromObject, [\n 'cachedContent',\n ]);\n if (parentObject !== undefined && fromCachedContent != null) {\n common.setValueByPath(\n parentObject,\n ['cachedContent'],\n t.tCachedContentName(apiClient, fromCachedContent),\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (fromResponseModalities != null) {\n common.setValueByPath(\n toObject,\n ['responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (fromMediaResolution != null) {\n common.setValueByPath(toObject, ['mediaResolution'], fromMediaResolution);\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (fromSpeechConfig != null) {\n common.setValueByPath(\n toObject,\n ['speechConfig'],\n speechConfigToVertex(t.tSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromAudioTimestamp = common.getValueByPath(fromObject, [\n 'audioTimestamp',\n ]);\n if (fromAudioTimestamp != null) {\n common.setValueByPath(toObject, ['audioTimestamp'], fromAudioTimestamp);\n }\n\n const fromThinkingConfig = common.getValueByPath(fromObject, [\n 'thinkingConfig',\n ]);\n if (fromThinkingConfig != null) {\n common.setValueByPath(\n toObject,\n ['thinkingConfig'],\n thinkingConfigToVertex(fromThinkingConfig),\n );\n }\n\n return toObject;\n}\n\nexport function generateContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['generationConfig'],\n generateContentConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentConfigToVertex(\n fromObject: types.EmbedContentConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromTaskType = common.getValueByPath(fromObject, ['taskType']);\n if (parentObject !== undefined && fromTaskType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'task_type'],\n fromTaskType,\n );\n }\n\n const fromTitle = common.getValueByPath(fromObject, ['title']);\n if (parentObject !== undefined && fromTitle != null) {\n common.setValueByPath(parentObject, ['instances[]', 'title'], fromTitle);\n }\n\n const fromOutputDimensionality = common.getValueByPath(fromObject, [\n 'outputDimensionality',\n ]);\n if (parentObject !== undefined && fromOutputDimensionality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputDimensionality'],\n fromOutputDimensionality,\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (parentObject !== undefined && fromMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['instances[]', 'mimeType'],\n fromMimeType,\n );\n }\n\n const fromAutoTruncate = common.getValueByPath(fromObject, ['autoTruncate']);\n if (parentObject !== undefined && fromAutoTruncate != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'autoTruncate'],\n fromAutoTruncate,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.EmbedContentParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n common.setValueByPath(\n toObject,\n ['instances[]', 'content'],\n t.tContentsForEmbed(apiClient, fromContents),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n embedContentConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesConfigToVertex(\n fromObject: types.GenerateImagesConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromImageSize = common.getValueByPath(fromObject, ['imageSize']);\n if (parentObject !== undefined && fromImageSize != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleImageSize'],\n fromImageSize,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateImagesParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateImagesConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function imageToVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, ['imageBytes']);\n if (fromImageBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromImageBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function maskReferenceConfigToVertex(\n fromObject: types.MaskReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMaskMode = common.getValueByPath(fromObject, ['maskMode']);\n if (fromMaskMode != null) {\n common.setValueByPath(toObject, ['maskMode'], fromMaskMode);\n }\n\n const fromSegmentationClasses = common.getValueByPath(fromObject, [\n 'segmentationClasses',\n ]);\n if (fromSegmentationClasses != null) {\n common.setValueByPath(toObject, ['maskClasses'], fromSegmentationClasses);\n }\n\n const fromMaskDilation = common.getValueByPath(fromObject, ['maskDilation']);\n if (fromMaskDilation != null) {\n common.setValueByPath(toObject, ['dilation'], fromMaskDilation);\n }\n\n return toObject;\n}\n\nexport function controlReferenceConfigToVertex(\n fromObject: types.ControlReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromControlType = common.getValueByPath(fromObject, ['controlType']);\n if (fromControlType != null) {\n common.setValueByPath(toObject, ['controlType'], fromControlType);\n }\n\n const fromEnableControlImageComputation = common.getValueByPath(fromObject, [\n 'enableControlImageComputation',\n ]);\n if (fromEnableControlImageComputation != null) {\n common.setValueByPath(\n toObject,\n ['computeControl'],\n fromEnableControlImageComputation,\n );\n }\n\n return toObject;\n}\n\nexport function styleReferenceConfigToVertex(\n fromObject: types.StyleReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromStyleDescription = common.getValueByPath(fromObject, [\n 'styleDescription',\n ]);\n if (fromStyleDescription != null) {\n common.setValueByPath(toObject, ['styleDescription'], fromStyleDescription);\n }\n\n return toObject;\n}\n\nexport function subjectReferenceConfigToVertex(\n fromObject: types.SubjectReferenceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSubjectType = common.getValueByPath(fromObject, ['subjectType']);\n if (fromSubjectType != null) {\n common.setValueByPath(toObject, ['subjectType'], fromSubjectType);\n }\n\n const fromSubjectDescription = common.getValueByPath(fromObject, [\n 'subjectDescription',\n ]);\n if (fromSubjectDescription != null) {\n common.setValueByPath(\n toObject,\n ['subjectDescription'],\n fromSubjectDescription,\n );\n }\n\n return toObject;\n}\n\nexport function referenceImageAPIInternalToVertex(\n fromObject: _internal_types.ReferenceImageAPIInternal,\n): Record {\n const toObject: Record = {};\n\n const fromReferenceImage = common.getValueByPath(fromObject, [\n 'referenceImage',\n ]);\n if (fromReferenceImage != null) {\n common.setValueByPath(\n toObject,\n ['referenceImage'],\n imageToVertex(fromReferenceImage),\n );\n }\n\n const fromReferenceId = common.getValueByPath(fromObject, ['referenceId']);\n if (fromReferenceId != null) {\n common.setValueByPath(toObject, ['referenceId'], fromReferenceId);\n }\n\n const fromReferenceType = common.getValueByPath(fromObject, [\n 'referenceType',\n ]);\n if (fromReferenceType != null) {\n common.setValueByPath(toObject, ['referenceType'], fromReferenceType);\n }\n\n const fromMaskImageConfig = common.getValueByPath(fromObject, [\n 'maskImageConfig',\n ]);\n if (fromMaskImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['maskImageConfig'],\n maskReferenceConfigToVertex(fromMaskImageConfig),\n );\n }\n\n const fromControlImageConfig = common.getValueByPath(fromObject, [\n 'controlImageConfig',\n ]);\n if (fromControlImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['controlImageConfig'],\n controlReferenceConfigToVertex(fromControlImageConfig),\n );\n }\n\n const fromStyleImageConfig = common.getValueByPath(fromObject, [\n 'styleImageConfig',\n ]);\n if (fromStyleImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['styleImageConfig'],\n styleReferenceConfigToVertex(fromStyleImageConfig),\n );\n }\n\n const fromSubjectImageConfig = common.getValueByPath(fromObject, [\n 'subjectImageConfig',\n ]);\n if (fromSubjectImageConfig != null) {\n common.setValueByPath(\n toObject,\n ['subjectImageConfig'],\n subjectReferenceConfigToVertex(fromSubjectImageConfig),\n );\n }\n\n return toObject;\n}\n\nexport function editImageConfigToVertex(\n fromObject: types.EditImageConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromGuidanceScale = common.getValueByPath(fromObject, [\n 'guidanceScale',\n ]);\n if (parentObject !== undefined && fromGuidanceScale != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'guidanceScale'],\n fromGuidanceScale,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromSafetyFilterLevel = common.getValueByPath(fromObject, [\n 'safetyFilterLevel',\n ]);\n if (parentObject !== undefined && fromSafetyFilterLevel != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'safetySetting'],\n fromSafetyFilterLevel,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromIncludeSafetyAttributes = common.getValueByPath(fromObject, [\n 'includeSafetyAttributes',\n ]);\n if (parentObject !== undefined && fromIncludeSafetyAttributes != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeSafetyAttributes'],\n fromIncludeSafetyAttributes,\n );\n }\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromLanguage = common.getValueByPath(fromObject, ['language']);\n if (parentObject !== undefined && fromLanguage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'language'],\n fromLanguage,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromAddWatermark = common.getValueByPath(fromObject, ['addWatermark']);\n if (parentObject !== undefined && fromAddWatermark != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'addWatermark'],\n fromAddWatermark,\n );\n }\n\n const fromEditMode = common.getValueByPath(fromObject, ['editMode']);\n if (parentObject !== undefined && fromEditMode != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editMode'],\n fromEditMode,\n );\n }\n\n const fromBaseSteps = common.getValueByPath(fromObject, ['baseSteps']);\n if (parentObject !== undefined && fromBaseSteps != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'editConfig', 'baseSteps'],\n fromBaseSteps,\n );\n }\n\n return toObject;\n}\n\nexport function editImageParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.EditImageParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromReferenceImages = common.getValueByPath(fromObject, [\n 'referenceImages',\n ]);\n if (fromReferenceImages != null) {\n let transformedList = fromReferenceImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return referenceImageAPIInternalToVertex(item);\n });\n }\n common.setValueByPath(\n toObject,\n ['instances[0]', 'referenceImages'],\n transformedList,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n editImageConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIConfigInternalToVertex(\n fromObject: _internal_types.UpscaleImageAPIConfigInternal,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromIncludeRaiReason = common.getValueByPath(fromObject, [\n 'includeRaiReason',\n ]);\n if (parentObject !== undefined && fromIncludeRaiReason != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'includeRaiReason'],\n fromIncludeRaiReason,\n );\n }\n\n const fromOutputMimeType = common.getValueByPath(fromObject, [\n 'outputMimeType',\n ]);\n if (parentObject !== undefined && fromOutputMimeType != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'mimeType'],\n fromOutputMimeType,\n );\n }\n\n const fromOutputCompressionQuality = common.getValueByPath(fromObject, [\n 'outputCompressionQuality',\n ]);\n if (parentObject !== undefined && fromOutputCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'outputOptions', 'compressionQuality'],\n fromOutputCompressionQuality,\n );\n }\n\n const fromEnhanceInputImage = common.getValueByPath(fromObject, [\n 'enhanceInputImage',\n ]);\n if (parentObject !== undefined && fromEnhanceInputImage != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'enhanceInputImage'],\n fromEnhanceInputImage,\n );\n }\n\n const fromImagePreservationFactor = common.getValueByPath(fromObject, [\n 'imagePreservationFactor',\n ]);\n if (parentObject !== undefined && fromImagePreservationFactor != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'upscaleConfig', 'imagePreservationFactor'],\n fromImagePreservationFactor,\n );\n }\n\n const fromNumberOfImages = common.getValueByPath(fromObject, [\n 'numberOfImages',\n ]);\n if (parentObject !== undefined && fromNumberOfImages != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfImages,\n );\n }\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (parentObject !== undefined && fromMode != null) {\n common.setValueByPath(parentObject, ['parameters', 'mode'], fromMode);\n }\n\n return toObject;\n}\n\nexport function upscaleImageAPIParametersInternalToVertex(\n apiClient: ApiClient,\n fromObject: _internal_types.UpscaleImageAPIParametersInternal,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromUpscaleFactor = common.getValueByPath(fromObject, [\n 'upscaleFactor',\n ]);\n if (fromUpscaleFactor != null) {\n common.setValueByPath(\n toObject,\n ['parameters', 'upscaleConfig', 'upscaleFactor'],\n fromUpscaleFactor,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n upscaleImageAPIConfigInternalToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GetModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listModelsConfigToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n const fromQueryBase = common.getValueByPath(fromObject, ['queryBase']);\n if (parentObject !== undefined && fromQueryBase != null) {\n common.setValueByPath(\n parentObject,\n ['_url', 'models_url'],\n t.tModelsUrl(apiClient, fromQueryBase),\n );\n }\n\n return toObject;\n}\n\nexport function listModelsParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ListModelsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listModelsConfigToVertex(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function updateModelConfigToVertex(\n fromObject: types.UpdateModelConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (parentObject !== undefined && fromDisplayName != null) {\n common.setValueByPath(parentObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (parentObject !== undefined && fromDefaultCheckpointId != null) {\n common.setValueByPath(\n parentObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n return toObject;\n}\n\nexport function updateModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.UpdateModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n updateModelConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function deleteModelParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.DeleteModelParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'name'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function countTokensConfigToVertex(\n fromObject: types.CountTokensConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['systemInstruction'],\n contentToVertex(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = fromTools;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToVertex(item);\n });\n }\n common.setValueByPath(parentObject, ['tools'], transformedList);\n }\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['generationConfig'],\n fromGenerationConfig,\n );\n }\n\n return toObject;\n}\n\nexport function countTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.CountTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n countTokensConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function computeTokensParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.ComputeTokensParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromContents = common.getValueByPath(fromObject, ['contents']);\n if (fromContents != null) {\n let transformedList = t.tContents(fromContents);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentToVertex(item);\n });\n }\n common.setValueByPath(toObject, ['contents'], transformedList);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function videoToVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, ['videoBytes']);\n if (fromVideoBytes != null) {\n common.setValueByPath(\n toObject,\n ['bytesBase64Encoded'],\n t.tBytes(fromVideoBytes),\n );\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generateVideosSourceToVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function generateVideosConfigToVertex(\n fromObject: types.GenerateVideosConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromNumberOfVideos = common.getValueByPath(fromObject, [\n 'numberOfVideos',\n ]);\n if (parentObject !== undefined && fromNumberOfVideos != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'sampleCount'],\n fromNumberOfVideos,\n );\n }\n\n const fromOutputGcsUri = common.getValueByPath(fromObject, ['outputGcsUri']);\n if (parentObject !== undefined && fromOutputGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'storageUri'],\n fromOutputGcsUri,\n );\n }\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (parentObject !== undefined && fromFps != null) {\n common.setValueByPath(parentObject, ['parameters', 'fps'], fromFps);\n }\n\n const fromDurationSeconds = common.getValueByPath(fromObject, [\n 'durationSeconds',\n ]);\n if (parentObject !== undefined && fromDurationSeconds != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'durationSeconds'],\n fromDurationSeconds,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(parentObject, ['parameters', 'seed'], fromSeed);\n }\n\n const fromAspectRatio = common.getValueByPath(fromObject, ['aspectRatio']);\n if (parentObject !== undefined && fromAspectRatio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'aspectRatio'],\n fromAspectRatio,\n );\n }\n\n const fromResolution = common.getValueByPath(fromObject, ['resolution']);\n if (parentObject !== undefined && fromResolution != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'resolution'],\n fromResolution,\n );\n }\n\n const fromPersonGeneration = common.getValueByPath(fromObject, [\n 'personGeneration',\n ]);\n if (parentObject !== undefined && fromPersonGeneration != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'personGeneration'],\n fromPersonGeneration,\n );\n }\n\n const fromPubsubTopic = common.getValueByPath(fromObject, ['pubsubTopic']);\n if (parentObject !== undefined && fromPubsubTopic != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'pubsubTopic'],\n fromPubsubTopic,\n );\n }\n\n const fromNegativePrompt = common.getValueByPath(fromObject, [\n 'negativePrompt',\n ]);\n if (parentObject !== undefined && fromNegativePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'negativePrompt'],\n fromNegativePrompt,\n );\n }\n\n const fromEnhancePrompt = common.getValueByPath(fromObject, [\n 'enhancePrompt',\n ]);\n if (parentObject !== undefined && fromEnhancePrompt != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'enhancePrompt'],\n fromEnhancePrompt,\n );\n }\n\n const fromGenerateAudio = common.getValueByPath(fromObject, [\n 'generateAudio',\n ]);\n if (parentObject !== undefined && fromGenerateAudio != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'generateAudio'],\n fromGenerateAudio,\n );\n }\n\n const fromLastFrame = common.getValueByPath(fromObject, ['lastFrame']);\n if (parentObject !== undefined && fromLastFrame != null) {\n common.setValueByPath(\n parentObject,\n ['instances[0]', 'lastFrame'],\n imageToVertex(fromLastFrame),\n );\n }\n\n const fromCompressionQuality = common.getValueByPath(fromObject, [\n 'compressionQuality',\n ]);\n if (parentObject !== undefined && fromCompressionQuality != null) {\n common.setValueByPath(\n parentObject,\n ['parameters', 'compressionQuality'],\n fromCompressionQuality,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosParametersToVertex(\n apiClient: ApiClient,\n fromObject: types.GenerateVideosParameters,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromPrompt != null) {\n common.setValueByPath(toObject, ['instances[0]', 'prompt'], fromPrompt);\n }\n\n const fromImage = common.getValueByPath(fromObject, ['image']);\n if (fromImage != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'image'],\n imageToVertex(fromImage),\n );\n }\n\n const fromVideo = common.getValueByPath(fromObject, ['video']);\n if (fromVideo != null) {\n common.setValueByPath(\n toObject,\n ['instances[0]', 'video'],\n videoToVertex(fromVideo),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n generateVideosConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromMldev(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citationSources']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromMldev(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromMldev(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromMldev(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(toObject, ['content'], contentFromMldev(fromContent));\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromMldev(fromCitationMetadata),\n );\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['tokenCount']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromMldev(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromMldev(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromMldev(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function embedContentResponseFromMldev(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, ['embeddings']);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromMldev(),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromMldev(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromMldev(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromMldev(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromMldev(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromMldev(fromSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromMldev(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromMldev(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromMldev(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function modelFromMldev(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['version']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromMldev(fromTunedModelInfo),\n );\n }\n\n const fromInputTokenLimit = common.getValueByPath(fromObject, [\n 'inputTokenLimit',\n ]);\n if (fromInputTokenLimit != null) {\n common.setValueByPath(toObject, ['inputTokenLimit'], fromInputTokenLimit);\n }\n\n const fromOutputTokenLimit = common.getValueByPath(fromObject, [\n 'outputTokenLimit',\n ]);\n if (fromOutputTokenLimit != null) {\n common.setValueByPath(toObject, ['outputTokenLimit'], fromOutputTokenLimit);\n }\n\n const fromSupportedActions = common.getValueByPath(fromObject, [\n 'supportedGenerationMethods',\n ]);\n if (fromSupportedActions != null) {\n common.setValueByPath(toObject, ['supportedActions'], fromSupportedActions);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromMldev(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromMldev(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n const fromCachedContentTokenCount = common.getValueByPath(fromObject, [\n 'cachedContentTokenCount',\n ]);\n if (fromCachedContentTokenCount != null) {\n common.setValueByPath(\n toObject,\n ['cachedContentTokenCount'],\n fromCachedContentTokenCount,\n );\n }\n\n return toObject;\n}\n\nexport function videoFromMldev(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['video', 'uri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'video',\n 'encodedVideo',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['encoding']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromMldev(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromMldev(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromMldev(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, [\n 'generatedSamples',\n ]);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromMldev(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, [\n 'response',\n 'generateVideoResponse',\n ]);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromMldev(fromResponse),\n );\n }\n\n return toObject;\n}\n\nexport function videoMetadataFromVertex(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobFromVertex(\n fromObject: types.Blob,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataFromVertex(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partFromVertex(\n fromObject: types.Part,\n): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataFromVertex(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobFromVertex(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataFromVertex(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentFromVertex(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function citationMetadataFromVertex(\n fromObject: types.CitationMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromCitations = common.getValueByPath(fromObject, ['citations']);\n if (fromCitations != null) {\n common.setValueByPath(toObject, ['citations'], fromCitations);\n }\n\n return toObject;\n}\n\nexport function urlMetadataFromVertex(\n fromObject: types.UrlMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromRetrievedUrl = common.getValueByPath(fromObject, ['retrievedUrl']);\n if (fromRetrievedUrl != null) {\n common.setValueByPath(toObject, ['retrievedUrl'], fromRetrievedUrl);\n }\n\n const fromUrlRetrievalStatus = common.getValueByPath(fromObject, [\n 'urlRetrievalStatus',\n ]);\n if (fromUrlRetrievalStatus != null) {\n common.setValueByPath(\n toObject,\n ['urlRetrievalStatus'],\n fromUrlRetrievalStatus,\n );\n }\n\n return toObject;\n}\n\nexport function urlContextMetadataFromVertex(\n fromObject: types.UrlContextMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromUrlMetadata = common.getValueByPath(fromObject, ['urlMetadata']);\n if (fromUrlMetadata != null) {\n let transformedList = fromUrlMetadata;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return urlMetadataFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['urlMetadata'], transformedList);\n }\n\n return toObject;\n}\n\nexport function candidateFromVertex(\n fromObject: types.Candidate,\n): Record {\n const toObject: Record = {};\n\n const fromContent = common.getValueByPath(fromObject, ['content']);\n if (fromContent != null) {\n common.setValueByPath(\n toObject,\n ['content'],\n contentFromVertex(fromContent),\n );\n }\n\n const fromCitationMetadata = common.getValueByPath(fromObject, [\n 'citationMetadata',\n ]);\n if (fromCitationMetadata != null) {\n common.setValueByPath(\n toObject,\n ['citationMetadata'],\n citationMetadataFromVertex(fromCitationMetadata),\n );\n }\n\n const fromFinishMessage = common.getValueByPath(fromObject, [\n 'finishMessage',\n ]);\n if (fromFinishMessage != null) {\n common.setValueByPath(toObject, ['finishMessage'], fromFinishMessage);\n }\n\n const fromFinishReason = common.getValueByPath(fromObject, ['finishReason']);\n if (fromFinishReason != null) {\n common.setValueByPath(toObject, ['finishReason'], fromFinishReason);\n }\n\n const fromUrlContextMetadata = common.getValueByPath(fromObject, [\n 'urlContextMetadata',\n ]);\n if (fromUrlContextMetadata != null) {\n common.setValueByPath(\n toObject,\n ['urlContextMetadata'],\n urlContextMetadataFromVertex(fromUrlContextMetadata),\n );\n }\n\n const fromAvgLogprobs = common.getValueByPath(fromObject, ['avgLogprobs']);\n if (fromAvgLogprobs != null) {\n common.setValueByPath(toObject, ['avgLogprobs'], fromAvgLogprobs);\n }\n\n const fromGroundingMetadata = common.getValueByPath(fromObject, [\n 'groundingMetadata',\n ]);\n if (fromGroundingMetadata != null) {\n common.setValueByPath(\n toObject,\n ['groundingMetadata'],\n fromGroundingMetadata,\n );\n }\n\n const fromIndex = common.getValueByPath(fromObject, ['index']);\n if (fromIndex != null) {\n common.setValueByPath(toObject, ['index'], fromIndex);\n }\n\n const fromLogprobsResult = common.getValueByPath(fromObject, [\n 'logprobsResult',\n ]);\n if (fromLogprobsResult != null) {\n common.setValueByPath(toObject, ['logprobsResult'], fromLogprobsResult);\n }\n\n const fromSafetyRatings = common.getValueByPath(fromObject, [\n 'safetyRatings',\n ]);\n if (fromSafetyRatings != null) {\n common.setValueByPath(toObject, ['safetyRatings'], fromSafetyRatings);\n }\n\n return toObject;\n}\n\nexport function generateContentResponseFromVertex(\n fromObject: types.GenerateContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromCandidates = common.getValueByPath(fromObject, ['candidates']);\n if (fromCandidates != null) {\n let transformedList = fromCandidates;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return candidateFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['candidates'], transformedList);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromResponseId = common.getValueByPath(fromObject, ['responseId']);\n if (fromResponseId != null) {\n common.setValueByPath(toObject, ['responseId'], fromResponseId);\n }\n\n const fromModelVersion = common.getValueByPath(fromObject, ['modelVersion']);\n if (fromModelVersion != null) {\n common.setValueByPath(toObject, ['modelVersion'], fromModelVersion);\n }\n\n const fromPromptFeedback = common.getValueByPath(fromObject, [\n 'promptFeedback',\n ]);\n if (fromPromptFeedback != null) {\n common.setValueByPath(toObject, ['promptFeedback'], fromPromptFeedback);\n }\n\n const fromUsageMetadata = common.getValueByPath(fromObject, [\n 'usageMetadata',\n ]);\n if (fromUsageMetadata != null) {\n common.setValueByPath(toObject, ['usageMetadata'], fromUsageMetadata);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingStatisticsFromVertex(\n fromObject: types.ContentEmbeddingStatistics,\n): Record {\n const toObject: Record = {};\n\n const fromTruncated = common.getValueByPath(fromObject, ['truncated']);\n if (fromTruncated != null) {\n common.setValueByPath(toObject, ['truncated'], fromTruncated);\n }\n\n const fromTokenCount = common.getValueByPath(fromObject, ['token_count']);\n if (fromTokenCount != null) {\n common.setValueByPath(toObject, ['tokenCount'], fromTokenCount);\n }\n\n return toObject;\n}\n\nexport function contentEmbeddingFromVertex(\n fromObject: types.ContentEmbedding,\n): Record {\n const toObject: Record = {};\n\n const fromValues = common.getValueByPath(fromObject, ['values']);\n if (fromValues != null) {\n common.setValueByPath(toObject, ['values'], fromValues);\n }\n\n const fromStatistics = common.getValueByPath(fromObject, ['statistics']);\n if (fromStatistics != null) {\n common.setValueByPath(\n toObject,\n ['statistics'],\n contentEmbeddingStatisticsFromVertex(fromStatistics),\n );\n }\n\n return toObject;\n}\n\nexport function embedContentMetadataFromVertex(\n fromObject: types.EmbedContentMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromBillableCharacterCount = common.getValueByPath(fromObject, [\n 'billableCharacterCount',\n ]);\n if (fromBillableCharacterCount != null) {\n common.setValueByPath(\n toObject,\n ['billableCharacterCount'],\n fromBillableCharacterCount,\n );\n }\n\n return toObject;\n}\n\nexport function embedContentResponseFromVertex(\n fromObject: types.EmbedContentResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromEmbeddings = common.getValueByPath(fromObject, [\n 'predictions[]',\n 'embeddings',\n ]);\n if (fromEmbeddings != null) {\n let transformedList = fromEmbeddings;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return contentEmbeddingFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['embeddings'], transformedList);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(\n toObject,\n ['metadata'],\n embedContentMetadataFromVertex(fromMetadata),\n );\n }\n\n return toObject;\n}\n\nexport function imageFromVertex(\n fromObject: types.Image,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['gcsUri'], fromGcsUri);\n }\n\n const fromImageBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromImageBytes != null) {\n common.setValueByPath(toObject, ['imageBytes'], t.tBytes(fromImageBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function safetyAttributesFromVertex(\n fromObject: types.SafetyAttributes,\n): Record {\n const toObject: Record = {};\n\n const fromCategories = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'categories',\n ]);\n if (fromCategories != null) {\n common.setValueByPath(toObject, ['categories'], fromCategories);\n }\n\n const fromScores = common.getValueByPath(fromObject, [\n 'safetyAttributes',\n 'scores',\n ]);\n if (fromScores != null) {\n common.setValueByPath(toObject, ['scores'], fromScores);\n }\n\n const fromContentType = common.getValueByPath(fromObject, ['contentType']);\n if (fromContentType != null) {\n common.setValueByPath(toObject, ['contentType'], fromContentType);\n }\n\n return toObject;\n}\n\nexport function generatedImageFromVertex(\n fromObject: types.GeneratedImage,\n): Record {\n const toObject: Record = {};\n\n const fromImage = common.getValueByPath(fromObject, ['_self']);\n if (fromImage != null) {\n common.setValueByPath(toObject, ['image'], imageFromVertex(fromImage));\n }\n\n const fromRaiFilteredReason = common.getValueByPath(fromObject, [\n 'raiFilteredReason',\n ]);\n if (fromRaiFilteredReason != null) {\n common.setValueByPath(\n toObject,\n ['raiFilteredReason'],\n fromRaiFilteredReason,\n );\n }\n\n const fromSafetyAttributes = common.getValueByPath(fromObject, ['_self']);\n if (fromSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['safetyAttributes'],\n safetyAttributesFromVertex(fromSafetyAttributes),\n );\n }\n\n const fromEnhancedPrompt = common.getValueByPath(fromObject, ['prompt']);\n if (fromEnhancedPrompt != null) {\n common.setValueByPath(toObject, ['enhancedPrompt'], fromEnhancedPrompt);\n }\n\n return toObject;\n}\n\nexport function generateImagesResponseFromVertex(\n fromObject: types.GenerateImagesResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n const fromPositivePromptSafetyAttributes = common.getValueByPath(fromObject, [\n 'positivePromptSafetyAttributes',\n ]);\n if (fromPositivePromptSafetyAttributes != null) {\n common.setValueByPath(\n toObject,\n ['positivePromptSafetyAttributes'],\n safetyAttributesFromVertex(fromPositivePromptSafetyAttributes),\n );\n }\n\n return toObject;\n}\n\nexport function editImageResponseFromVertex(\n fromObject: types.EditImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function upscaleImageResponseFromVertex(\n fromObject: types.UpscaleImageResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromGeneratedImages = common.getValueByPath(fromObject, [\n 'predictions',\n ]);\n if (fromGeneratedImages != null) {\n let transformedList = fromGeneratedImages;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedImageFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedImages'], transformedList);\n }\n\n return toObject;\n}\n\nexport function endpointFromVertex(\n fromObject: types.Endpoint,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['endpoint']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDeployedModelId = common.getValueByPath(fromObject, [\n 'deployedModelId',\n ]);\n if (fromDeployedModelId != null) {\n common.setValueByPath(toObject, ['deployedModelId'], fromDeployedModelId);\n }\n\n return toObject;\n}\n\nexport function tunedModelInfoFromVertex(\n fromObject: types.TunedModelInfo,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, [\n 'labels',\n 'google-vertex-llm-tuning-base-model-id',\n ]);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n return toObject;\n}\n\nexport function checkpointFromVertex(\n fromObject: types.Checkpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n return toObject;\n}\n\nexport function modelFromVertex(\n fromObject: types.Model,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromDisplayName = common.getValueByPath(fromObject, ['displayName']);\n if (fromDisplayName != null) {\n common.setValueByPath(toObject, ['displayName'], fromDisplayName);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromVersion = common.getValueByPath(fromObject, ['versionId']);\n if (fromVersion != null) {\n common.setValueByPath(toObject, ['version'], fromVersion);\n }\n\n const fromEndpoints = common.getValueByPath(fromObject, ['deployedModels']);\n if (fromEndpoints != null) {\n let transformedList = fromEndpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return endpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['endpoints'], transformedList);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromTunedModelInfo = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModelInfo != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelInfo'],\n tunedModelInfoFromVertex(fromTunedModelInfo),\n );\n }\n\n const fromDefaultCheckpointId = common.getValueByPath(fromObject, [\n 'defaultCheckpointId',\n ]);\n if (fromDefaultCheckpointId != null) {\n common.setValueByPath(\n toObject,\n ['defaultCheckpointId'],\n fromDefaultCheckpointId,\n );\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return checkpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function listModelsResponseFromVertex(\n fromObject: types.ListModelsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromModels = common.getValueByPath(fromObject, ['_self']);\n if (fromModels != null) {\n let transformedList = t.tExtractModels(fromModels);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return modelFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['models'], transformedList);\n }\n\n return toObject;\n}\n\nexport function deleteModelResponseFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function countTokensResponseFromVertex(\n fromObject: types.CountTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTotalTokens = common.getValueByPath(fromObject, ['totalTokens']);\n if (fromTotalTokens != null) {\n common.setValueByPath(toObject, ['totalTokens'], fromTotalTokens);\n }\n\n return toObject;\n}\n\nexport function computeTokensResponseFromVertex(\n fromObject: types.ComputeTokensResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromTokensInfo = common.getValueByPath(fromObject, ['tokensInfo']);\n if (fromTokensInfo != null) {\n common.setValueByPath(toObject, ['tokensInfo'], fromTokensInfo);\n }\n\n return toObject;\n}\n\nexport function videoFromVertex(\n fromObject: types.Video,\n): Record {\n const toObject: Record = {};\n\n const fromUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromUri != null) {\n common.setValueByPath(toObject, ['uri'], fromUri);\n }\n\n const fromVideoBytes = common.getValueByPath(fromObject, [\n 'bytesBase64Encoded',\n ]);\n if (fromVideoBytes != null) {\n common.setValueByPath(toObject, ['videoBytes'], t.tBytes(fromVideoBytes));\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function generatedVideoFromVertex(\n fromObject: types.GeneratedVideo,\n): Record {\n const toObject: Record = {};\n\n const fromVideo = common.getValueByPath(fromObject, ['_self']);\n if (fromVideo != null) {\n common.setValueByPath(toObject, ['video'], videoFromVertex(fromVideo));\n }\n\n return toObject;\n}\n\nexport function generateVideosResponseFromVertex(\n fromObject: types.GenerateVideosResponse,\n): Record {\n const toObject: Record = {};\n\n const fromGeneratedVideos = common.getValueByPath(fromObject, ['videos']);\n if (fromGeneratedVideos != null) {\n let transformedList = fromGeneratedVideos;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return generatedVideoFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['generatedVideos'], transformedList);\n }\n\n const fromRaiMediaFilteredCount = common.getValueByPath(fromObject, [\n 'raiMediaFilteredCount',\n ]);\n if (fromRaiMediaFilteredCount != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredCount'],\n fromRaiMediaFilteredCount,\n );\n }\n\n const fromRaiMediaFilteredReasons = common.getValueByPath(fromObject, [\n 'raiMediaFilteredReasons',\n ]);\n if (fromRaiMediaFilteredReasons != null) {\n common.setValueByPath(\n toObject,\n ['raiMediaFilteredReasons'],\n fromRaiMediaFilteredReasons,\n );\n }\n\n return toObject;\n}\n\nexport function generateVideosOperationFromVertex(\n fromObject: types.GenerateVideosOperation,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(\n toObject,\n ['response'],\n generateVideosResponseFromVertex(fromResponse),\n );\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from './_auth.js';\nimport * as common from './_common.js';\nimport {Downloader} from './_downloader.js';\nimport {Uploader} from './_uploader.js';\nimport {ApiError} from './errors.js';\nimport {\n DownloadFileParameters,\n File,\n HttpOptions,\n HttpResponse,\n UploadFileConfig,\n} from './types.js';\n\nconst CONTENT_TYPE_HEADER = 'Content-Type';\nconst SERVER_TIMEOUT_HEADER = 'X-Server-Timeout';\nconst USER_AGENT_HEADER = 'User-Agent';\nexport const GOOGLE_API_CLIENT_HEADER = 'x-goog-api-client';\nexport const SDK_VERSION = '1.11.0'; // x-release-please-version\nconst LIBRARY_LABEL = `google-genai-sdk/${SDK_VERSION}`;\nconst VERTEX_AI_API_DEFAULT_VERSION = 'v1beta1';\nconst GOOGLE_AI_API_DEFAULT_VERSION = 'v1beta';\nconst responseLineRE = /^data: (.*)(?:\\n\\n|\\r\\r|\\r\\n\\r\\n)/;\n\n/**\n * Options for initializing the ApiClient. The ApiClient uses the parameters\n * for authentication purposes as well as to infer if SDK should send the\n * request to Vertex AI or Gemini API.\n */\nexport interface ApiClientInitOptions {\n /**\n * The object used for adding authentication headers to API requests.\n */\n auth: Auth;\n /**\n * The uploader to use for uploading files. This field is required for\n * creating a client, will be set through the Node_client or Web_client.\n */\n uploader: Uploader;\n /**\n * Optional. The downloader to use for downloading files. This field is\n * required for creating a client, will be set through the Node_client or\n * Web_client.\n */\n downloader: Downloader;\n /**\n * Optional. The Google Cloud project ID for Vertex AI users.\n * It is not the numeric project name.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n project?: string;\n /**\n * Optional. The Google Cloud project location for Vertex AI users.\n * If not provided, SDK will try to resolve it from runtime environment.\n */\n location?: string;\n /**\n * The API Key. This is required for Gemini API users.\n */\n apiKey?: string;\n /**\n * Optional. Set to true if you intend to call Vertex AI endpoints.\n * If unset, default SDK behavior is to call Gemini API.\n */\n vertexai?: boolean;\n /**\n * Optional. The API version for the endpoint.\n * If unset, SDK will choose a default api version.\n */\n apiVersion?: string;\n /**\n * Optional. A set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional. An extra string to append at the end of the User-Agent header.\n *\n * This can be used to e.g specify the runtime and its version.\n */\n userAgentExtra?: string;\n}\n\n/**\n * Represents the necessary information to send a request to an API endpoint.\n * This interface defines the structure for constructing and executing HTTP\n * requests.\n */\nexport interface HttpRequest {\n /**\n * URL path from the modules, this path is appended to the base API URL to\n * form the complete request URL.\n *\n * If you wish to set full URL, use httpOptions.baseUrl instead. Example to\n * set full URL in the request:\n *\n * const request: HttpRequest = {\n * path: '',\n * httpOptions: {\n * baseUrl: 'https://',\n * apiVersion: '',\n * },\n * httpMethod: 'GET',\n * };\n *\n * The result URL will be: https://\n *\n */\n path: string;\n /**\n * Optional query parameters to be appended to the request URL.\n */\n queryParams?: Record;\n /**\n * Optional request body in json string or Blob format, GET request doesn't\n * need a request body.\n */\n body?: string | Blob;\n /**\n * The HTTP method to be used for the request.\n */\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE';\n /**\n * Optional set of customizable configuration for HTTP requests.\n */\n httpOptions?: HttpOptions;\n /**\n * Optional abort signal which can be used to cancel the request.\n */\n abortSignal?: AbortSignal;\n}\n\n/**\n * The ApiClient class is used to send requests to the Gemini API or Vertex AI\n * endpoints.\n */\nexport class ApiClient {\n readonly clientOptions: ApiClientInitOptions;\n\n constructor(opts: ApiClientInitOptions) {\n this.clientOptions = {\n ...opts,\n project: opts.project,\n location: opts.location,\n apiKey: opts.apiKey,\n vertexai: opts.vertexai,\n };\n\n const initHttpOptions: HttpOptions = {};\n\n if (this.clientOptions.vertexai) {\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? VERTEX_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = this.baseUrlFromProjectLocation();\n this.normalizeAuthParameters();\n } else {\n // Gemini API\n initHttpOptions.apiVersion =\n this.clientOptions.apiVersion ?? GOOGLE_AI_API_DEFAULT_VERSION;\n initHttpOptions.baseUrl = `https://generativelanguage.googleapis.com/`;\n }\n\n initHttpOptions.headers = this.getDefaultHeaders();\n\n this.clientOptions.httpOptions = initHttpOptions;\n\n if (opts.httpOptions) {\n this.clientOptions.httpOptions = this.patchHttpOptions(\n initHttpOptions,\n opts.httpOptions,\n );\n }\n }\n\n /**\n * Determines the base URL for Vertex AI based on project and location.\n * Uses the global endpoint if location is 'global' or if project/location\n * are not specified (implying API key usage).\n * @private\n */\n private baseUrlFromProjectLocation(): string {\n if (\n this.clientOptions.project &&\n this.clientOptions.location &&\n this.clientOptions.location !== 'global'\n ) {\n // Regional endpoint\n return `https://${this.clientOptions.location}-aiplatform.googleapis.com/`;\n }\n // Global endpoint (covers 'global' location and API key usage)\n return `https://aiplatform.googleapis.com/`;\n }\n\n /**\n * Normalizes authentication parameters for Vertex AI.\n * If project and location are provided, API key is cleared.\n * If project and location are not provided (implying API key usage),\n * project and location are cleared.\n * @private\n */\n private normalizeAuthParameters(): void {\n if (this.clientOptions.project && this.clientOptions.location) {\n // Using project/location for auth, clear potential API key\n this.clientOptions.apiKey = undefined;\n return;\n }\n // Using API key for auth (or no auth provided yet), clear project/location\n this.clientOptions.project = undefined;\n this.clientOptions.location = undefined;\n }\n\n isVertexAI(): boolean {\n return this.clientOptions.vertexai ?? false;\n }\n\n getProject() {\n return this.clientOptions.project;\n }\n\n getLocation() {\n return this.clientOptions.location;\n }\n\n getApiVersion() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.apiVersion !== undefined\n ) {\n return this.clientOptions.httpOptions.apiVersion;\n }\n throw new Error('API version is not set.');\n }\n\n getBaseUrl() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.baseUrl !== undefined\n ) {\n return this.clientOptions.httpOptions.baseUrl;\n }\n throw new Error('Base URL is not set.');\n }\n\n getRequestUrl() {\n return this.getRequestUrlInternal(this.clientOptions.httpOptions);\n }\n\n getHeaders() {\n if (\n this.clientOptions.httpOptions &&\n this.clientOptions.httpOptions.headers !== undefined\n ) {\n return this.clientOptions.httpOptions.headers;\n } else {\n throw new Error('Headers are not set.');\n }\n }\n\n private getRequestUrlInternal(httpOptions?: HttpOptions) {\n if (\n !httpOptions ||\n httpOptions.baseUrl === undefined ||\n httpOptions.apiVersion === undefined\n ) {\n throw new Error('HTTP options are not correctly set.');\n }\n const baseUrl = httpOptions.baseUrl.endsWith('/')\n ? httpOptions.baseUrl.slice(0, -1)\n : httpOptions.baseUrl;\n const urlElement: Array = [baseUrl];\n if (httpOptions.apiVersion && httpOptions.apiVersion !== '') {\n urlElement.push(httpOptions.apiVersion);\n }\n return urlElement.join('/');\n }\n\n getBaseResourcePath() {\n return `projects/${this.clientOptions.project}/locations/${\n this.clientOptions.location\n }`;\n }\n\n getApiKey() {\n return this.clientOptions.apiKey;\n }\n\n getWebsocketBaseUrl() {\n const baseUrl = this.getBaseUrl();\n const urlParts = new URL(baseUrl);\n urlParts.protocol = urlParts.protocol == 'http:' ? 'ws' : 'wss';\n return urlParts.toString();\n }\n\n setBaseUrl(url: string) {\n if (this.clientOptions.httpOptions) {\n this.clientOptions.httpOptions.baseUrl = url;\n } else {\n throw new Error('HTTP options are not correctly set.');\n }\n }\n\n private constructUrl(\n path: string,\n httpOptions: HttpOptions,\n prependProjectLocation: boolean,\n ): URL {\n const urlElement: Array = [this.getRequestUrlInternal(httpOptions)];\n if (prependProjectLocation) {\n urlElement.push(this.getBaseResourcePath());\n }\n if (path !== '') {\n urlElement.push(path);\n }\n const url = new URL(`${urlElement.join('/')}`);\n\n return url;\n }\n\n private shouldPrependVertexProjectPath(request: HttpRequest): boolean {\n if (this.clientOptions.apiKey) {\n return false;\n }\n if (!this.clientOptions.vertexai) {\n return false;\n }\n if (request.path.startsWith('projects/')) {\n // Assume the path already starts with\n // `projects//location/`.\n return false;\n }\n if (\n request.httpMethod === 'GET' &&\n request.path.startsWith('publishers/google/models')\n ) {\n // These paths are used by Vertex's models.get and models.list\n // calls. For base models Vertex does not accept a project/location\n // prefix (for tuned model the prefix is required).\n return false;\n }\n return true;\n }\n\n async request(request: HttpRequest): Promise {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (request.queryParams) {\n for (const [key, value] of Object.entries(request.queryParams)) {\n url.searchParams.append(key, String(value));\n }\n }\n let requestInit: RequestInit = {};\n if (request.httpMethod === 'GET') {\n if (request.body && request.body !== '{}') {\n throw new Error(\n 'Request body should be empty for GET request, but got non empty request body',\n );\n }\n } else {\n requestInit.body = request.body;\n }\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.unaryApiCall(url, requestInit, request.httpMethod);\n }\n\n private patchHttpOptions(\n baseHttpOptions: HttpOptions,\n requestHttpOptions: HttpOptions,\n ): HttpOptions {\n const patchedHttpOptions = JSON.parse(\n JSON.stringify(baseHttpOptions),\n ) as HttpOptions;\n\n for (const [key, value] of Object.entries(requestHttpOptions)) {\n // Records compile to objects.\n if (typeof value === 'object') {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = {...patchedHttpOptions[key], ...value};\n } else if (value !== undefined) {\n // @ts-expect-error TS2345TS7053: Element implicitly has an 'any' type\n // because expression of type 'string' can't be used to index type\n // 'HttpOptions'.\n patchedHttpOptions[key] = value;\n }\n }\n return patchedHttpOptions;\n }\n\n async requestStream(\n request: HttpRequest,\n ): Promise> {\n let patchedHttpOptions = this.clientOptions.httpOptions!;\n if (request.httpOptions) {\n patchedHttpOptions = this.patchHttpOptions(\n this.clientOptions.httpOptions!,\n request.httpOptions,\n );\n }\n\n const prependProjectLocation = this.shouldPrependVertexProjectPath(request);\n const url = this.constructUrl(\n request.path,\n patchedHttpOptions,\n prependProjectLocation,\n );\n if (!url.searchParams.has('alt') || url.searchParams.get('alt') !== 'sse') {\n url.searchParams.set('alt', 'sse');\n }\n let requestInit: RequestInit = {};\n requestInit.body = request.body;\n requestInit = await this.includeExtraHttpOptionsToRequestInit(\n requestInit,\n patchedHttpOptions,\n request.abortSignal,\n );\n return this.streamApiCall(url, requestInit, request.httpMethod);\n }\n\n private async includeExtraHttpOptionsToRequestInit(\n requestInit: RequestInit,\n httpOptions: HttpOptions,\n abortSignal?: AbortSignal,\n ): Promise {\n if ((httpOptions && httpOptions.timeout) || abortSignal) {\n const abortController = new AbortController();\n const signal = abortController.signal;\n if (httpOptions.timeout && httpOptions?.timeout > 0) {\n const timeoutHandle = setTimeout(\n () => abortController.abort(),\n httpOptions.timeout,\n );\n if (\n timeoutHandle &&\n typeof (timeoutHandle as unknown as NodeJS.Timeout).unref ===\n 'function'\n ) {\n // call unref to prevent nodejs process from hanging, see\n // https://nodejs.org/api/timers.html#timeoutunref\n timeoutHandle.unref();\n }\n }\n if (abortSignal) {\n abortSignal.addEventListener('abort', () => {\n abortController.abort();\n });\n }\n requestInit.signal = signal;\n }\n if (httpOptions && httpOptions.extraBody !== null) {\n includeExtraBodyToRequestInit(\n requestInit,\n httpOptions.extraBody as Record,\n );\n }\n requestInit.headers = await this.getHeadersInternal(httpOptions);\n return requestInit;\n }\n\n private async unaryApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return new HttpResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n private async streamApiCall(\n url: URL,\n requestInit: RequestInit,\n httpMethod: 'GET' | 'POST' | 'PATCH' | 'DELETE',\n ): Promise> {\n return this.apiCall(url.toString(), {\n ...requestInit,\n method: httpMethod,\n })\n .then(async (response) => {\n await throwErrorIfNotOK(response);\n return this.processStreamResponse(response);\n })\n .catch((e) => {\n if (e instanceof Error) {\n throw e;\n } else {\n throw new Error(JSON.stringify(e));\n }\n });\n }\n\n async *processStreamResponse(\n response: Response,\n ): AsyncGenerator {\n const reader = response?.body?.getReader();\n const decoder = new TextDecoder('utf-8');\n if (!reader) {\n throw new Error('Response body is empty');\n }\n\n try {\n let buffer = '';\n while (true) {\n const {done, value} = await reader.read();\n if (done) {\n if (buffer.trim().length > 0) {\n throw new Error('Incomplete JSON segment at the end');\n }\n break;\n }\n const chunkString = decoder.decode(value, {stream: true});\n\n // Parse and throw an error if the chunk contains an error.\n try {\n const chunkJson = JSON.parse(chunkString) as Record;\n if ('error' in chunkJson) {\n const errorJson = JSON.parse(\n JSON.stringify(chunkJson['error']),\n ) as Record;\n const status = errorJson['status'] as string;\n const code = errorJson['code'] as number;\n const errorMessage = `got status: ${status}. ${JSON.stringify(\n chunkJson,\n )}`;\n if (code >= 400 && code < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: code,\n });\n throw apiError;\n }\n }\n } catch (e: unknown) {\n const error = e as Error;\n if (error.name === 'ApiError') {\n throw e;\n }\n }\n buffer += chunkString;\n let match = buffer.match(responseLineRE);\n while (match) {\n const processedChunkString = match[1];\n try {\n const partialResponse = new Response(processedChunkString, {\n headers: response?.headers,\n status: response?.status,\n statusText: response?.statusText,\n });\n yield new HttpResponse(partialResponse);\n buffer = buffer.slice(match[0].length);\n match = buffer.match(responseLineRE);\n } catch (e) {\n throw new Error(\n `exception parsing stream chunk ${processedChunkString}. ${e}`,\n );\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n }\n private async apiCall(\n url: string,\n requestInit: RequestInit,\n ): Promise {\n return fetch(url, requestInit).catch((e) => {\n throw new Error(`exception ${e} sending request`);\n });\n }\n\n getDefaultHeaders(): Record {\n const headers: Record = {};\n\n const versionHeaderValue =\n LIBRARY_LABEL + ' ' + this.clientOptions.userAgentExtra;\n\n headers[USER_AGENT_HEADER] = versionHeaderValue;\n headers[GOOGLE_API_CLIENT_HEADER] = versionHeaderValue;\n headers[CONTENT_TYPE_HEADER] = 'application/json';\n\n return headers;\n }\n\n private async getHeadersInternal(\n httpOptions: HttpOptions | undefined,\n ): Promise {\n const headers = new Headers();\n if (httpOptions && httpOptions.headers) {\n for (const [key, value] of Object.entries(httpOptions.headers)) {\n headers.append(key, value);\n }\n // Append a timeout header if it is set, note that the timeout option is\n // in milliseconds but the header is in seconds.\n if (httpOptions.timeout && httpOptions.timeout > 0) {\n headers.append(\n SERVER_TIMEOUT_HEADER,\n String(Math.ceil(httpOptions.timeout / 1000)),\n );\n }\n }\n await this.clientOptions.auth.addAuthHeaders(headers);\n return headers;\n }\n\n /**\n * Uploads a file asynchronously using Gemini API only, this is not supported\n * in Vertex AI.\n *\n * @param file The string path to the file to be uploaded or a Blob object.\n * @param config Optional parameters specified in the `UploadFileConfig`\n * interface. @see {@link UploadFileConfig}\n * @return A promise that resolves to a `File` object.\n * @throws An error if called on a Vertex AI client.\n * @throws An error if the `mimeType` is not provided and can not be inferred,\n */\n async uploadFile(\n file: string | Blob,\n config?: UploadFileConfig,\n ): Promise {\n const fileToUpload: File = {};\n if (config != null) {\n fileToUpload.mimeType = config.mimeType;\n fileToUpload.name = config.name;\n fileToUpload.displayName = config.displayName;\n }\n\n if (fileToUpload.name && !fileToUpload.name.startsWith('files/')) {\n fileToUpload.name = `files/${fileToUpload.name}`;\n }\n\n const uploader = this.clientOptions.uploader;\n const fileStat = await uploader.stat(file);\n fileToUpload.sizeBytes = String(fileStat.size);\n const mimeType = config?.mimeType ?? fileStat.type;\n if (mimeType === undefined || mimeType === '') {\n throw new Error(\n 'Can not determine mimeType. Please provide mimeType in the config.',\n );\n }\n fileToUpload.mimeType = mimeType;\n\n const uploadUrl = await this.fetchUploadUrl(fileToUpload, config);\n return uploader.upload(file, uploadUrl, this);\n }\n\n /**\n * Downloads a file asynchronously to the specified path.\n *\n * @params params - The parameters for the download request, see {@link\n * DownloadFileParameters}\n */\n async downloadFile(params: DownloadFileParameters): Promise {\n const downloader = this.clientOptions.downloader;\n await downloader.download(params, this);\n }\n\n private async fetchUploadUrl(\n file: File,\n config?: UploadFileConfig,\n ): Promise {\n let httpOptions: HttpOptions = {};\n if (config?.httpOptions) {\n httpOptions = config.httpOptions;\n } else {\n httpOptions = {\n apiVersion: '', // api-version is set in the path.\n headers: {\n 'Content-Type': 'application/json',\n 'X-Goog-Upload-Protocol': 'resumable',\n 'X-Goog-Upload-Command': 'start',\n 'X-Goog-Upload-Header-Content-Length': `${file.sizeBytes}`,\n 'X-Goog-Upload-Header-Content-Type': `${file.mimeType}`,\n },\n };\n }\n\n const body: Record = {\n 'file': file,\n };\n const httpResponse = await this.request({\n path: common.formatMap(\n 'upload/v1beta/files',\n body['_url'] as Record,\n ),\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions,\n });\n\n if (!httpResponse || !httpResponse?.headers) {\n throw new Error(\n 'Server did not return an HttpResponse or the returned HttpResponse did not have headers.',\n );\n }\n\n const uploadUrl: string | undefined =\n httpResponse?.headers?.['x-goog-upload-url'];\n if (uploadUrl === undefined) {\n throw new Error(\n 'Failed to get upload url. Server did not return the x-google-upload-url in the headers',\n );\n }\n return uploadUrl;\n }\n}\n\nasync function throwErrorIfNotOK(response: Response | undefined) {\n if (response === undefined) {\n throw new Error('response is undefined');\n }\n if (!response.ok) {\n const status: number = response.status;\n let errorBody: Record;\n if (response.headers.get('content-type')?.includes('application/json')) {\n errorBody = await response.json();\n } else {\n errorBody = {\n error: {\n message: await response.text(),\n code: response.status,\n status: response.statusText,\n },\n };\n }\n const errorMessage = JSON.stringify(errorBody);\n if (status >= 400 && status < 600) {\n const apiError = new ApiError({\n message: errorMessage,\n status: status,\n });\n throw apiError;\n }\n throw new Error(errorMessage);\n }\n}\n\n/**\n * Recursively updates the `requestInit.body` with values from an `extraBody` object.\n *\n * If `requestInit.body` is a string, it's assumed to be JSON and will be parsed.\n * The `extraBody` is then deeply merged into this parsed object.\n * If `requestInit.body` is a Blob, `extraBody` will be ignored, and a warning logged,\n * as merging structured data into an opaque Blob is not supported.\n *\n * The function does not enforce that updated values from `extraBody` have the\n * same type as existing values in `requestInit.body`. Type mismatches during\n * the merge will result in a warning, but the value from `extraBody` will overwrite\n * the original. `extraBody` users are responsible for ensuring `extraBody` has the correct structure.\n *\n * @param requestInit The RequestInit object whose body will be updated.\n * @param extraBody The object containing updates to be merged into `requestInit.body`.\n */\nexport function includeExtraBodyToRequestInit(\n requestInit: RequestInit,\n extraBody: Record,\n) {\n if (!extraBody || Object.keys(extraBody).length === 0) {\n return;\n }\n\n if (requestInit.body instanceof Blob) {\n console.warn(\n 'includeExtraBodyToRequestInit: extraBody provided but current request body is a Blob. extraBody will be ignored as merging is not supported for Blob bodies.',\n );\n return;\n }\n\n let currentBodyObject: Record = {};\n\n // If adding new type to HttpRequest.body, please check the code below to\n // see if we need to update the logic.\n if (typeof requestInit.body === 'string' && requestInit.body.length > 0) {\n try {\n const parsedBody = JSON.parse(requestInit.body);\n if (\n typeof parsedBody === 'object' &&\n parsedBody !== null &&\n !Array.isArray(parsedBody)\n ) {\n currentBodyObject = parsedBody as Record;\n } else {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is valid JSON but not a non-array object. Skip applying extraBody to the request body.',\n );\n return;\n }\n /* eslint-disable-next-line @typescript-eslint/no-unused-vars */\n } catch (e) {\n console.warn(\n 'includeExtraBodyToRequestInit: Original request body is not valid JSON. Skip applying extraBody to the request body.',\n );\n return;\n }\n }\n\n function deepMerge(\n target: Record,\n source: Record,\n ): Record {\n const output = {...target};\n for (const key in source) {\n if (Object.prototype.hasOwnProperty.call(source, key)) {\n const sourceValue = source[key];\n const targetValue = output[key];\n if (\n sourceValue &&\n typeof sourceValue === 'object' &&\n !Array.isArray(sourceValue) &&\n targetValue &&\n typeof targetValue === 'object' &&\n !Array.isArray(targetValue)\n ) {\n output[key] = deepMerge(\n targetValue as Record,\n sourceValue as Record,\n );\n } else {\n if (\n targetValue &&\n sourceValue &&\n typeof targetValue !== typeof sourceValue\n ) {\n console.warn(\n `includeExtraBodyToRequestInit:deepMerge: Type mismatch for key \"${key}\". Original type: ${typeof targetValue}, New type: ${typeof sourceValue}. Overwriting.`,\n );\n }\n output[key] = sourceValue;\n }\n }\n }\n return output;\n }\n\n const mergedBody = deepMerge(currentBodyObject, extraBody);\n requestInit.body = JSON.stringify(mergedBody);\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport type {Client as McpClient} from '@modelcontextprotocol/sdk/client/index.js';\nimport type {Tool as McpTool} from '@modelcontextprotocol/sdk/types.js';\n\nimport {GOOGLE_API_CLIENT_HEADER} from '../_api_client.js';\nimport {mcpToolsToGeminiTool} from '../_transformers.js';\nimport {\n CallableTool,\n CallableToolConfig,\n FunctionCall,\n Part,\n Tool,\n ToolListUnion,\n} from '../types.js';\n\n// TODO: b/416041229 - Determine how to retrieve the MCP package version.\nexport const MCP_LABEL = 'mcp_used/unknown';\n\n// Whether MCP tool usage is detected from mcpToTool. This is used for\n// telemetry.\nlet hasMcpToolUsageFromMcpToTool = false;\n\n// Checks whether the list of tools contains any MCP tools.\nexport function hasMcpToolUsage(tools: ToolListUnion): boolean {\n for (const tool of tools) {\n if (isMcpCallableTool(tool)) {\n return true;\n }\n if (typeof tool === 'object' && 'inputSchema' in tool) {\n return true;\n }\n }\n\n return hasMcpToolUsageFromMcpToTool;\n}\n\n// Sets the MCP version label in the Google API client header.\nexport function setMcpUsageHeader(headers: Record) {\n const existingHeader = headers[GOOGLE_API_CLIENT_HEADER] ?? '';\n headers[GOOGLE_API_CLIENT_HEADER] = (\n existingHeader + ` ${MCP_LABEL}`\n ).trimStart();\n}\n\n// Returns true if the object is a MCP CallableTool, otherwise false.\nfunction isMcpCallableTool(object: unknown): boolean {\n return (\n object !== null &&\n typeof object === 'object' &&\n object instanceof McpCallableTool\n );\n}\n\n// List all tools from the MCP client.\nasync function* listAllTools(\n mcpClient: McpClient,\n maxTools: number = 100,\n): AsyncGenerator {\n let cursor: string | undefined = undefined;\n let numTools = 0;\n while (numTools < maxTools) {\n const t = await mcpClient.listTools({cursor});\n for (const tool of t.tools) {\n yield tool;\n numTools++;\n }\n if (!t.nextCursor) {\n break;\n }\n cursor = t.nextCursor;\n }\n}\n\n/**\n * McpCallableTool can be used for model inference and invoking MCP clients with\n * given function call arguments.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport class McpCallableTool implements CallableTool {\n private readonly mcpClients;\n private mcpTools: McpTool[] = [];\n private functionNameToMcpClient: Record = {};\n private readonly config: CallableToolConfig;\n\n private constructor(\n mcpClients: McpClient[] = [],\n config: CallableToolConfig,\n ) {\n this.mcpClients = mcpClients;\n this.config = config;\n }\n\n /**\n * Creates a McpCallableTool.\n */\n public static create(\n mcpClients: McpClient[],\n config: CallableToolConfig,\n ): McpCallableTool {\n return new McpCallableTool(mcpClients, config);\n }\n\n /**\n * Validates the function names are not duplicate and initialize the function\n * name to MCP client mapping.\n *\n * @throws {Error} if the MCP tools from the MCP clients have duplicate tool\n * names.\n */\n async initialize() {\n if (this.mcpTools.length > 0) {\n return;\n }\n\n const functionMap: Record = {};\n const mcpTools: McpTool[] = [];\n for (const mcpClient of this.mcpClients) {\n for await (const mcpTool of listAllTools(mcpClient)) {\n mcpTools.push(mcpTool);\n const mcpToolName = mcpTool.name as string;\n if (functionMap[mcpToolName]) {\n throw new Error(\n `Duplicate function name ${\n mcpToolName\n } found in MCP tools. Please ensure function names are unique.`,\n );\n }\n functionMap[mcpToolName] = mcpClient;\n }\n }\n this.mcpTools = mcpTools;\n this.functionNameToMcpClient = functionMap;\n }\n\n public async tool(): Promise {\n await this.initialize();\n return mcpToolsToGeminiTool(this.mcpTools, this.config);\n }\n\n public async callTool(functionCalls: FunctionCall[]): Promise {\n await this.initialize();\n const functionCallResponseParts: Part[] = [];\n for (const functionCall of functionCalls) {\n if (functionCall.name! in this.functionNameToMcpClient) {\n const mcpClient = this.functionNameToMcpClient[functionCall.name!];\n let requestOptions = undefined;\n // TODO: b/424238654 - Add support for finer grained timeout control.\n if (this.config.timeout) {\n requestOptions = {\n timeout: this.config.timeout,\n };\n }\n const callToolResponse = await mcpClient.callTool(\n {\n name: functionCall.name!,\n arguments: functionCall.args,\n },\n // Set the result schema to undefined to allow MCP to rely on the\n // default schema.\n undefined,\n requestOptions,\n );\n functionCallResponseParts.push({\n functionResponse: {\n name: functionCall.name,\n response: callToolResponse.isError\n ? {error: callToolResponse}\n : (callToolResponse as Record),\n },\n });\n }\n }\n return functionCallResponseParts;\n }\n}\n\nfunction isMcpClient(client: unknown): client is McpClient {\n return (\n client !== null &&\n typeof client === 'object' &&\n 'listTools' in client &&\n typeof client.listTools === 'function'\n );\n}\n\n/**\n * Creates a McpCallableTool from MCP clients and an optional config.\n *\n * The callable tool can invoke the MCP clients with given function call\n * arguments. (often for automatic function calling).\n * Use the config to modify tool parameters such as behavior.\n *\n * @experimental Built-in MCP support is an experimental feature, may change in future\n * versions.\n */\nexport function mcpToTool(\n ...args: [...McpClient[], CallableToolConfig | McpClient]\n): CallableTool {\n // Set MCP usage for telemetry.\n hasMcpToolUsageFromMcpToTool = true;\n if (args.length === 0) {\n throw new Error('No MCP clients provided');\n }\n const maybeConfig = args[args.length - 1];\n if (isMcpClient(maybeConfig)) {\n return McpCallableTool.create(args as McpClient[], {});\n }\n return McpCallableTool.create(\n args.slice(0, args.length - 1) as McpClient[],\n maybeConfig,\n );\n}\n\n/**\n * Sets the MCP tool usage flag from calling mcpToTool. This is used for\n * telemetry.\n */\nexport function setMcpToolUsageFromMcpToTool(mcpToolUsage: boolean) {\n hasMcpToolUsageFromMcpToTool = mcpToolUsage;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live music client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport * as types from './types.js';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveMusicServerMessage, and then calling the onmessage callback.\n * Note that the first message which is received from the server is a\n * setupComplete message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveMusicServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveMusicServerMessage =\n new types.LiveMusicServerMessage();\n let data: types.LiveMusicServerMessage;\n if (event.data instanceof Blob) {\n data = JSON.parse(await event.data.text()) as types.LiveMusicServerMessage;\n } else {\n data = JSON.parse(event.data) as types.LiveMusicServerMessage;\n }\n const response = converters.liveMusicServerMessageFromMldev(data);\n Object.assign(serverMessage, response);\n onmessage(serverMessage);\n}\n\n/**\n LiveMusic class encapsulates the configuration for live music\n generation via Lyria Live models.\n\n @experimental\n */\nexport class LiveMusic {\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {}\n\n /**\n Establishes a connection to the specified model and returns a\n LiveMusicSession object representing that connection.\n\n @experimental\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model = 'models/lyria-realtime-exp';\n const session = await ai.live.music.connect({\n model: model,\n callbacks: {\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(\n params: types.LiveMusicConnectParameters,\n ): Promise {\n if (this.apiClient.isVertexAI()) {\n throw new Error('Live music is not supported for Vertex AI.');\n }\n console.warn(\n 'Live music generation is experimental and may change in future versions.',\n );\n\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n const headers = mapToHeaders(this.apiClient.getDefaultHeaders());\n const apiKey = this.apiClient.getApiKey();\n const url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.BidiGenerateMusic?key=${apiKey}`;\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveMusicCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n const model = t.tModel(this.apiClient, params.model);\n const setup = converters.liveMusicClientSetupToMldev({\n model,\n });\n const clientMessage = converters.liveMusicClientMessageToMldev({setup});\n conn.send(JSON.stringify(clientMessage));\n\n return new LiveMusicSession(conn, this.apiClient);\n }\n}\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class LiveMusicSession {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n /**\n Sets inputs to steer music generation. Updates the session's current\n weighted prompts.\n\n @param params - Contains one property, `weightedPrompts`.\n\n - `weightedPrompts` to send to the model; weights are normalized to\n sum to 1.0.\n\n @experimental\n */\n async setWeightedPrompts(\n params: types.LiveMusicSetWeightedPromptsParameters,\n ) {\n if (\n !params.weightedPrompts ||\n Object.keys(params.weightedPrompts).length === 0\n ) {\n throw new Error(\n 'Weighted prompts must be set and contain at least one entry.',\n );\n }\n const setWeightedPromptsParameters =\n converters.liveMusicSetWeightedPromptsParametersToMldev(params);\n const clientContent = converters.liveMusicClientContentToMldev(\n setWeightedPromptsParameters,\n );\n this.conn.send(JSON.stringify({clientContent}));\n }\n\n /**\n Sets a configuration to the model. Updates the session's current\n music generation config.\n\n @param params - Contains one property, `musicGenerationConfig`.\n\n - `musicGenerationConfig` to set in the model. Passing an empty or\n undefined config to the model will reset the config to defaults.\n\n @experimental\n */\n async setMusicGenerationConfig(params: types.LiveMusicSetConfigParameters) {\n if (!params.musicGenerationConfig) {\n params.musicGenerationConfig = {};\n }\n const setConfigParameters =\n converters.liveMusicSetConfigParametersToMldev(params);\n const clientMessage =\n converters.liveMusicClientMessageToMldev(setConfigParameters);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n private sendPlaybackControl(playbackControl: types.LiveMusicPlaybackControl) {\n const clientMessage = converters.liveMusicClientMessageToMldev({\n playbackControl,\n });\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n * Start the music stream.\n *\n * @experimental\n */\n play() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PLAY);\n }\n\n /**\n * Temporarily halt the music stream. Use `play` to resume from the current\n * position.\n *\n * @experimental\n */\n pause() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.PAUSE);\n }\n\n /**\n * Stop the music stream and reset the state. Retains the current prompts\n * and config.\n *\n * @experimental\n */\n stop() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.STOP);\n }\n\n /**\n * Resets the context of the music generation without stopping it.\n * Retains the current prompts and config.\n *\n * @experimental\n */\n resetContext() {\n this.sendPlaybackControl(types.LiveMusicPlaybackControl.RESET_CONTEXT);\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n/**\n * Live client.\n *\n * @experimental\n */\n\nimport {ApiClient} from './_api_client.js';\nimport {Auth} from './_auth.js';\nimport * as t from './_transformers.js';\nimport {WebSocket, WebSocketCallbacks, WebSocketFactory} from './_websocket.js';\nimport * as converters from './converters/_live_converters.js';\nimport {\n contentToMldev,\n contentToVertex,\n} from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {LiveMusic} from './music.js';\nimport * as types from './types.js';\n\nconst FUNCTION_RESPONSE_REQUIRES_ID =\n 'FunctionResponse request must have an `id` field from the response of a ToolCall.FunctionalCalls in Google AI.';\n\n/**\n * Handles incoming messages from the WebSocket.\n *\n * @remarks\n * This function is responsible for parsing incoming messages, transforming them\n * into LiveServerMessages, and then calling the onmessage callback. Note that\n * the first message which is received from the server is a setupComplete\n * message.\n *\n * @param apiClient The ApiClient instance.\n * @param onmessage The user-provided onmessage callback (if any).\n * @param event The MessageEvent from the WebSocket.\n */\nasync function handleWebSocketMessage(\n apiClient: ApiClient,\n onmessage: (msg: types.LiveServerMessage) => void,\n event: MessageEvent,\n): Promise {\n const serverMessage: types.LiveServerMessage = new types.LiveServerMessage();\n let jsonData: string;\n if (event.data instanceof Blob) {\n jsonData = await event.data.text();\n } else if (event.data instanceof ArrayBuffer) {\n jsonData = new TextDecoder().decode(event.data);\n } else {\n jsonData = event.data;\n }\n\n const data = JSON.parse(jsonData) as types.LiveServerMessage;\n\n if (apiClient.isVertexAI()) {\n const resp = converters.liveServerMessageFromVertex(data);\n Object.assign(serverMessage, resp);\n } else {\n const resp = converters.liveServerMessageFromMldev(data);\n Object.assign(serverMessage, resp);\n }\n\n onmessage(serverMessage);\n}\n\n/**\n Live class encapsulates the configuration for live interaction with the\n Generative Language API. It embeds ApiClient for general API settings.\n\n @experimental\n */\nexport class Live {\n public readonly music: LiveMusic;\n\n constructor(\n private readonly apiClient: ApiClient,\n private readonly auth: Auth,\n private readonly webSocketFactory: WebSocketFactory,\n ) {\n this.music = new LiveMusic(\n this.apiClient,\n this.auth,\n this.webSocketFactory,\n );\n }\n\n /**\n Establishes a connection to the specified model with the given\n configuration and returns a Session object representing that connection.\n\n @experimental Built-in MCP support is an experimental feature, may change in\n future versions.\n\n @remarks\n\n @param params - The parameters for establishing a connection to the model.\n @return A live session.\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n },\n callbacks: {\n onopen: () => {\n console.log('Connected to the socket.');\n },\n onmessage: (e: MessageEvent) => {\n console.log('Received message from the server: %s\\n', debug(e.data));\n },\n onerror: (e: ErrorEvent) => {\n console.log('Error occurred: %s\\n', debug(e.error));\n },\n onclose: (e: CloseEvent) => {\n console.log('Connection closed.');\n },\n },\n });\n ```\n */\n async connect(params: types.LiveConnectParameters): Promise {\n // TODO: b/404946746 - Support per request HTTP options.\n if (params.config && params.config.httpOptions) {\n throw new Error(\n 'The Live module does not support httpOptions at request-level in' +\n ' LiveConnectConfig yet. Please use the client-level httpOptions' +\n ' configuration instead.',\n );\n }\n const websocketBaseUrl = this.apiClient.getWebsocketBaseUrl();\n const apiVersion = this.apiClient.getApiVersion();\n let url: string;\n const defaultHeaders = this.apiClient.getDefaultHeaders();\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n setMcpUsageHeader(defaultHeaders);\n }\n const headers = mapToHeaders(defaultHeaders);\n if (this.apiClient.isVertexAI()) {\n url = `${websocketBaseUrl}/ws/google.cloud.aiplatform.${\n apiVersion\n }.LlmBidiService/BidiGenerateContent`;\n await this.auth.addAuthHeaders(headers);\n } else {\n const apiKey = this.apiClient.getApiKey();\n\n let method = 'BidiGenerateContent';\n let keyName = 'key';\n if (apiKey?.startsWith('auth_tokens/')) {\n console.warn(\n 'Warning: Ephemeral token support is experimental and may change in future versions.',\n );\n if (apiVersion !== 'v1alpha') {\n console.warn(\n \"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.\",\n );\n }\n method = 'BidiGenerateContentConstrained';\n keyName = 'access_token';\n }\n\n url = `${websocketBaseUrl}/ws/google.ai.generativelanguage.${\n apiVersion\n }.GenerativeService.${method}?${keyName}=${apiKey}`;\n }\n\n let onopenResolve: (value: unknown) => void = () => {};\n const onopenPromise = new Promise((resolve: (value: unknown) => void) => {\n onopenResolve = resolve;\n });\n\n const callbacks: types.LiveCallbacks = params.callbacks;\n\n const onopenAwaitedCallback = function () {\n callbacks?.onopen?.();\n onopenResolve({});\n };\n\n const apiClient = this.apiClient;\n\n const websocketCallbacks: WebSocketCallbacks = {\n onopen: onopenAwaitedCallback,\n onmessage: (event: MessageEvent) => {\n void handleWebSocketMessage(apiClient, callbacks.onmessage, event);\n },\n onerror:\n callbacks?.onerror ??\n function (e: ErrorEvent) {\n void e;\n },\n onclose:\n callbacks?.onclose ??\n function (e: CloseEvent) {\n void e;\n },\n };\n\n const conn = this.webSocketFactory.create(\n url,\n headersToMap(headers),\n websocketCallbacks,\n );\n conn.connect();\n // Wait for the websocket to open before sending requests.\n await onopenPromise;\n\n let transformedModel = t.tModel(this.apiClient, params.model);\n if (\n this.apiClient.isVertexAI() &&\n transformedModel.startsWith('publishers/')\n ) {\n const project = this.apiClient.getProject();\n const location = this.apiClient.getLocation();\n transformedModel =\n `projects/${project}/locations/${location}/` + transformedModel;\n }\n\n let clientMessage: Record = {};\n\n if (\n this.apiClient.isVertexAI() &&\n params.config?.responseModalities === undefined\n ) {\n // Set default to AUDIO to align with MLDev API.\n if (params.config === undefined) {\n params.config = {responseModalities: [types.Modality.AUDIO]};\n } else {\n params.config.responseModalities = [types.Modality.AUDIO];\n }\n }\n if (params.config?.generationConfig) {\n // Raise deprecation warning for generationConfig.\n console.warn(\n '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).',\n );\n }\n const inputTools = params.config?.tools ?? [];\n const convertedTools: types.Tool[] = [];\n for (const tool of inputTools) {\n if (this.isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n convertedTools.push(await callableTool.tool());\n } else {\n convertedTools.push(tool as types.Tool);\n }\n }\n if (convertedTools.length > 0) {\n params.config!.tools = convertedTools;\n }\n const liveConnectParameters: types.LiveConnectParameters = {\n model: transformedModel,\n config: params.config,\n callbacks: params.callbacks,\n };\n if (this.apiClient.isVertexAI()) {\n clientMessage = converters.liveConnectParametersToVertex(\n this.apiClient,\n liveConnectParameters,\n );\n } else {\n clientMessage = converters.liveConnectParametersToMldev(\n this.apiClient,\n liveConnectParameters,\n );\n }\n delete clientMessage['config'];\n conn.send(JSON.stringify(clientMessage));\n return new Session(conn, this.apiClient);\n }\n\n // TODO: b/416041229 - Abstract this method to a common place.\n private isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n }\n}\n\nconst defaultLiveSendClientContentParamerters: types.LiveSendClientContentParameters =\n {\n turnComplete: true,\n };\n\n/**\n Represents a connection to the API.\n\n @experimental\n */\nexport class Session {\n constructor(\n readonly conn: WebSocket,\n private readonly apiClient: ApiClient,\n ) {}\n\n private tLiveClientContent(\n apiClient: ApiClient,\n params: types.LiveSendClientContentParameters,\n ): types.LiveClientMessage {\n if (params.turns !== null && params.turns !== undefined) {\n let contents: types.Content[] = [];\n try {\n contents = t.tContents(params.turns as types.ContentListUnion);\n if (apiClient.isVertexAI()) {\n contents = contents.map((item) => contentToVertex(item));\n } else {\n contents = contents.map((item) => contentToMldev(item));\n }\n } catch {\n throw new Error(\n `Failed to parse client content \"turns\", type: '${typeof params.turns}'`,\n );\n }\n return {\n clientContent: {turns: contents, turnComplete: params.turnComplete},\n };\n }\n\n return {\n clientContent: {turnComplete: params.turnComplete},\n };\n }\n\n private tLiveClienttToolResponse(\n apiClient: ApiClient,\n params: types.LiveSendToolResponseParameters,\n ): types.LiveClientMessage {\n let functionResponses: types.FunctionResponse[] = [];\n\n if (params.functionResponses == null) {\n throw new Error('functionResponses is required.');\n }\n\n if (!Array.isArray(params.functionResponses)) {\n functionResponses = [params.functionResponses];\n } else {\n functionResponses = params.functionResponses;\n }\n\n if (functionResponses.length === 0) {\n throw new Error('functionResponses is required.');\n }\n\n for (const functionResponse of functionResponses) {\n if (\n typeof functionResponse !== 'object' ||\n functionResponse === null ||\n !('name' in functionResponse) ||\n !('response' in functionResponse)\n ) {\n throw new Error(\n `Could not parse function response, type '${typeof functionResponse}'.`,\n );\n }\n if (!apiClient.isVertexAI() && !('id' in functionResponse)) {\n throw new Error(FUNCTION_RESPONSE_REQUIRES_ID);\n }\n }\n\n const clientMessage: types.LiveClientMessage = {\n toolResponse: {functionResponses: functionResponses},\n };\n return clientMessage;\n }\n\n /**\n Send a message over the established connection.\n\n @param params - Contains two **optional** properties, `turns` and\n `turnComplete`.\n\n - `turns` will be converted to a `Content[]`\n - `turnComplete: true` [default] indicates that you are done sending\n content and expect a response. If `turnComplete: false`, the server\n will wait for additional messages before starting generation.\n\n @experimental\n\n @remarks\n There are two ways to send messages to the live API:\n `sendClientContent` and `sendRealtimeInput`.\n\n `sendClientContent` messages are added to the model context **in order**.\n Having a conversation using `sendClientContent` messages is roughly\n equivalent to using the `Chat.sendMessageStream`, except that the state of\n the `chat` history is stored on the API server instead of locally.\n\n Because of `sendClientContent`'s order guarantee, the model cannot respons\n as quickly to `sendClientContent` messages as to `sendRealtimeInput`\n messages. This makes the biggest difference when sending objects that have\n significant preprocessing time (typically images).\n\n The `sendClientContent` message sends a `Content[]`\n which has more options than the `Blob` sent by `sendRealtimeInput`.\n\n So the main use-cases for `sendClientContent` over `sendRealtimeInput` are:\n\n - Sending anything that can't be represented as a `Blob` (text,\n `sendClientContent({turns=\"Hello?\"}`)).\n - Managing turns when not using audio input and voice activity detection.\n (`sendClientContent({turnComplete:true})` or the short form\n `sendClientContent()`)\n - Prefilling a conversation context\n ```\n sendClientContent({\n turns: [\n Content({role:user, parts:...}),\n Content({role:user, parts:...}),\n ...\n ]\n })\n ```\n @experimental\n */\n sendClientContent(params: types.LiveSendClientContentParameters) {\n params = {\n ...defaultLiveSendClientContentParamerters,\n ...params,\n };\n\n const clientMessage: types.LiveClientMessage = this.tLiveClientContent(\n this.apiClient,\n params,\n );\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a realtime message over the established connection.\n\n @param params - Contains one property, `media`.\n\n - `media` will be converted to a `Blob`\n\n @experimental\n\n @remarks\n Use `sendRealtimeInput` for realtime audio chunks and video frames (images).\n\n With `sendRealtimeInput` the api will respond to audio automatically\n based on voice activity detection (VAD).\n\n `sendRealtimeInput` is optimized for responsivness at the expense of\n deterministic ordering guarantees. Audio and video tokens are to the\n context when they become available.\n\n Note: The Call signature expects a `Blob` object, but only a subset\n of audio and image mimetypes are allowed.\n */\n sendRealtimeInput(params: types.LiveSendRealtimeInputParameters) {\n let clientMessage: types.LiveClientMessage = {};\n\n if (this.apiClient.isVertexAI()) {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToVertex(params),\n };\n } else {\n clientMessage = {\n 'realtimeInput':\n converters.liveSendRealtimeInputParametersToMldev(params),\n };\n }\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Send a function response message over the established connection.\n\n @param params - Contains property `functionResponses`.\n\n - `functionResponses` will be converted to a `functionResponses[]`\n\n @remarks\n Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server.\n\n Use {@link types.LiveConnectConfig#tools} to configure the callable functions.\n\n @experimental\n */\n sendToolResponse(params: types.LiveSendToolResponseParameters) {\n if (params.functionResponses == null) {\n throw new Error('Tool response parameters are required.');\n }\n\n const clientMessage: types.LiveClientMessage =\n this.tLiveClienttToolResponse(this.apiClient, params);\n this.conn.send(JSON.stringify(clientMessage));\n }\n\n /**\n Terminates the WebSocket connection.\n\n @experimental\n\n @example\n ```ts\n let model: string;\n if (GOOGLE_GENAI_USE_VERTEXAI) {\n model = 'gemini-2.0-flash-live-preview-04-09';\n } else {\n model = 'gemini-live-2.5-flash-preview';\n }\n const session = await ai.live.connect({\n model: model,\n config: {\n responseModalities: [Modality.AUDIO],\n }\n });\n\n session.close();\n ```\n */\n close() {\n this.conn.close();\n }\n}\n\n// Converts an headers object to a \"map\" object as expected by the WebSocket\n// constructor. We use this as the Auth interface works with Headers objects\n// while the WebSocket constructor takes a map.\nfunction headersToMap(headers: Headers): Record {\n const headerMap: Record = {};\n headers.forEach((value, key) => {\n headerMap[key] = value;\n });\n return headerMap;\n}\n\n// Converts a \"map\" object to a headers object. We use this as the Auth\n// interface works with Headers objects while the API client default headers\n// returns a map.\nfunction mapToHeaders(map: Record): Headers {\n const headers = new Headers();\n for (const [key, value] of Object.entries(map)) {\n headers.append(key, value);\n }\n return headers;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport * as types from './types.js';\n\nexport const DEFAULT_MAX_REMOTE_CALLS = 10;\n\n/** Returns whether automatic function calling is disabled. */\nexport function shouldDisableAfc(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n if (config?.automaticFunctionCalling?.disable) {\n return true;\n }\n\n let callableToolsPresent = false;\n for (const tool of config?.tools ?? []) {\n if (isCallableTool(tool)) {\n callableToolsPresent = true;\n break;\n }\n }\n if (!callableToolsPresent) {\n return true;\n }\n\n const maxCalls = config?.automaticFunctionCalling?.maximumRemoteCalls;\n if (\n (maxCalls && (maxCalls < 0 || !Number.isInteger(maxCalls))) ||\n maxCalls == 0\n ) {\n console.warn(\n 'Invalid maximumRemoteCalls value provided for automatic function calling. Disabled automatic function calling. Please provide a valid integer value greater than 0. maximumRemoteCalls provided:',\n maxCalls,\n );\n return true;\n }\n return false;\n}\n\nexport function isCallableTool(tool: types.ToolUnion): boolean {\n return 'callTool' in tool && typeof tool.callTool === 'function';\n}\n\n// Checks whether the list of tools contains any CallableTools. Will return true\n// if there is at least one CallableTool.\nexport function hasCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => isCallableTool(tool)) ?? false;\n}\n\n// Checks whether the list of tools contains any non-callable tools. Will return\n// true if there is at least one non-Callable tool.\nexport function hasNonCallableTools(\n params: types.GenerateContentParameters,\n): boolean {\n return params.config?.tools?.some((tool) => !isCallableTool(tool)) ?? false;\n}\n\n/**\n * Returns whether to append automatic function calling history to the\n * response.\n */\nexport function shouldAppendAfcHistory(\n config: types.GenerateContentConfig | undefined,\n): boolean {\n return !config?.automaticFunctionCalling?.ignoreCallHistory;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {\n DEFAULT_MAX_REMOTE_CALLS,\n hasCallableTools,\n hasNonCallableTools,\n isCallableTool,\n shouldAppendAfcHistory,\n shouldDisableAfc,\n} from './_afc.js';\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as _internal_types from './_internal_types.js';\nimport {tContents} from './_transformers.js';\nimport * as converters from './converters/_models_converters.js';\nimport {hasMcpToolUsage, setMcpUsageHeader} from './mcp/_mcp.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Models extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Makes an API request to generate content with a given model.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContent({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * candidateCount: 2,\n * }\n * });\n * console.log(response);\n * ```\n */\n generateContent = async (\n params: types.GenerateContentParameters,\n ): Promise => {\n const transformedParams = await this.processParamsMaybeAddMcpUsage(params);\n this.maybeMoveToResponseJsonSchem(params);\n if (!hasCallableTools(params) || shouldDisableAfc(params.config)) {\n return await this.generateContentInternal(transformedParams);\n }\n\n if (hasNonCallableTools(params)) {\n throw new Error(\n 'Automatic function calling with CallableTools and Tools is not yet supported.',\n );\n }\n\n let response: types.GenerateContentResponse;\n let functionResponseContent: types.Content;\n const automaticFunctionCallingHistory: types.Content[] = tContents(\n transformedParams.contents,\n );\n const maxRemoteCalls =\n transformedParams.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let remoteCalls = 0;\n while (remoteCalls < maxRemoteCalls) {\n response = await this.generateContentInternal(transformedParams);\n if (!response.functionCalls || response.functionCalls!.length === 0) {\n break;\n }\n\n const responseContent: types.Content = response.candidates![0].content!;\n const functionResponseParts: types.Part[] = [];\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const parts = await callableTool.callTool(response.functionCalls!);\n functionResponseParts.push(...parts);\n }\n }\n\n remoteCalls++;\n\n functionResponseContent = {\n role: 'user',\n parts: functionResponseParts,\n };\n\n transformedParams.contents = tContents(transformedParams.contents);\n (transformedParams.contents as types.Content[]).push(responseContent);\n (transformedParams.contents as types.Content[]).push(\n functionResponseContent,\n );\n\n if (shouldAppendAfcHistory(transformedParams.config)) {\n automaticFunctionCallingHistory.push(responseContent);\n automaticFunctionCallingHistory.push(functionResponseContent);\n }\n }\n if (shouldAppendAfcHistory(transformedParams.config)) {\n response!.automaticFunctionCallingHistory =\n automaticFunctionCallingHistory;\n }\n return response!;\n };\n\n /**\n * This logic is needed for GenerateContentConfig only.\n * Previously we made GenerateContentConfig.responseSchema field to accept\n * unknown. Since v1.9.0, we switch to use backend JSON schema support.\n * To maintain backward compatibility, we move the data that was treated as\n * JSON schema from the responseSchema field to the responseJsonSchema field.\n */\n private maybeMoveToResponseJsonSchem(\n params: types.GenerateContentParameters,\n ): void {\n if (params.config && params.config.responseSchema) {\n if (!params.config.responseJsonSchema) {\n if (Object.keys(params.config.responseSchema).includes('$schema')) {\n params.config.responseJsonSchema = params.config.responseSchema;\n delete params.config.responseSchema;\n }\n }\n }\n return;\n }\n\n /**\n * Makes an API request to generate content with a given model and yields the\n * response in chunks.\n *\n * For the `model` parameter, supported formats for Vertex AI API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The full resource name starts with 'projects/', for example:\n * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash'\n * - The partial resource name with 'publishers/', for example:\n * 'publishers/google/models/gemini-2.0-flash' or\n * 'publishers/meta/models/llama-3.1-405b-instruct-maas'\n * - `/` separated publisher and model name, for example:\n * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas'\n *\n * For the `model` parameter, supported formats for Gemini API include:\n * - The Gemini model ID, for example: 'gemini-2.0-flash'\n * - The model name starts with 'models/', for example:\n * 'models/gemini-2.0-flash'\n * - For tuned models, the model name starts with 'tunedModels/',\n * for example:\n * 'tunedModels/1234567890123456789'\n *\n * Some models support multimodal input and output.\n *\n * @param params - The parameters for generating content with streaming response.\n * @return The response from generating content.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateContentStream({\n * model: 'gemini-2.0-flash',\n * contents: 'why is the sky blue?',\n * config: {\n * maxOutputTokens: 200,\n * }\n * });\n * for await (const chunk of response) {\n * console.log(chunk);\n * }\n * ```\n */\n generateContentStream = async (\n params: types.GenerateContentParameters,\n ): Promise> => {\n this.maybeMoveToResponseJsonSchem(params);\n if (shouldDisableAfc(params.config)) {\n const transformedParams =\n await this.processParamsMaybeAddMcpUsage(params);\n return await this.generateContentStreamInternal(transformedParams);\n } else {\n return await this.processAfcStream(params);\n }\n };\n\n /**\n * Transforms the CallableTools in the parameters to be simply Tools, it\n * copies the params into a new object and replaces the tools, it does not\n * modify the original params. Also sets the MCP usage header if there are\n * MCP tools in the parameters.\n */\n private async processParamsMaybeAddMcpUsage(\n params: types.GenerateContentParameters,\n ): Promise {\n const tools = params.config?.tools;\n if (!tools) {\n return params;\n }\n const transformedTools = await Promise.all(\n tools.map(async (tool) => {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n return await callableTool.tool();\n }\n return tool;\n }),\n );\n const newParams: types.GenerateContentParameters = {\n model: params.model,\n contents: params.contents,\n config: {\n ...params.config,\n tools: transformedTools,\n },\n };\n newParams.config!.tools = transformedTools;\n\n if (\n params.config &&\n params.config.tools &&\n hasMcpToolUsage(params.config.tools)\n ) {\n const headers = params.config.httpOptions?.headers ?? {};\n let newHeaders = {...headers};\n if (Object.keys(newHeaders).length === 0) {\n newHeaders = this.apiClient.getDefaultHeaders();\n }\n setMcpUsageHeader(newHeaders);\n newParams.config!.httpOptions = {\n ...params.config.httpOptions,\n headers: newHeaders,\n };\n }\n return newParams;\n }\n\n private async initAfcToolsMap(\n params: types.GenerateContentParameters,\n ): Promise> {\n const afcTools: Map = new Map();\n for (const tool of params.config?.tools ?? []) {\n if (isCallableTool(tool)) {\n const callableTool = tool as types.CallableTool;\n const toolDeclaration = await callableTool.tool();\n for (const declaration of toolDeclaration.functionDeclarations ?? []) {\n if (!declaration.name) {\n throw new Error('Function declaration name is required.');\n }\n if (afcTools.has(declaration.name)) {\n throw new Error(\n `Duplicate tool declaration name: ${declaration.name}`,\n );\n }\n afcTools.set(declaration.name, callableTool);\n }\n }\n }\n return afcTools;\n }\n\n private async processAfcStream(\n params: types.GenerateContentParameters,\n ): Promise> {\n const maxRemoteCalls =\n params.config?.automaticFunctionCalling?.maximumRemoteCalls ??\n DEFAULT_MAX_REMOTE_CALLS;\n let wereFunctionsCalled = false;\n let remoteCallCount = 0;\n const afcToolsMap = await this.initAfcToolsMap(params);\n return (async function* (\n models: Models,\n afcTools: Map,\n params: types.GenerateContentParameters,\n ) {\n while (remoteCallCount < maxRemoteCalls) {\n if (wereFunctionsCalled) {\n remoteCallCount++;\n wereFunctionsCalled = false;\n }\n const transformedParams =\n await models.processParamsMaybeAddMcpUsage(params);\n const response =\n await models.generateContentStreamInternal(transformedParams);\n\n const functionResponses: types.Part[] = [];\n const responseContents: types.Content[] = [];\n\n for await (const chunk of response) {\n yield chunk;\n if (chunk.candidates && chunk.candidates[0]?.content) {\n responseContents.push(chunk.candidates[0].content);\n for (const part of chunk.candidates[0].content.parts ?? []) {\n if (remoteCallCount < maxRemoteCalls && part.functionCall) {\n if (!part.functionCall.name) {\n throw new Error(\n 'Function call name was not returned by the model.',\n );\n }\n if (!afcTools.has(part.functionCall.name)) {\n throw new Error(\n `Automatic function calling was requested, but not all the tools the model used implement the CallableTool interface. Available tools: ${afcTools.keys()}, mising tool: ${\n part.functionCall.name\n }`,\n );\n } else {\n const responseParts = await afcTools\n .get(part.functionCall.name)!\n .callTool([part.functionCall]);\n functionResponses.push(...responseParts);\n }\n }\n }\n }\n }\n\n if (functionResponses.length > 0) {\n wereFunctionsCalled = true;\n const typedResponseChunk = new types.GenerateContentResponse();\n typedResponseChunk.candidates = [\n {\n content: {\n role: 'user',\n parts: functionResponses,\n },\n },\n ];\n\n yield typedResponseChunk;\n\n const newContents: types.Content[] = [];\n newContents.push(...responseContents);\n newContents.push({\n role: 'user',\n parts: functionResponses,\n });\n const updatedContents = tContents(params.contents).concat(\n newContents,\n );\n\n params.contents = updatedContents;\n } else {\n break;\n }\n }\n })(this, afcToolsMap, params);\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n generateImages = async (\n params: types.GenerateImagesParameters,\n ): Promise => {\n return await this.generateImagesInternal(params).then((apiResponse) => {\n let positivePromptSafetyAttributes;\n const generatedImages = [];\n\n if (apiResponse?.generatedImages) {\n for (const generatedImage of apiResponse.generatedImages) {\n if (\n generatedImage &&\n generatedImage?.safetyAttributes &&\n generatedImage?.safetyAttributes?.contentType === 'Positive Prompt'\n ) {\n positivePromptSafetyAttributes = generatedImage?.safetyAttributes;\n } else {\n generatedImages.push(generatedImage);\n }\n }\n }\n let response: types.GenerateImagesResponse;\n\n if (positivePromptSafetyAttributes) {\n response = {\n generatedImages: generatedImages,\n positivePromptSafetyAttributes: positivePromptSafetyAttributes,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n } else {\n response = {\n generatedImages: generatedImages,\n sdkHttpResponse: apiResponse.sdkHttpResponse,\n };\n }\n return response;\n });\n };\n\n list = async (\n params?: types.ListModelsParameters,\n ): Promise> => {\n const defaultConfig: types.ListModelsConfig = {\n queryBase: true,\n };\n const actualConfig: types.ListModelsConfig = {\n ...defaultConfig,\n ...params?.config,\n };\n const actualParams: types.ListModelsParameters = {\n config: actualConfig,\n };\n\n if (this.apiClient.isVertexAI()) {\n if (!actualParams.config!.queryBase) {\n if (actualParams.config?.filter) {\n throw new Error(\n 'Filtering tuned models list for Vertex AI is not currently supported',\n );\n } else {\n actualParams.config!.filter = 'labels.tune-type:*';\n }\n }\n }\n\n return new Pager(\n PagedItem.PAGED_ITEM_MODELS,\n (x: types.ListModelsParameters) => this.listInternal(x),\n await this.listInternal(actualParams),\n actualParams,\n );\n };\n\n /**\n * Edits an image based on a prompt, list of reference images, and configuration.\n *\n * @param params - The parameters for editing an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.editImage({\n * model: 'imagen-3.0-capability-001',\n * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.',\n * referenceImages: [subjectReferenceImage]\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n editImage = async (\n params: types.EditImageParameters,\n ): Promise => {\n const paramsInternal: _internal_types.EditImageParametersInternal = {\n model: params.model,\n prompt: params.prompt,\n referenceImages: [],\n config: params.config,\n };\n if (params.referenceImages) {\n if (params.referenceImages) {\n paramsInternal.referenceImages = params.referenceImages.map((img) =>\n img.toReferenceImageAPI(),\n );\n }\n }\n return await this.editImageInternal(paramsInternal);\n };\n\n /**\n * Upscales an image based on an image, upscale factor, and configuration.\n * Only supported in Vertex AI currently.\n *\n * @param params - The parameters for upscaling an image.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await client.models.upscaleImage({\n * model: 'imagen-3.0-generate-002',\n * image: image,\n * upscaleFactor: 'x2',\n * config: {\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n upscaleImage = async (\n params: types.UpscaleImageParameters,\n ): Promise => {\n let apiConfig: _internal_types.UpscaleImageAPIConfigInternal = {\n numberOfImages: 1,\n mode: 'upscale',\n };\n\n if (params.config) {\n apiConfig = {...apiConfig, ...params.config};\n }\n\n const apiParams: _internal_types.UpscaleImageAPIParametersInternal = {\n model: params.model,\n image: params.image,\n upscaleFactor: params.upscaleFactor,\n config: apiConfig,\n };\n return await this.upscaleImageInternal(apiParams);\n };\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n generateVideos = async (\n params: types.GenerateVideosParameters,\n ): Promise => {\n return await this.generateVideosInternal(params);\n };\n\n private async generateContentInternal(\n params: types.GenerateContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:generateContent',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateContentResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async generateContentStreamInternal(\n params: types.GenerateContentParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromVertex(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n } else {\n const body = converters.generateContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:streamGenerateContent?alt=sse',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const apiClient = this.apiClient;\n response = apiClient.requestStream({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n }) as Promise>;\n\n return response.then(async function* (\n apiResponse: AsyncGenerator,\n ) {\n for await (const chunk of apiResponse) {\n const resp = converters.generateContentResponseFromMldev(\n (await chunk.json()) as types.GenerateContentResponse,\n );\n\n resp['sdkHttpResponse'] = {\n headers: chunk.headers,\n } as types.HttpResponse;\n\n const typedResp = new types.GenerateContentResponse();\n Object.assign(typedResp, resp);\n yield typedResp;\n }\n });\n }\n }\n\n /**\n * Calculates embeddings for the given contents. Only text is supported.\n *\n * @param params - The parameters for embedding contents.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.embedContent({\n * model: 'text-embedding-004',\n * contents: [\n * 'What is your name?',\n * 'What is your favorite color?',\n * ],\n * config: {\n * outputDimensionality: 64,\n * },\n * });\n * console.log(response);\n * ```\n */\n async embedContent(\n params: types.EmbedContentParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.embedContentParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromVertex(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.embedContentParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:batchEmbedContents',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EmbedContentResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.embedContentResponseFromMldev(apiResponse);\n const typedResp = new types.EmbedContentResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Generates an image based on a text description and configuration.\n *\n * @param params - The parameters for generating images.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.generateImages({\n * model: 'imagen-3.0-generate-002',\n * prompt: 'Robot holding a red skateboard',\n * config: {\n * numberOfImages: 1,\n * includeRaiReason: true,\n * },\n * });\n * console.log(response?.generatedImages?.[0]?.image?.imageBytes);\n * ```\n */\n private async generateImagesInternal(\n params: types.GenerateImagesParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateImagesParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromVertex(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateImagesParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.GenerateImagesResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateImagesResponseFromMldev(apiResponse);\n const typedResp = new types.GenerateImagesResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async editImageInternal(\n params: _internal_types.EditImageParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.editImageParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.EditImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.editImageResponseFromVertex(apiResponse);\n const typedResp = new types.EditImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async upscaleImageInternal(\n params: _internal_types.UpscaleImageAPIParametersInternal,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.upscaleImageAPIParametersInternalToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predict',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.UpscaleImageResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.upscaleImageResponseFromVertex(apiResponse);\n const typedResp = new types.UpscaleImageResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Fetches information about a model by name.\n *\n * @example\n * ```ts\n * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'});\n * ```\n */\n async get(params: types.GetModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.getModelParametersToMldev(this.apiClient, params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n private async listInternal(\n params: types.ListModelsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listModelsParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromVertex(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listModelsParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{models_url}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListModelsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listModelsResponseFromMldev(apiResponse);\n const typedResp = new types.ListModelsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Updates a tuned model by its name.\n *\n * @param params - The parameters for updating the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.update({\n * model: 'tuned-model-name',\n * config: {\n * displayName: 'New display name',\n * description: 'New description',\n * },\n * });\n * ```\n */\n async update(params: types.UpdateModelParameters): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.updateModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromVertex(apiResponse);\n\n return resp as types.Model;\n });\n } else {\n const body = converters.updateModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'PATCH',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.modelFromMldev(apiResponse);\n\n return resp as types.Model;\n });\n }\n }\n\n /**\n * Deletes a tuned model by its name.\n *\n * @param params - The parameters for deleting the model.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.delete({model: 'tuned-model-name'});\n * ```\n */\n async delete(\n params: types.DeleteModelParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.deleteModelParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromVertex();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.deleteModelParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'DELETE',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then(() => {\n const resp = converters.deleteModelResponseFromMldev();\n const typedResp = new types.DeleteModelResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Counts the number of tokens in the given contents. Multimodal input is\n * supported for Gemini models.\n *\n * @param params - The parameters for counting tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.countTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'The quick brown fox jumps over the lazy dog.'\n * });\n * console.log(response);\n * ```\n */\n async countTokens(\n params: types.CountTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.countTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromVertex(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.countTokensParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:countTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.CountTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.countTokensResponseFromMldev(apiResponse);\n const typedResp = new types.CountTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n /**\n * Given a list of contents, returns a corresponding TokensInfo containing\n * the list of tokens and list of token ids.\n *\n * This method is not supported by the Gemini Developer API.\n *\n * @param params - The parameters for computing tokens.\n * @return The response from the API.\n *\n * @example\n * ```ts\n * const response = await ai.models.computeTokens({\n * model: 'gemini-2.0-flash',\n * contents: 'What is your name?'\n * });\n * console.log(response);\n * ```\n */\n async computeTokens(\n params: types.ComputeTokensParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.computeTokensParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:computeTokens',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ComputeTokensResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.computeTokensResponseFromVertex(apiResponse);\n const typedResp = new types.ComputeTokensResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n /**\n * Generates videos based on a text description and configuration.\n *\n * @param params - The parameters for generating videos.\n * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method.\n *\n * @example\n * ```ts\n * const operation = await ai.models.generateVideos({\n * model: 'veo-2.0-generate-001',\n * prompt: 'A neon hologram of a cat driving at top speed',\n * config: {\n * numberOfVideos: 1\n * });\n *\n * while (!operation.done) {\n * await new Promise(resolve => setTimeout(resolve, 10000));\n * operation = await ai.operations.getVideosOperation({operation: operation});\n * }\n *\n * console.log(operation.response?.generatedVideos?.[0]?.video?.uri);\n * ```\n */\n\n private async generateVideosInternal(\n params: types.GenerateVideosParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.generateVideosParametersToVertex(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromVertex(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.generateVideosParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n '{model}:predictLongRunning',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.generateVideosOperationFromMldev(apiResponse);\n const typedResp = new types.GenerateVideosOperation();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as types from '../types.js';\n\nexport function getOperationParametersToMldev(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function getOperationParametersToVertex(\n fromObject: types.GetOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(\n toObject,\n ['_url', 'operationName'],\n fromOperationName,\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function fetchPredictOperationParametersToVertex(\n fromObject: types.FetchPredictOperationParameters,\n): Record {\n const toObject: Record = {};\n\n const fromOperationName = common.getValueByPath(fromObject, [\n 'operationName',\n ]);\n if (fromOperationName != null) {\n common.setValueByPath(toObject, ['operationName'], fromOperationName);\n }\n\n const fromResourceName = common.getValueByPath(fromObject, ['resourceName']);\n if (fromResourceName != null) {\n common.setValueByPath(toObject, ['_url', 'resourceName'], fromResourceName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_operations_converters.js';\nimport * as types from './types.js';\n\nexport class Operations extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async getVideosOperation(\n parameters: types.OperationGetParameters<\n types.GenerateVideosResponse,\n types.GenerateVideosOperation\n >,\n ): Promise {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n /**\n * Gets the status of a long-running operation.\n *\n * @param parameters The parameters for the get operation request.\n * @return The updated Operation object, with the latest status or result.\n */\n async get>(\n parameters: types.OperationGetParameters,\n ): Promise> {\n const operation = parameters.operation;\n const config = parameters.config;\n\n if (operation.name === undefined || operation.name === '') {\n throw new Error('Operation name is required.');\n }\n\n if (this.apiClient.isVertexAI()) {\n const resourceName = operation.name.split('/operations/')[0];\n let httpOptions: types.HttpOptions | undefined = undefined;\n\n if (config && 'httpOptions' in config) {\n httpOptions = config.httpOptions;\n }\n\n const rawOperation = await this.fetchPredictVideosOperationInternal({\n operationName: operation.name,\n resourceName: resourceName,\n config: {httpOptions: httpOptions},\n });\n\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: true,\n });\n } else {\n const rawOperation = await this.getVideosOperationInternal({\n operationName: operation.name,\n config: config,\n });\n return operation._fromAPIResponse({\n apiResponse: rawOperation,\n isVertexAI: false,\n });\n }\n }\n\n private async getVideosOperationInternal(\n params: types.GetOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getOperationParametersToVertex(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n const body = converters.getOperationParametersToMldev(params);\n path = common.formatMap(\n '{operationName}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n }\n }\n\n private async fetchPredictVideosOperationInternal(\n params: types.FetchPredictOperationParameters,\n ): Promise> {\n let response: Promise>;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.fetchPredictOperationParametersToVertex(params);\n path = common.formatMap(\n '{resourceName}:fetchPredictOperation',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise>;\n\n return response;\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from '../_api_client.js';\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function prebuiltVoiceConfigToMldev(\n fromObject: types.PrebuiltVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceName = common.getValueByPath(fromObject, ['voiceName']);\n if (fromVoiceName != null) {\n common.setValueByPath(toObject, ['voiceName'], fromVoiceName);\n }\n\n return toObject;\n}\n\nexport function voiceConfigToMldev(\n fromObject: types.VoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromPrebuiltVoiceConfig = common.getValueByPath(fromObject, [\n 'prebuiltVoiceConfig',\n ]);\n if (fromPrebuiltVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['prebuiltVoiceConfig'],\n prebuiltVoiceConfigToMldev(fromPrebuiltVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function speakerVoiceConfigToMldev(\n fromObject: types.SpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeaker = common.getValueByPath(fromObject, ['speaker']);\n if (fromSpeaker != null) {\n common.setValueByPath(toObject, ['speaker'], fromSpeaker);\n }\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n return toObject;\n}\n\nexport function multiSpeakerVoiceConfigToMldev(\n fromObject: types.MultiSpeakerVoiceConfig,\n): Record {\n const toObject: Record = {};\n\n const fromSpeakerVoiceConfigs = common.getValueByPath(fromObject, [\n 'speakerVoiceConfigs',\n ]);\n if (fromSpeakerVoiceConfigs != null) {\n let transformedList = fromSpeakerVoiceConfigs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return speakerVoiceConfigToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['speakerVoiceConfigs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function speechConfigToMldev(\n fromObject: types.SpeechConfig,\n): Record {\n const toObject: Record = {};\n\n const fromVoiceConfig = common.getValueByPath(fromObject, ['voiceConfig']);\n if (fromVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['voiceConfig'],\n voiceConfigToMldev(fromVoiceConfig),\n );\n }\n\n const fromMultiSpeakerVoiceConfig = common.getValueByPath(fromObject, [\n 'multiSpeakerVoiceConfig',\n ]);\n if (fromMultiSpeakerVoiceConfig != null) {\n common.setValueByPath(\n toObject,\n ['multiSpeakerVoiceConfig'],\n multiSpeakerVoiceConfigToMldev(fromMultiSpeakerVoiceConfig),\n );\n }\n\n const fromLanguageCode = common.getValueByPath(fromObject, ['languageCode']);\n if (fromLanguageCode != null) {\n common.setValueByPath(toObject, ['languageCode'], fromLanguageCode);\n }\n\n return toObject;\n}\n\nexport function videoMetadataToMldev(\n fromObject: types.VideoMetadata,\n): Record {\n const toObject: Record = {};\n\n const fromFps = common.getValueByPath(fromObject, ['fps']);\n if (fromFps != null) {\n common.setValueByPath(toObject, ['fps'], fromFps);\n }\n\n const fromEndOffset = common.getValueByPath(fromObject, ['endOffset']);\n if (fromEndOffset != null) {\n common.setValueByPath(toObject, ['endOffset'], fromEndOffset);\n }\n\n const fromStartOffset = common.getValueByPath(fromObject, ['startOffset']);\n if (fromStartOffset != null) {\n common.setValueByPath(toObject, ['startOffset'], fromStartOffset);\n }\n\n return toObject;\n}\n\nexport function blobToMldev(fromObject: types.Blob): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromData = common.getValueByPath(fromObject, ['data']);\n if (fromData != null) {\n common.setValueByPath(toObject, ['data'], fromData);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function fileDataToMldev(\n fromObject: types.FileData,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['displayName']) !== undefined) {\n throw new Error('displayName parameter is not supported in Gemini API.');\n }\n\n const fromFileUri = common.getValueByPath(fromObject, ['fileUri']);\n if (fromFileUri != null) {\n common.setValueByPath(toObject, ['fileUri'], fromFileUri);\n }\n\n const fromMimeType = common.getValueByPath(fromObject, ['mimeType']);\n if (fromMimeType != null) {\n common.setValueByPath(toObject, ['mimeType'], fromMimeType);\n }\n\n return toObject;\n}\n\nexport function partToMldev(fromObject: types.Part): Record {\n const toObject: Record = {};\n\n const fromVideoMetadata = common.getValueByPath(fromObject, [\n 'videoMetadata',\n ]);\n if (fromVideoMetadata != null) {\n common.setValueByPath(\n toObject,\n ['videoMetadata'],\n videoMetadataToMldev(fromVideoMetadata),\n );\n }\n\n const fromThought = common.getValueByPath(fromObject, ['thought']);\n if (fromThought != null) {\n common.setValueByPath(toObject, ['thought'], fromThought);\n }\n\n const fromInlineData = common.getValueByPath(fromObject, ['inlineData']);\n if (fromInlineData != null) {\n common.setValueByPath(\n toObject,\n ['inlineData'],\n blobToMldev(fromInlineData),\n );\n }\n\n const fromFileData = common.getValueByPath(fromObject, ['fileData']);\n if (fromFileData != null) {\n common.setValueByPath(\n toObject,\n ['fileData'],\n fileDataToMldev(fromFileData),\n );\n }\n\n const fromThoughtSignature = common.getValueByPath(fromObject, [\n 'thoughtSignature',\n ]);\n if (fromThoughtSignature != null) {\n common.setValueByPath(toObject, ['thoughtSignature'], fromThoughtSignature);\n }\n\n const fromCodeExecutionResult = common.getValueByPath(fromObject, [\n 'codeExecutionResult',\n ]);\n if (fromCodeExecutionResult != null) {\n common.setValueByPath(\n toObject,\n ['codeExecutionResult'],\n fromCodeExecutionResult,\n );\n }\n\n const fromExecutableCode = common.getValueByPath(fromObject, [\n 'executableCode',\n ]);\n if (fromExecutableCode != null) {\n common.setValueByPath(toObject, ['executableCode'], fromExecutableCode);\n }\n\n const fromFunctionCall = common.getValueByPath(fromObject, ['functionCall']);\n if (fromFunctionCall != null) {\n common.setValueByPath(toObject, ['functionCall'], fromFunctionCall);\n }\n\n const fromFunctionResponse = common.getValueByPath(fromObject, [\n 'functionResponse',\n ]);\n if (fromFunctionResponse != null) {\n common.setValueByPath(toObject, ['functionResponse'], fromFunctionResponse);\n }\n\n const fromText = common.getValueByPath(fromObject, ['text']);\n if (fromText != null) {\n common.setValueByPath(toObject, ['text'], fromText);\n }\n\n return toObject;\n}\n\nexport function contentToMldev(\n fromObject: types.Content,\n): Record {\n const toObject: Record = {};\n\n const fromParts = common.getValueByPath(fromObject, ['parts']);\n if (fromParts != null) {\n let transformedList = fromParts;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return partToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['parts'], transformedList);\n }\n\n const fromRole = common.getValueByPath(fromObject, ['role']);\n if (fromRole != null) {\n common.setValueByPath(toObject, ['role'], fromRole);\n }\n\n return toObject;\n}\n\nexport function functionDeclarationToMldev(\n fromObject: types.FunctionDeclaration,\n): Record {\n const toObject: Record = {};\n\n const fromBehavior = common.getValueByPath(fromObject, ['behavior']);\n if (fromBehavior != null) {\n common.setValueByPath(toObject, ['behavior'], fromBehavior);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromParameters = common.getValueByPath(fromObject, ['parameters']);\n if (fromParameters != null) {\n common.setValueByPath(toObject, ['parameters'], fromParameters);\n }\n\n const fromParametersJsonSchema = common.getValueByPath(fromObject, [\n 'parametersJsonSchema',\n ]);\n if (fromParametersJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['parametersJsonSchema'],\n fromParametersJsonSchema,\n );\n }\n\n const fromResponse = common.getValueByPath(fromObject, ['response']);\n if (fromResponse != null) {\n common.setValueByPath(toObject, ['response'], fromResponse);\n }\n\n const fromResponseJsonSchema = common.getValueByPath(fromObject, [\n 'responseJsonSchema',\n ]);\n if (fromResponseJsonSchema != null) {\n common.setValueByPath(\n toObject,\n ['responseJsonSchema'],\n fromResponseJsonSchema,\n );\n }\n\n return toObject;\n}\n\nexport function intervalToMldev(\n fromObject: types.Interval,\n): Record {\n const toObject: Record = {};\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n return toObject;\n}\n\nexport function googleSearchToMldev(\n fromObject: types.GoogleSearch,\n): Record {\n const toObject: Record = {};\n\n const fromTimeRangeFilter = common.getValueByPath(fromObject, [\n 'timeRangeFilter',\n ]);\n if (fromTimeRangeFilter != null) {\n common.setValueByPath(\n toObject,\n ['timeRangeFilter'],\n intervalToMldev(fromTimeRangeFilter),\n );\n }\n\n return toObject;\n}\n\nexport function dynamicRetrievalConfigToMldev(\n fromObject: types.DynamicRetrievalConfig,\n): Record {\n const toObject: Record = {};\n\n const fromMode = common.getValueByPath(fromObject, ['mode']);\n if (fromMode != null) {\n common.setValueByPath(toObject, ['mode'], fromMode);\n }\n\n const fromDynamicThreshold = common.getValueByPath(fromObject, [\n 'dynamicThreshold',\n ]);\n if (fromDynamicThreshold != null) {\n common.setValueByPath(toObject, ['dynamicThreshold'], fromDynamicThreshold);\n }\n\n return toObject;\n}\n\nexport function googleSearchRetrievalToMldev(\n fromObject: types.GoogleSearchRetrieval,\n): Record {\n const toObject: Record = {};\n\n const fromDynamicRetrievalConfig = common.getValueByPath(fromObject, [\n 'dynamicRetrievalConfig',\n ]);\n if (fromDynamicRetrievalConfig != null) {\n common.setValueByPath(\n toObject,\n ['dynamicRetrievalConfig'],\n dynamicRetrievalConfigToMldev(fromDynamicRetrievalConfig),\n );\n }\n\n return toObject;\n}\n\nexport function urlContextToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function toolComputerUseToMldev(\n fromObject: types.ToolComputerUse,\n): Record {\n const toObject: Record = {};\n\n const fromExcludedPredefinedFunctions = common.getValueByPath(fromObject, [\n 'excludedPredefinedFunctions',\n ]);\n if (fromExcludedPredefinedFunctions != null) {\n common.setValueByPath(\n toObject,\n ['excludedPredefinedFunctions'],\n fromExcludedPredefinedFunctions,\n );\n }\n\n const fromEnvironment = common.getValueByPath(fromObject, ['environment']);\n if (fromEnvironment != null) {\n common.setValueByPath(toObject, ['environment'], fromEnvironment);\n }\n\n return toObject;\n}\n\nexport function toolToMldev(fromObject: types.Tool): Record {\n const toObject: Record = {};\n\n const fromFunctionDeclarations = common.getValueByPath(fromObject, [\n 'functionDeclarations',\n ]);\n if (fromFunctionDeclarations != null) {\n let transformedList = fromFunctionDeclarations;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return functionDeclarationToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['functionDeclarations'], transformedList);\n }\n\n if (common.getValueByPath(fromObject, ['retrieval']) !== undefined) {\n throw new Error('retrieval parameter is not supported in Gemini API.');\n }\n\n const fromGoogleSearch = common.getValueByPath(fromObject, ['googleSearch']);\n if (fromGoogleSearch != null) {\n common.setValueByPath(\n toObject,\n ['googleSearch'],\n googleSearchToMldev(fromGoogleSearch),\n );\n }\n\n const fromGoogleSearchRetrieval = common.getValueByPath(fromObject, [\n 'googleSearchRetrieval',\n ]);\n if (fromGoogleSearchRetrieval != null) {\n common.setValueByPath(\n toObject,\n ['googleSearchRetrieval'],\n googleSearchRetrievalToMldev(fromGoogleSearchRetrieval),\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['enterpriseWebSearch']) !== undefined\n ) {\n throw new Error(\n 'enterpriseWebSearch parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['googleMaps']) !== undefined) {\n throw new Error('googleMaps parameter is not supported in Gemini API.');\n }\n\n const fromUrlContext = common.getValueByPath(fromObject, ['urlContext']);\n if (fromUrlContext != null) {\n common.setValueByPath(toObject, ['urlContext'], urlContextToMldev());\n }\n\n const fromComputerUse = common.getValueByPath(fromObject, ['computerUse']);\n if (fromComputerUse != null) {\n common.setValueByPath(\n toObject,\n ['computerUse'],\n toolComputerUseToMldev(fromComputerUse),\n );\n }\n\n const fromCodeExecution = common.getValueByPath(fromObject, [\n 'codeExecution',\n ]);\n if (fromCodeExecution != null) {\n common.setValueByPath(toObject, ['codeExecution'], fromCodeExecution);\n }\n\n return toObject;\n}\n\nexport function sessionResumptionConfigToMldev(\n fromObject: types.SessionResumptionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromHandle = common.getValueByPath(fromObject, ['handle']);\n if (fromHandle != null) {\n common.setValueByPath(toObject, ['handle'], fromHandle);\n }\n\n if (common.getValueByPath(fromObject, ['transparent']) !== undefined) {\n throw new Error('transparent parameter is not supported in Gemini API.');\n }\n\n return toObject;\n}\n\nexport function audioTranscriptionConfigToMldev(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n\nexport function automaticActivityDetectionToMldev(\n fromObject: types.AutomaticActivityDetection,\n): Record {\n const toObject: Record = {};\n\n const fromDisabled = common.getValueByPath(fromObject, ['disabled']);\n if (fromDisabled != null) {\n common.setValueByPath(toObject, ['disabled'], fromDisabled);\n }\n\n const fromStartOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'startOfSpeechSensitivity',\n ]);\n if (fromStartOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['startOfSpeechSensitivity'],\n fromStartOfSpeechSensitivity,\n );\n }\n\n const fromEndOfSpeechSensitivity = common.getValueByPath(fromObject, [\n 'endOfSpeechSensitivity',\n ]);\n if (fromEndOfSpeechSensitivity != null) {\n common.setValueByPath(\n toObject,\n ['endOfSpeechSensitivity'],\n fromEndOfSpeechSensitivity,\n );\n }\n\n const fromPrefixPaddingMs = common.getValueByPath(fromObject, [\n 'prefixPaddingMs',\n ]);\n if (fromPrefixPaddingMs != null) {\n common.setValueByPath(toObject, ['prefixPaddingMs'], fromPrefixPaddingMs);\n }\n\n const fromSilenceDurationMs = common.getValueByPath(fromObject, [\n 'silenceDurationMs',\n ]);\n if (fromSilenceDurationMs != null) {\n common.setValueByPath(\n toObject,\n ['silenceDurationMs'],\n fromSilenceDurationMs,\n );\n }\n\n return toObject;\n}\n\nexport function realtimeInputConfigToMldev(\n fromObject: types.RealtimeInputConfig,\n): Record {\n const toObject: Record = {};\n\n const fromAutomaticActivityDetection = common.getValueByPath(fromObject, [\n 'automaticActivityDetection',\n ]);\n if (fromAutomaticActivityDetection != null) {\n common.setValueByPath(\n toObject,\n ['automaticActivityDetection'],\n automaticActivityDetectionToMldev(fromAutomaticActivityDetection),\n );\n }\n\n const fromActivityHandling = common.getValueByPath(fromObject, [\n 'activityHandling',\n ]);\n if (fromActivityHandling != null) {\n common.setValueByPath(toObject, ['activityHandling'], fromActivityHandling);\n }\n\n const fromTurnCoverage = common.getValueByPath(fromObject, ['turnCoverage']);\n if (fromTurnCoverage != null) {\n common.setValueByPath(toObject, ['turnCoverage'], fromTurnCoverage);\n }\n\n return toObject;\n}\n\nexport function slidingWindowToMldev(\n fromObject: types.SlidingWindow,\n): Record {\n const toObject: Record = {};\n\n const fromTargetTokens = common.getValueByPath(fromObject, ['targetTokens']);\n if (fromTargetTokens != null) {\n common.setValueByPath(toObject, ['targetTokens'], fromTargetTokens);\n }\n\n return toObject;\n}\n\nexport function contextWindowCompressionConfigToMldev(\n fromObject: types.ContextWindowCompressionConfig,\n): Record {\n const toObject: Record = {};\n\n const fromTriggerTokens = common.getValueByPath(fromObject, [\n 'triggerTokens',\n ]);\n if (fromTriggerTokens != null) {\n common.setValueByPath(toObject, ['triggerTokens'], fromTriggerTokens);\n }\n\n const fromSlidingWindow = common.getValueByPath(fromObject, [\n 'slidingWindow',\n ]);\n if (fromSlidingWindow != null) {\n common.setValueByPath(\n toObject,\n ['slidingWindow'],\n slidingWindowToMldev(fromSlidingWindow),\n );\n }\n\n return toObject;\n}\n\nexport function proactivityConfigToMldev(\n fromObject: types.ProactivityConfig,\n): Record {\n const toObject: Record = {};\n\n const fromProactiveAudio = common.getValueByPath(fromObject, [\n 'proactiveAudio',\n ]);\n if (fromProactiveAudio != null) {\n common.setValueByPath(toObject, ['proactiveAudio'], fromProactiveAudio);\n }\n\n return toObject;\n}\n\nexport function liveConnectConfigToMldev(\n fromObject: types.LiveConnectConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGenerationConfig = common.getValueByPath(fromObject, [\n 'generationConfig',\n ]);\n if (parentObject !== undefined && fromGenerationConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig'],\n fromGenerationConfig,\n );\n }\n\n const fromResponseModalities = common.getValueByPath(fromObject, [\n 'responseModalities',\n ]);\n if (parentObject !== undefined && fromResponseModalities != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'responseModalities'],\n fromResponseModalities,\n );\n }\n\n const fromTemperature = common.getValueByPath(fromObject, ['temperature']);\n if (parentObject !== undefined && fromTemperature != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'temperature'],\n fromTemperature,\n );\n }\n\n const fromTopP = common.getValueByPath(fromObject, ['topP']);\n if (parentObject !== undefined && fromTopP != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topP'],\n fromTopP,\n );\n }\n\n const fromTopK = common.getValueByPath(fromObject, ['topK']);\n if (parentObject !== undefined && fromTopK != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'topK'],\n fromTopK,\n );\n }\n\n const fromMaxOutputTokens = common.getValueByPath(fromObject, [\n 'maxOutputTokens',\n ]);\n if (parentObject !== undefined && fromMaxOutputTokens != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'maxOutputTokens'],\n fromMaxOutputTokens,\n );\n }\n\n const fromMediaResolution = common.getValueByPath(fromObject, [\n 'mediaResolution',\n ]);\n if (parentObject !== undefined && fromMediaResolution != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'mediaResolution'],\n fromMediaResolution,\n );\n }\n\n const fromSeed = common.getValueByPath(fromObject, ['seed']);\n if (parentObject !== undefined && fromSeed != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'seed'],\n fromSeed,\n );\n }\n\n const fromSpeechConfig = common.getValueByPath(fromObject, ['speechConfig']);\n if (parentObject !== undefined && fromSpeechConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'speechConfig'],\n speechConfigToMldev(t.tLiveSpeechConfig(fromSpeechConfig)),\n );\n }\n\n const fromEnableAffectiveDialog = common.getValueByPath(fromObject, [\n 'enableAffectiveDialog',\n ]);\n if (parentObject !== undefined && fromEnableAffectiveDialog != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'generationConfig', 'enableAffectiveDialog'],\n fromEnableAffectiveDialog,\n );\n }\n\n const fromSystemInstruction = common.getValueByPath(fromObject, [\n 'systemInstruction',\n ]);\n if (parentObject !== undefined && fromSystemInstruction != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'systemInstruction'],\n contentToMldev(t.tContent(fromSystemInstruction)),\n );\n }\n\n const fromTools = common.getValueByPath(fromObject, ['tools']);\n if (parentObject !== undefined && fromTools != null) {\n let transformedList = t.tTools(fromTools);\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return toolToMldev(t.tTool(item));\n });\n }\n common.setValueByPath(parentObject, ['setup', 'tools'], transformedList);\n }\n\n const fromSessionResumption = common.getValueByPath(fromObject, [\n 'sessionResumption',\n ]);\n if (parentObject !== undefined && fromSessionResumption != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'sessionResumption'],\n sessionResumptionConfigToMldev(fromSessionResumption),\n );\n }\n\n const fromInputAudioTranscription = common.getValueByPath(fromObject, [\n 'inputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromInputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'inputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromOutputAudioTranscription = common.getValueByPath(fromObject, [\n 'outputAudioTranscription',\n ]);\n if (parentObject !== undefined && fromOutputAudioTranscription != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'outputAudioTranscription'],\n audioTranscriptionConfigToMldev(),\n );\n }\n\n const fromRealtimeInputConfig = common.getValueByPath(fromObject, [\n 'realtimeInputConfig',\n ]);\n if (parentObject !== undefined && fromRealtimeInputConfig != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'realtimeInputConfig'],\n realtimeInputConfigToMldev(fromRealtimeInputConfig),\n );\n }\n\n const fromContextWindowCompression = common.getValueByPath(fromObject, [\n 'contextWindowCompression',\n ]);\n if (parentObject !== undefined && fromContextWindowCompression != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'contextWindowCompression'],\n contextWindowCompressionConfigToMldev(fromContextWindowCompression),\n );\n }\n\n const fromProactivity = common.getValueByPath(fromObject, ['proactivity']);\n if (parentObject !== undefined && fromProactivity != null) {\n common.setValueByPath(\n parentObject,\n ['setup', 'proactivity'],\n proactivityConfigToMldev(fromProactivity),\n );\n }\n\n return toObject;\n}\n\nexport function liveConnectConstraintsToMldev(\n apiClient: ApiClient,\n fromObject: types.LiveConnectConstraints,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(\n toObject,\n ['setup', 'model'],\n t.tModel(apiClient, fromModel),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n liveConnectConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenConfigToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromExpireTime = common.getValueByPath(fromObject, ['expireTime']);\n if (parentObject !== undefined && fromExpireTime != null) {\n common.setValueByPath(parentObject, ['expireTime'], fromExpireTime);\n }\n\n const fromNewSessionExpireTime = common.getValueByPath(fromObject, [\n 'newSessionExpireTime',\n ]);\n if (parentObject !== undefined && fromNewSessionExpireTime != null) {\n common.setValueByPath(\n parentObject,\n ['newSessionExpireTime'],\n fromNewSessionExpireTime,\n );\n }\n\n const fromUses = common.getValueByPath(fromObject, ['uses']);\n if (parentObject !== undefined && fromUses != null) {\n common.setValueByPath(parentObject, ['uses'], fromUses);\n }\n\n const fromLiveConnectConstraints = common.getValueByPath(fromObject, [\n 'liveConnectConstraints',\n ]);\n if (parentObject !== undefined && fromLiveConnectConstraints != null) {\n common.setValueByPath(\n parentObject,\n ['bidiGenerateContentSetup'],\n liveConnectConstraintsToMldev(apiClient, fromLiveConnectConstraints),\n );\n }\n\n const fromLockAdditionalFields = common.getValueByPath(fromObject, [\n 'lockAdditionalFields',\n ]);\n if (parentObject !== undefined && fromLockAdditionalFields != null) {\n common.setValueByPath(\n parentObject,\n ['fieldMask'],\n fromLockAdditionalFields,\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToMldev(\n apiClient: ApiClient,\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createAuthTokenConfigToMldev(apiClient, fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function createAuthTokenParametersToVertex(\n fromObject: types.CreateAuthTokenParameters,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['config']) !== undefined) {\n throw new Error('config parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function authTokenFromMldev(\n fromObject: types.AuthToken,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n return toObject;\n}\n\nexport function authTokenFromVertex(): Record {\n const toObject: Record = {};\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tokens_converters.js';\nimport * as types from './types.js';\n\n/**\n * Returns a comma-separated list of field masks from a given object.\n *\n * @param setup The object to extract field masks from.\n * @return A comma-separated list of field masks.\n */\nfunction getFieldMasks(setup: Record): string {\n const fields: string[] = [];\n\n for (const key in setup) {\n if (Object.prototype.hasOwnProperty.call(setup, key)) {\n const value = setup[key];\n // 2nd layer, recursively get field masks see TODO(b/418290100)\n if (\n typeof value === 'object' &&\n value != null &&\n Object.keys(value).length > 0\n ) {\n const field = Object.keys(value).map((kk) => `${key}.${kk}`);\n fields.push(...field);\n } else {\n fields.push(key); // 1st layer\n }\n }\n }\n\n return fields.join(',');\n}\n\n/**\n * Converts bidiGenerateContentSetup.\n * @param requestDict - The request dictionary.\n * @param config - The configuration object.\n * @return - The modified request dictionary.\n */\nfunction convertBidiSetupToTokenSetup(\n requestDict: Record,\n config?: {lockAdditionalFields?: string[]},\n): Record {\n // Convert bidiGenerateContentSetup from bidiGenerateContentSetup.setup.\n let setupForMaskGeneration: Record | null = null;\n const bidiGenerateContentSetupValue = requestDict['bidiGenerateContentSetup'];\n if (\n typeof bidiGenerateContentSetupValue === 'object' &&\n bidiGenerateContentSetupValue !== null &&\n 'setup' in bidiGenerateContentSetupValue\n ) {\n // Now we know bidiGenerateContentSetupValue is an object and has a 'setup'\n // property.\n const innerSetup = (bidiGenerateContentSetupValue as {setup: unknown})\n .setup;\n\n if (typeof innerSetup === 'object' && innerSetup !== null) {\n // Valid inner setup found.\n requestDict['bidiGenerateContentSetup'] = innerSetup;\n setupForMaskGeneration = innerSetup as Record;\n } else {\n // `bidiGenerateContentSetupValue.setup` is not a valid object; treat as\n // if bidiGenerateContentSetup is invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n } else if (bidiGenerateContentSetupValue !== undefined) {\n // `bidiGenerateContentSetup` exists but not in the expected\n // shape {setup: {...}}; treat as invalid.\n delete requestDict['bidiGenerateContentSetup'];\n }\n\n const preExistingFieldMask = requestDict['fieldMask'];\n // Handle mask generation setup.\n if (setupForMaskGeneration) {\n const generatedMaskFromBidi = getFieldMasks(setupForMaskGeneration);\n\n if (\n Array.isArray(config?.lockAdditionalFields) &&\n config?.lockAdditionalFields.length === 0\n ) {\n // Case 1: lockAdditionalFields is an empty array. Lock only fields from\n // bidi setup.\n if (generatedMaskFromBidi) {\n // Only assign if mask is not empty\n requestDict['fieldMask'] = generatedMaskFromBidi;\n } else {\n delete requestDict['fieldMask']; // If mask is empty, effectively no\n // specific fields locked by bidi\n }\n } else if (\n config?.lockAdditionalFields &&\n config.lockAdditionalFields.length > 0 &&\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // Case 2: Lock fields from bidi setup + additional fields\n // (preExistingFieldMask).\n\n const generationConfigFields = [\n 'temperature',\n 'topK',\n 'topP',\n 'maxOutputTokens',\n 'responseModalities',\n 'seed',\n 'speechConfig',\n ];\n\n let mappedFieldsFromPreExisting: string[] = [];\n if (preExistingFieldMask.length > 0) {\n mappedFieldsFromPreExisting = preExistingFieldMask.map((field) => {\n if (generationConfigFields.includes(field)) {\n return `generationConfig.${field}`;\n }\n return field; // Keep original field name if not in\n // generationConfigFields\n });\n }\n\n const finalMaskParts: string[] = [];\n if (generatedMaskFromBidi) {\n finalMaskParts.push(generatedMaskFromBidi);\n }\n if (mappedFieldsFromPreExisting.length > 0) {\n finalMaskParts.push(...mappedFieldsFromPreExisting);\n }\n\n if (finalMaskParts.length > 0) {\n requestDict['fieldMask'] = finalMaskParts.join(',');\n } else {\n // If no fields from bidi and no valid additional fields from\n // pre-existing mask.\n delete requestDict['fieldMask'];\n }\n } else {\n // Case 3: \"Lock all fields\" (meaning, don't send a field_mask, let server\n // defaults apply or all are mutable). This is hit if:\n // - `config.lockAdditionalFields` is undefined.\n // - `config.lockAdditionalFields` is non-empty, BUT\n // `preExistingFieldMask` is null, not a string, or an empty string.\n delete requestDict['fieldMask'];\n }\n } else {\n // No valid `bidiGenerateContentSetup` was found or extracted.\n // \"Lock additional null fields if any\".\n if (\n preExistingFieldMask !== null &&\n Array.isArray(preExistingFieldMask) &&\n preExistingFieldMask.length > 0\n ) {\n // If there's a pre-existing field mask, it's a string, and it's not\n // empty, then we should lock all fields.\n requestDict['fieldMask'] = preExistingFieldMask.join(',');\n } else {\n delete requestDict['fieldMask'];\n }\n }\n\n return requestDict;\n}\n\nexport class Tokens extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n /**\n * Creates an ephemeral auth token resource.\n *\n * @experimental\n *\n * @remarks\n * Ephemeral auth tokens is only supported in the Gemini Developer API.\n * It can be used for the session connection to the Live constrained API.\n * Support in v1alpha only.\n *\n * @param params - The parameters for the create request.\n * @return The created auth token.\n *\n * @example\n * ```ts\n * const ai = new GoogleGenAI({\n * apiKey: token.name,\n * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only.\n * });\n *\n * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig\n * // when using the token in Live API sessions. Each session connection can\n * // use a different configuration.\n * const config: CreateAuthTokenConfig = {\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 2: If LiveEphemeralParameters is set, lock all fields in\n * // LiveConnectConfig when using the token in Live API sessions. For\n * // example, changing `outputAudioTranscription` in the Live API\n * // connection will be ignored by the API.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * }\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // set, lock LiveConnectConfig with set and additional fields (e.g.\n * // responseModalities, systemInstruction, temperature in this example) when\n * // using the token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: ['temperature'],\n * }\n * const token = await ai.tokens.create(config);\n *\n * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is\n * // empty array, lock LiveConnectConfig with set fields (e.g.\n * // responseModalities, systemInstruction in this example) when using the\n * // token in Live API sessions.\n * const config: CreateAuthTokenConfig =\n * uses: 3,\n * expireTime: '2025-05-01T00:00:00Z',\n * LiveEphemeralParameters: {\n * model: 'gemini-2.0-flash-001',\n * config: {\n * 'responseModalities': ['AUDIO'],\n * 'systemInstruction': 'Always answer in English.',\n * }\n * },\n * lockAdditionalFields: [],\n * }\n * const token = await ai.tokens.create(config);\n * ```\n */\n\n async create(\n params: types.CreateAuthTokenParameters,\n ): Promise {\n let response: Promise;\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'The client.tokens.create method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createAuthTokenParametersToMldev(\n this.apiClient,\n params,\n );\n path = common.formatMap(\n 'auth_tokens',\n body['_url'] as Record,\n );\n\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n const transformedBody = convertBidiSetupToTokenSetup(body, params.config);\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(transformedBody),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.authTokenFromMldev(apiResponse);\n\n return resp as types.AuthToken;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport * as common from '../_common.js';\nimport * as t from '../_transformers.js';\nimport * as types from '../types.js';\n\nexport function getTuningJobParametersToMldev(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToMldev(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToMldev(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningExampleToMldev(\n fromObject: types.TuningExample,\n): Record {\n const toObject: Record = {};\n\n const fromTextInput = common.getValueByPath(fromObject, ['textInput']);\n if (fromTextInput != null) {\n common.setValueByPath(toObject, ['textInput'], fromTextInput);\n }\n\n const fromOutput = common.getValueByPath(fromObject, ['output']);\n if (fromOutput != null) {\n common.setValueByPath(toObject, ['output'], fromOutput);\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToMldev(\n fromObject: types.TuningDataset,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['gcsUri']) !== undefined) {\n throw new Error('gcsUri parameter is not supported in Gemini API.');\n }\n\n if (\n common.getValueByPath(fromObject, ['vertexDatasetResource']) !== undefined\n ) {\n throw new Error(\n 'vertexDatasetResource parameter is not supported in Gemini API.',\n );\n }\n\n const fromExamples = common.getValueByPath(fromObject, ['examples']);\n if (fromExamples != null) {\n let transformedList = fromExamples;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningExampleToMldev(item);\n });\n }\n common.setValueByPath(toObject, ['examples', 'examples'], transformedList);\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToMldev(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n if (common.getValueByPath(fromObject, ['validationDataset']) !== undefined) {\n throw new Error(\n 'validationDataset parameter is not supported in Gemini API.',\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['displayName'],\n fromTunedModelDisplayName,\n );\n }\n\n if (common.getValueByPath(fromObject, ['description']) !== undefined) {\n throw new Error('description parameter is not supported in Gemini API.');\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (fromLearningRateMultiplier != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'hyperparameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n if (\n common.getValueByPath(fromObject, ['exportLastCheckpointOnly']) !==\n undefined\n ) {\n throw new Error(\n 'exportLastCheckpointOnly parameter is not supported in Gemini API.',\n );\n }\n\n if (common.getValueByPath(fromObject, ['adapterSize']) !== undefined) {\n throw new Error('adapterSize parameter is not supported in Gemini API.');\n }\n\n const fromBatchSize = common.getValueByPath(fromObject, ['batchSize']);\n if (parentObject !== undefined && fromBatchSize != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'batchSize'],\n fromBatchSize,\n );\n }\n\n const fromLearningRate = common.getValueByPath(fromObject, ['learningRate']);\n if (parentObject !== undefined && fromLearningRate != null) {\n common.setValueByPath(\n parentObject,\n ['tuningTask', 'hyperparameters', 'learningRate'],\n fromLearningRate,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToMldev(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['tuningTask', 'trainingData'],\n tuningDatasetToMldev(fromTrainingDataset),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToMldev(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function getTuningJobParametersToVertex(\n fromObject: types.GetTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['_url', 'name'], fromName);\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(toObject, ['config'], fromConfig);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsConfigToVertex(\n fromObject: types.ListTuningJobsConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromPageSize = common.getValueByPath(fromObject, ['pageSize']);\n if (parentObject !== undefined && fromPageSize != null) {\n common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize);\n }\n\n const fromPageToken = common.getValueByPath(fromObject, ['pageToken']);\n if (parentObject !== undefined && fromPageToken != null) {\n common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken);\n }\n\n const fromFilter = common.getValueByPath(fromObject, ['filter']);\n if (parentObject !== undefined && fromFilter != null) {\n common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter);\n }\n\n return toObject;\n}\n\nexport function listTuningJobsParametersToVertex(\n fromObject: types.ListTuningJobsParameters,\n): Record {\n const toObject: Record = {};\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n listTuningJobsConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tuningDatasetToVertex(\n fromObject: types.TuningDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (parentObject !== undefined && fromGcsUri != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromGcsUri,\n );\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n if (common.getValueByPath(fromObject, ['examples']) !== undefined) {\n throw new Error('examples parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function tuningValidationDatasetToVertex(\n fromObject: types.TuningValidationDataset,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromGcsUri = common.getValueByPath(fromObject, ['gcsUri']);\n if (fromGcsUri != null) {\n common.setValueByPath(toObject, ['validationDatasetUri'], fromGcsUri);\n }\n\n const fromVertexDatasetResource = common.getValueByPath(fromObject, [\n 'vertexDatasetResource',\n ]);\n if (parentObject !== undefined && fromVertexDatasetResource != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n fromVertexDatasetResource,\n );\n }\n\n return toObject;\n}\n\nexport function createTuningJobConfigToVertex(\n fromObject: types.CreateTuningJobConfig,\n parentObject: Record,\n): Record {\n const toObject: Record = {};\n\n const fromValidationDataset = common.getValueByPath(fromObject, [\n 'validationDataset',\n ]);\n if (parentObject !== undefined && fromValidationDataset != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec'],\n tuningValidationDatasetToVertex(fromValidationDataset, toObject),\n );\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (parentObject !== undefined && fromTunedModelDisplayName != null) {\n common.setValueByPath(\n parentObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (parentObject !== undefined && fromDescription != null) {\n common.setValueByPath(parentObject, ['description'], fromDescription);\n }\n\n const fromEpochCount = common.getValueByPath(fromObject, ['epochCount']);\n if (parentObject !== undefined && fromEpochCount != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'epochCount'],\n fromEpochCount,\n );\n }\n\n const fromLearningRateMultiplier = common.getValueByPath(fromObject, [\n 'learningRateMultiplier',\n ]);\n if (parentObject !== undefined && fromLearningRateMultiplier != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'learningRateMultiplier'],\n fromLearningRateMultiplier,\n );\n }\n\n const fromExportLastCheckpointOnly = common.getValueByPath(fromObject, [\n 'exportLastCheckpointOnly',\n ]);\n if (parentObject !== undefined && fromExportLastCheckpointOnly != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'exportLastCheckpointOnly'],\n fromExportLastCheckpointOnly,\n );\n }\n\n const fromAdapterSize = common.getValueByPath(fromObject, ['adapterSize']);\n if (parentObject !== undefined && fromAdapterSize != null) {\n common.setValueByPath(\n parentObject,\n ['supervisedTuningSpec', 'hyperParameters', 'adapterSize'],\n fromAdapterSize,\n );\n }\n\n if (common.getValueByPath(fromObject, ['batchSize']) !== undefined) {\n throw new Error('batchSize parameter is not supported in Vertex AI.');\n }\n\n if (common.getValueByPath(fromObject, ['learningRate']) !== undefined) {\n throw new Error('learningRate parameter is not supported in Vertex AI.');\n }\n\n return toObject;\n}\n\nexport function createTuningJobParametersToVertex(\n fromObject: types.CreateTuningJobParameters,\n): Record {\n const toObject: Record = {};\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTrainingDataset = common.getValueByPath(fromObject, [\n 'trainingDataset',\n ]);\n if (fromTrainingDataset != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec', 'trainingDatasetUri'],\n tuningDatasetToVertex(fromTrainingDataset, toObject),\n );\n }\n\n const fromConfig = common.getValueByPath(fromObject, ['config']);\n if (fromConfig != null) {\n common.setValueByPath(\n toObject,\n ['config'],\n createTuningJobConfigToVertex(fromConfig, toObject),\n );\n }\n\n return toObject;\n}\n\nexport function tunedModelFromMldev(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['name']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['name']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromMldev(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'startTime',\n ]);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, [\n 'tuningTask',\n 'completeTime',\n ]);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['_self']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromMldev(fromTunedModel),\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromMldev(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tunedModels']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromMldev(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningOperationFromMldev(\n fromObject: types.TuningOperation,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromMetadata = common.getValueByPath(fromObject, ['metadata']);\n if (fromMetadata != null) {\n common.setValueByPath(toObject, ['metadata'], fromMetadata);\n }\n\n const fromDone = common.getValueByPath(fromObject, ['done']);\n if (fromDone != null) {\n common.setValueByPath(toObject, ['done'], fromDone);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n return toObject;\n}\n\nexport function tunedModelCheckpointFromVertex(\n fromObject: types.TunedModelCheckpoint,\n): Record {\n const toObject: Record = {};\n\n const fromCheckpointId = common.getValueByPath(fromObject, ['checkpointId']);\n if (fromCheckpointId != null) {\n common.setValueByPath(toObject, ['checkpointId'], fromCheckpointId);\n }\n\n const fromEpoch = common.getValueByPath(fromObject, ['epoch']);\n if (fromEpoch != null) {\n common.setValueByPath(toObject, ['epoch'], fromEpoch);\n }\n\n const fromStep = common.getValueByPath(fromObject, ['step']);\n if (fromStep != null) {\n common.setValueByPath(toObject, ['step'], fromStep);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n return toObject;\n}\n\nexport function tunedModelFromVertex(\n fromObject: types.TunedModel,\n): Record {\n const toObject: Record = {};\n\n const fromModel = common.getValueByPath(fromObject, ['model']);\n if (fromModel != null) {\n common.setValueByPath(toObject, ['model'], fromModel);\n }\n\n const fromEndpoint = common.getValueByPath(fromObject, ['endpoint']);\n if (fromEndpoint != null) {\n common.setValueByPath(toObject, ['endpoint'], fromEndpoint);\n }\n\n const fromCheckpoints = common.getValueByPath(fromObject, ['checkpoints']);\n if (fromCheckpoints != null) {\n let transformedList = fromCheckpoints;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tunedModelCheckpointFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['checkpoints'], transformedList);\n }\n\n return toObject;\n}\n\nexport function tuningJobFromVertex(\n fromObject: types.TuningJob,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromName = common.getValueByPath(fromObject, ['name']);\n if (fromName != null) {\n common.setValueByPath(toObject, ['name'], fromName);\n }\n\n const fromState = common.getValueByPath(fromObject, ['state']);\n if (fromState != null) {\n common.setValueByPath(toObject, ['state'], t.tTuningJobStatus(fromState));\n }\n\n const fromCreateTime = common.getValueByPath(fromObject, ['createTime']);\n if (fromCreateTime != null) {\n common.setValueByPath(toObject, ['createTime'], fromCreateTime);\n }\n\n const fromStartTime = common.getValueByPath(fromObject, ['startTime']);\n if (fromStartTime != null) {\n common.setValueByPath(toObject, ['startTime'], fromStartTime);\n }\n\n const fromEndTime = common.getValueByPath(fromObject, ['endTime']);\n if (fromEndTime != null) {\n common.setValueByPath(toObject, ['endTime'], fromEndTime);\n }\n\n const fromUpdateTime = common.getValueByPath(fromObject, ['updateTime']);\n if (fromUpdateTime != null) {\n common.setValueByPath(toObject, ['updateTime'], fromUpdateTime);\n }\n\n const fromError = common.getValueByPath(fromObject, ['error']);\n if (fromError != null) {\n common.setValueByPath(toObject, ['error'], fromError);\n }\n\n const fromDescription = common.getValueByPath(fromObject, ['description']);\n if (fromDescription != null) {\n common.setValueByPath(toObject, ['description'], fromDescription);\n }\n\n const fromBaseModel = common.getValueByPath(fromObject, ['baseModel']);\n if (fromBaseModel != null) {\n common.setValueByPath(toObject, ['baseModel'], fromBaseModel);\n }\n\n const fromTunedModel = common.getValueByPath(fromObject, ['tunedModel']);\n if (fromTunedModel != null) {\n common.setValueByPath(\n toObject,\n ['tunedModel'],\n tunedModelFromVertex(fromTunedModel),\n );\n }\n\n const fromSupervisedTuningSpec = common.getValueByPath(fromObject, [\n 'supervisedTuningSpec',\n ]);\n if (fromSupervisedTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['supervisedTuningSpec'],\n fromSupervisedTuningSpec,\n );\n }\n\n const fromTuningDataStats = common.getValueByPath(fromObject, [\n 'tuningDataStats',\n ]);\n if (fromTuningDataStats != null) {\n common.setValueByPath(toObject, ['tuningDataStats'], fromTuningDataStats);\n }\n\n const fromEncryptionSpec = common.getValueByPath(fromObject, [\n 'encryptionSpec',\n ]);\n if (fromEncryptionSpec != null) {\n common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec);\n }\n\n const fromPartnerModelTuningSpec = common.getValueByPath(fromObject, [\n 'partnerModelTuningSpec',\n ]);\n if (fromPartnerModelTuningSpec != null) {\n common.setValueByPath(\n toObject,\n ['partnerModelTuningSpec'],\n fromPartnerModelTuningSpec,\n );\n }\n\n const fromDistillationSpec = common.getValueByPath(fromObject, [\n 'distillationSpec',\n ]);\n if (fromDistillationSpec != null) {\n common.setValueByPath(toObject, ['distillationSpec'], fromDistillationSpec);\n }\n\n const fromExperiment = common.getValueByPath(fromObject, ['experiment']);\n if (fromExperiment != null) {\n common.setValueByPath(toObject, ['experiment'], fromExperiment);\n }\n\n const fromLabels = common.getValueByPath(fromObject, ['labels']);\n if (fromLabels != null) {\n common.setValueByPath(toObject, ['labels'], fromLabels);\n }\n\n const fromPipelineJob = common.getValueByPath(fromObject, ['pipelineJob']);\n if (fromPipelineJob != null) {\n common.setValueByPath(toObject, ['pipelineJob'], fromPipelineJob);\n }\n\n const fromSatisfiesPzi = common.getValueByPath(fromObject, ['satisfiesPzi']);\n if (fromSatisfiesPzi != null) {\n common.setValueByPath(toObject, ['satisfiesPzi'], fromSatisfiesPzi);\n }\n\n const fromSatisfiesPzs = common.getValueByPath(fromObject, ['satisfiesPzs']);\n if (fromSatisfiesPzs != null) {\n common.setValueByPath(toObject, ['satisfiesPzs'], fromSatisfiesPzs);\n }\n\n const fromServiceAccount = common.getValueByPath(fromObject, [\n 'serviceAccount',\n ]);\n if (fromServiceAccount != null) {\n common.setValueByPath(toObject, ['serviceAccount'], fromServiceAccount);\n }\n\n const fromTunedModelDisplayName = common.getValueByPath(fromObject, [\n 'tunedModelDisplayName',\n ]);\n if (fromTunedModelDisplayName != null) {\n common.setValueByPath(\n toObject,\n ['tunedModelDisplayName'],\n fromTunedModelDisplayName,\n );\n }\n\n return toObject;\n}\n\nexport function listTuningJobsResponseFromVertex(\n fromObject: types.ListTuningJobsResponse,\n): Record {\n const toObject: Record = {};\n\n const fromSdkHttpResponse = common.getValueByPath(fromObject, [\n 'sdkHttpResponse',\n ]);\n if (fromSdkHttpResponse != null) {\n common.setValueByPath(toObject, ['sdkHttpResponse'], fromSdkHttpResponse);\n }\n\n const fromNextPageToken = common.getValueByPath(fromObject, [\n 'nextPageToken',\n ]);\n if (fromNextPageToken != null) {\n common.setValueByPath(toObject, ['nextPageToken'], fromNextPageToken);\n }\n\n const fromTuningJobs = common.getValueByPath(fromObject, ['tuningJobs']);\n if (fromTuningJobs != null) {\n let transformedList = fromTuningJobs;\n if (Array.isArray(transformedList)) {\n transformedList = transformedList.map((item) => {\n return tuningJobFromVertex(item);\n });\n }\n common.setValueByPath(toObject, ['tuningJobs'], transformedList);\n }\n\n return toObject;\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\n// Code generated by the Google Gen AI SDK generator DO NOT EDIT.\n\nimport {ApiClient} from './_api_client.js';\nimport * as common from './_common.js';\nimport {BaseModule} from './_common.js';\nimport * as converters from './converters/_tunings_converters.js';\nimport {PagedItem, Pager} from './pagers.js';\nimport * as types from './types.js';\n\nexport class Tunings extends BaseModule {\n constructor(private readonly apiClient: ApiClient) {\n super();\n }\n\n /**\n * Gets a TuningJob.\n *\n * @param name - The resource name of the tuning job.\n * @return - A TuningJob object.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n get = async (\n params: types.GetTuningJobParameters,\n ): Promise => {\n return await this.getInternal(params);\n };\n\n /**\n * Lists tuning jobs.\n *\n * @param config - The configuration for the list request.\n * @return - A list of tuning jobs.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n list = async (\n params: types.ListTuningJobsParameters = {},\n ): Promise> => {\n return new Pager(\n PagedItem.PAGED_ITEM_TUNING_JOBS,\n (x: types.ListTuningJobsParameters) => this.listInternal(x),\n await this.listInternal(params),\n params,\n );\n };\n\n /**\n * Creates a supervised fine-tuning job.\n *\n * @param params - The parameters for the tuning job.\n * @return - A TuningJob operation.\n *\n * @experimental - The SDK's tuning implementation is experimental, and may\n * change in future versions.\n */\n tune = async (\n params: types.CreateTuningJobParameters,\n ): Promise => {\n if (this.apiClient.isVertexAI()) {\n return await this.tuneInternal(params);\n } else {\n const operation = await this.tuneMldevInternal(params);\n let tunedModelName = '';\n if (\n operation['metadata'] !== undefined &&\n operation['metadata']['tunedModel'] !== undefined\n ) {\n tunedModelName = operation['metadata']['tunedModel'] as string;\n } else if (\n operation['name'] !== undefined &&\n operation['name'].includes('/operations/')\n ) {\n tunedModelName = operation['name'].split('/operations/')[0];\n }\n const tuningJob: types.TuningJob = {\n name: tunedModelName,\n state: types.JobState.JOB_STATE_QUEUED,\n };\n\n return tuningJob;\n }\n };\n\n private async getInternal(\n params: types.GetTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.getTuningJobParametersToVertex(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n const body = converters.getTuningJobParametersToMldev(params);\n path = common.formatMap(\n '{name}',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json();\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromMldev(apiResponse);\n\n return resp as types.TuningJob;\n });\n }\n }\n\n private async listInternal(\n params: types.ListTuningJobsParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.listTuningJobsParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromVertex(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n } else {\n const body = converters.listTuningJobsParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'GET',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.ListTuningJobsResponse;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.listTuningJobsResponseFromMldev(apiResponse);\n const typedResp = new types.ListTuningJobsResponse();\n Object.assign(typedResp, resp);\n return typedResp;\n });\n }\n }\n\n private async tuneInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n const body = converters.createTuningJobParametersToVertex(params);\n path = common.formatMap(\n 'tuningJobs',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningJob;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningJobFromVertex(apiResponse);\n\n return resp as types.TuningJob;\n });\n } else {\n throw new Error('This method is only supported by the Vertex AI.');\n }\n }\n\n private async tuneMldevInternal(\n params: types.CreateTuningJobParameters,\n ): Promise {\n let response: Promise;\n\n let path: string = '';\n let queryParams: Record = {};\n if (this.apiClient.isVertexAI()) {\n throw new Error(\n 'This method is only supported by the Gemini Developer API.',\n );\n } else {\n const body = converters.createTuningJobParametersToMldev(params);\n path = common.formatMap(\n 'tunedModels',\n body['_url'] as Record,\n );\n queryParams = body['_query'] as Record;\n delete body['config'];\n delete body['_url'];\n delete body['_query'];\n\n response = this.apiClient\n .request({\n path: path,\n queryParams: queryParams,\n body: JSON.stringify(body),\n httpMethod: 'POST',\n httpOptions: params.config?.httpOptions,\n abortSignal: params.config?.abortSignal,\n })\n .then((httpResponse) => {\n return httpResponse.json().then((jsonResponse) => {\n const response = jsonResponse as types.TuningOperation;\n response.sdkHttpResponse = {\n headers: httpResponse.headers,\n } as types.HttpResponse;\n return response;\n });\n }) as Promise;\n\n return response.then((apiResponse) => {\n const resp = converters.tuningOperationFromMldev(apiResponse);\n\n return resp as types.TuningOperation;\n });\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {Downloader} from '../_downloader.js';\nimport {DownloadFileParameters} from '../types.js';\n\nexport class BrowserDownloader implements Downloader {\n async download(\n _params: DownloadFileParameters,\n _apiClient: ApiClient,\n ): Promise {\n throw new Error(\n 'Download to file is not supported in the browser, please use a browser compliant download like an tag.',\n );\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {File, HttpResponse} from '../types.js';\n\nimport {crossError} from './_cross_error.js';\n\nexport const MAX_CHUNK_SIZE = 1024 * 1024 * 8; // bytes\nexport const MAX_RETRY_COUNT = 3;\nexport const INITIAL_RETRY_DELAY_MS = 1000;\nexport const DELAY_MULTIPLIER = 2;\nexport const X_GOOG_UPLOAD_STATUS_HEADER_FIELD = 'x-goog-upload-status';\n\nexport class CrossUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return uploadBlob(file, uploadUrl, apiClient);\n }\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw crossError();\n } else {\n return getBlobStat(file);\n }\n }\n}\n\nexport async function uploadBlob(\n file: Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n): Promise {\n let fileSize = 0;\n let offset = 0;\n let response: HttpResponse = new HttpResponse(new Response());\n let uploadCommand = 'upload';\n fileSize = file.size;\n while (offset < fileSize) {\n const chunkSize = Math.min(MAX_CHUNK_SIZE, fileSize - offset);\n const chunk = file.slice(offset, offset + chunkSize);\n if (offset + chunkSize >= fileSize) {\n uploadCommand += ', finalize';\n }\n let retryCount = 0;\n let currentDelayMs = INITIAL_RETRY_DELAY_MS;\n while (retryCount < MAX_RETRY_COUNT) {\n response = await apiClient.request({\n path: '',\n body: chunk,\n httpMethod: 'POST',\n httpOptions: {\n apiVersion: '',\n baseUrl: uploadUrl,\n headers: {\n 'X-Goog-Upload-Command': uploadCommand,\n 'X-Goog-Upload-Offset': String(offset),\n 'Content-Length': String(chunkSize),\n },\n },\n });\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD]) {\n break;\n }\n retryCount++;\n await sleep(currentDelayMs);\n currentDelayMs = currentDelayMs * DELAY_MULTIPLIER;\n }\n offset += chunkSize;\n // The `x-goog-upload-status` header field can be `active`, `final` and\n //`cancelled` in resposne.\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'active') {\n break;\n }\n // TODO(b/401391430) Investigate why the upload status is not finalized\n // even though all content has been uploaded.\n if (fileSize <= offset) {\n throw new Error(\n 'All content has been uploaded, but the upload status is not finalized.',\n );\n }\n }\n const responseJson = (await response?.json()) as Record<\n string,\n File | unknown\n >;\n if (response?.headers?.[X_GOOG_UPLOAD_STATUS_HEADER_FIELD] !== 'final') {\n throw new Error('Failed to upload file: Upload status is not finalized.');\n }\n return responseJson['file'] as File;\n}\n\nexport async function getBlobStat(file: Blob): Promise {\n const fileStat: FileStat = {size: file.size, type: file.type};\n return fileStat;\n}\n\nexport function sleep(ms: number): Promise {\n return new Promise((resolvePromise) => setTimeout(resolvePromise, ms));\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\nimport {ApiClient} from '../_api_client.js';\nimport {FileStat, Uploader} from '../_uploader.js';\nimport {getBlobStat, uploadBlob} from '../cross/_cross_uploader.js';\nimport {File} from '../types.js';\n\nexport class BrowserUploader implements Uploader {\n async upload(\n file: string | Blob,\n uploadUrl: string,\n apiClient: ApiClient,\n ): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n }\n\n return await uploadBlob(file, uploadUrl, apiClient);\n }\n\n async stat(file: string | Blob): Promise {\n if (typeof file === 'string') {\n throw new Error('File path is not supported in browser uploader.');\n } else {\n return await getBlobStat(file);\n }\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {\n WebSocketCallbacks,\n WebSocketFactory,\n WebSocket as Ws,\n} from '../_websocket.js';\n\nexport class BrowserWebSocketFactory implements WebSocketFactory {\n create(\n url: string,\n headers: Record,\n callbacks: WebSocketCallbacks,\n ): Ws {\n return new BrowserWebSocket(url, headers, callbacks);\n }\n}\n\nexport class BrowserWebSocket implements Ws {\n private ws?: WebSocket;\n\n constructor(\n private readonly url: string,\n private readonly headers: Record,\n private readonly callbacks: WebSocketCallbacks,\n ) {}\n\n connect(): void {\n this.ws = new WebSocket(this.url);\n\n this.ws.onopen = this.callbacks.onopen;\n this.ws.onerror = this.callbacks.onerror;\n this.ws.onclose = this.callbacks.onclose;\n this.ws.onmessage = this.callbacks.onmessage;\n }\n\n send(message: string) {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.send(message);\n }\n\n close() {\n if (this.ws === undefined) {\n throw new Error('WebSocket is not connected');\n }\n\n this.ws.close();\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {Auth} from '../_auth.js';\n\nexport const GOOGLE_API_KEY_HEADER = 'x-goog-api-key';\n// TODO(b/395122533): We need a secure client side authentication mechanism.\nexport class WebAuth implements Auth {\n constructor(private readonly apiKey: string) {}\n\n async addAuthHeaders(headers: Headers): Promise {\n if (headers.get(GOOGLE_API_KEY_HEADER) !== null) {\n return;\n }\n\n if (this.apiKey.startsWith('auth_tokens/')) {\n throw new Error('Ephemeral tokens are only supported by the live API.');\n }\n\n // Check if API key is empty or null\n if (!this.apiKey) {\n throw new Error('API key is missing. Please provide a valid API key.');\n }\n headers.append(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n}\n","/**\n * @license\n * Copyright 2025 Google LLC\n * SPDX-License-Identifier: Apache-2.0\n */\n\nimport {ApiClient} from '../_api_client.js';\nimport {getBaseUrl} from '../_base_url.js';\nimport {Batches} from '../batches.js';\nimport {Caches} from '../caches.js';\nimport {Chats} from '../chats.js';\nimport {GoogleGenAIOptions} from '../client.js';\nimport {Files} from '../files.js';\nimport {Live} from '../live.js';\nimport {Models} from '../models.js';\nimport {Operations} from '../operations.js';\nimport {Tokens} from '../tokens.js';\nimport {Tunings} from '../tunings.js';\n\nimport {BrowserDownloader} from './_browser_downloader.js';\nimport {BrowserUploader} from './_browser_uploader.js';\nimport {BrowserWebSocketFactory} from './_browser_websocket.js';\nimport {WebAuth} from './_web_auth.js';\n\nconst LANGUAGE_LABEL_PREFIX = 'gl-node/';\n\n/**\n * The Google GenAI SDK.\n *\n * @remarks\n * Provides access to the GenAI features through either the {@link\n * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or\n * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI\n * API}.\n *\n * The {@link GoogleGenAIOptions.vertexai} value determines which of the API\n * services to use.\n *\n * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be\n * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey}\n * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link\n * GoogleGenAIOptions.location} should not be set.\n *\n * @example\n * Initializing the SDK for using the Gemini API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'});\n * ```\n *\n * @example\n * Initializing the SDK for using the Vertex AI API:\n * ```ts\n * import {GoogleGenAI} from '@google/genai';\n * const ai = new GoogleGenAI({\n * vertexai: true,\n * project: 'PROJECT_ID',\n * location: 'PROJECT_LOCATION'\n * });\n * ```\n *\n */\nexport class GoogleGenAI {\n protected readonly apiClient: ApiClient;\n private readonly apiKey?: string;\n public readonly vertexai: boolean;\n private readonly apiVersion?: string;\n readonly models: Models;\n readonly live: Live;\n readonly batches: Batches;\n readonly chats: Chats;\n readonly caches: Caches;\n readonly files: Files;\n readonly operations: Operations;\n readonly authTokens: Tokens;\n readonly tunings: Tunings;\n\n constructor(options: GoogleGenAIOptions) {\n if (options.apiKey == null) {\n throw new Error('An API Key must be set when running in a browser');\n }\n // Web client only supports API key mode for Vertex AI.\n if (options.project || options.location) {\n throw new Error(\n 'Vertex AI project based authentication is not supported on browser runtimes. Please do not provide a project or location.',\n );\n }\n this.vertexai = options.vertexai ?? false;\n\n this.apiKey = options.apiKey;\n\n const baseUrl = getBaseUrl(\n options.httpOptions,\n options.vertexai,\n /*vertexBaseUrlFromEnv*/ undefined,\n /*geminiBaseUrlFromEnv*/ undefined,\n );\n if (baseUrl) {\n if (options.httpOptions) {\n options.httpOptions.baseUrl = baseUrl;\n } else {\n options.httpOptions = {baseUrl: baseUrl};\n }\n }\n\n this.apiVersion = options.apiVersion;\n const auth = new WebAuth(this.apiKey);\n this.apiClient = new ApiClient({\n auth: auth,\n apiVersion: this.apiVersion,\n apiKey: this.apiKey,\n vertexai: this.vertexai,\n httpOptions: options.httpOptions,\n userAgentExtra: LANGUAGE_LABEL_PREFIX + 'web',\n uploader: new BrowserUploader(),\n downloader: new BrowserDownloader(),\n });\n this.models = new Models(this.apiClient);\n this.live = new Live(this.apiClient, auth, new BrowserWebSocketFactory());\n this.batches = new Batches(this.apiClient);\n this.chats = new Chats(this.models, this.apiClient);\n this.caches = new Caches(this.apiClient);\n this.files = new Files(this.apiClient);\n this.operations = new Operations(this.apiClient);\n this.authTokens = new Tokens(this.apiClient);\n this.tunings = new Tunings(this.apiClient);\n }\n}\n"],"names":["tBytes","types.Type","baseTransformers.tBytes","videoMetadataToMldev","common.getValueByPath","common.setValueByPath","blobToMldev","fileDataToMldev","partToMldev","contentToMldev","schemaToMldev","safetySettingToMldev","functionDeclarationToMldev","intervalToMldev","googleSearchToMldev","dynamicRetrievalConfigToMldev","googleSearchRetrievalToMldev","urlContextToMldev","toolComputerUseToMldev","toolToMldev","functionCallingConfigToMldev","latLngToMldev","retrievalConfigToMldev","toolConfigToMldev","prebuiltVoiceConfigToMldev","voiceConfigToMldev","speakerVoiceConfigToMldev","multiSpeakerVoiceConfigToMldev","speechConfigToMldev","thinkingConfigToMldev","generateContentConfigToMldev","t.tContent","t.tSchema","t.tTools","t.tTool","t.tCachedContentName","t.tSpeechConfig","t.tModel","t.tContents","t.tBatchJobSource","t.tBatchJobName","t.tBatchJobDestination","videoMetadataFromMldev","blobFromMldev","fileDataFromMldev","partFromMldev","contentFromMldev","citationMetadataFromMldev","urlMetadataFromMldev","urlContextMetadataFromMldev","candidateFromMldev","generateContentResponseFromMldev","t.tJobState","converters.createBatchJobParametersToVertex","common.formatMap","converters.batchJobFromVertex","converters.createBatchJobParametersToMldev","converters.batchJobFromMldev","converters.getBatchJobParametersToVertex","converters.getBatchJobParametersToMldev","converters.cancelBatchJobParametersToVertex","converters.cancelBatchJobParametersToMldev","converters.listBatchJobsParametersToVertex","converters.listBatchJobsResponseFromVertex","types.ListBatchJobsResponse","converters.listBatchJobsParametersToMldev","converters.listBatchJobsResponseFromMldev","converters.deleteBatchJobParametersToVertex","converters.deleteResourceJobFromVertex","converters.deleteBatchJobParametersToMldev","converters.deleteResourceJobFromMldev","t.tCachesModel","videoMetadataToVertex","blobToVertex","fileDataToVertex","partToVertex","contentToVertex","functionDeclarationToVertex","intervalToVertex","googleSearchToVertex","dynamicRetrievalConfigToVertex","googleSearchRetrievalToVertex","enterpriseWebSearchToVertex","apiKeyConfigToVertex","authConfigToVertex","googleMapsToVertex","urlContextToVertex","toolToVertex","functionCallingConfigToVertex","latLngToVertex","retrievalConfigToVertex","toolConfigToVertex","converters.createCachedContentParametersToVertex","converters.cachedContentFromVertex","converters.createCachedContentParametersToMldev","converters.cachedContentFromMldev","converters.getCachedContentParametersToVertex","converters.getCachedContentParametersToMldev","converters.deleteCachedContentParametersToVertex","converters.deleteCachedContentResponseFromVertex","types.DeleteCachedContentResponse","converters.deleteCachedContentParametersToMldev","converters.deleteCachedContentResponseFromMldev","converters.updateCachedContentParametersToVertex","converters.updateCachedContentParametersToMldev","converters.listCachedContentsParametersToVertex","converters.listCachedContentsResponseFromVertex","types.ListCachedContentsResponse","converters.listCachedContentsParametersToMldev","converters.listCachedContentsResponseFromMldev","t.tFileName","converters.fileFromMldev","converters.listFilesParametersToMldev","converters.listFilesResponseFromMldev","types.ListFilesResponse","converters.createFileParametersToMldev","converters.createFileResponseFromMldev","types.CreateFileResponse","converters.getFileParametersToMldev","converters.deleteFileParametersToMldev","converters.deleteFileResponseFromMldev","types.DeleteFileResponse","sessionResumptionConfigToMldev","audioTranscriptionConfigToMldev","automaticActivityDetectionToMldev","realtimeInputConfigToMldev","slidingWindowToMldev","contextWindowCompressionConfigToMldev","proactivityConfigToMldev","liveConnectConfigToMldev","t.tLiveSpeechConfig","t.tBlobs","t.tAudioBlob","t.tImageBlob","prebuiltVoiceConfigToVertex","voiceConfigToVertex","speechConfigToVertex","videoMetadataFromVertex","blobFromVertex","fileDataFromVertex","partFromVertex","contentFromVertex","t.tContentsForEmbed","t.tModelsUrl","t.tBytes","t.tExtractModels","handleWebSocketMessage","types.LiveMusicServerMessage","converters.liveMusicServerMessageFromMldev","mapToHeaders","headersToMap","converters.liveMusicClientSetupToMldev","converters.liveMusicClientMessageToMldev","converters.liveMusicSetWeightedPromptsParametersToMldev","converters.liveMusicClientContentToMldev","converters.liveMusicSetConfigParametersToMldev","types.LiveMusicPlaybackControl","types.LiveServerMessage","converters.liveServerMessageFromVertex","converters.liveServerMessageFromMldev","types.Modality","converters.liveConnectParametersToVertex","converters.liveConnectParametersToMldev","converters.liveSendRealtimeInputParametersToVertex","converters.liveSendRealtimeInputParametersToMldev","types.GenerateContentResponse","converters.generateContentParametersToVertex","converters.generateContentResponseFromVertex","converters.generateContentParametersToMldev","converters.generateContentResponseFromMldev","converters.embedContentParametersToVertex","converters.embedContentResponseFromVertex","types.EmbedContentResponse","converters.embedContentParametersToMldev","converters.embedContentResponseFromMldev","converters.generateImagesParametersToVertex","converters.generateImagesResponseFromVertex","types.GenerateImagesResponse","converters.generateImagesParametersToMldev","converters.generateImagesResponseFromMldev","converters.editImageParametersInternalToVertex","converters.editImageResponseFromVertex","types.EditImageResponse","converters.upscaleImageAPIParametersInternalToVertex","converters.upscaleImageResponseFromVertex","types.UpscaleImageResponse","converters.getModelParametersToVertex","converters.modelFromVertex","converters.getModelParametersToMldev","converters.modelFromMldev","converters.listModelsParametersToVertex","converters.listModelsResponseFromVertex","types.ListModelsResponse","converters.listModelsParametersToMldev","converters.listModelsResponseFromMldev","converters.updateModelParametersToVertex","converters.updateModelParametersToMldev","converters.deleteModelParametersToVertex","converters.deleteModelResponseFromVertex","types.DeleteModelResponse","converters.deleteModelParametersToMldev","converters.deleteModelResponseFromMldev","converters.countTokensParametersToVertex","converters.countTokensResponseFromVertex","types.CountTokensResponse","converters.countTokensParametersToMldev","converters.countTokensResponseFromMldev","converters.computeTokensParametersToVertex","converters.computeTokensResponseFromVertex","types.ComputeTokensResponse","converters.generateVideosParametersToVertex","converters.generateVideosOperationFromVertex","types.GenerateVideosOperation","converters.generateVideosParametersToMldev","converters.generateVideosOperationFromMldev","converters.getOperationParametersToVertex","converters.getOperationParametersToMldev","converters.fetchPredictOperationParametersToVertex","converters.createAuthTokenParametersToMldev","converters.authTokenFromMldev","t.tTuningJobStatus","types.JobState","converters.getTuningJobParametersToVertex","converters.tuningJobFromVertex","converters.getTuningJobParametersToMldev","converters.tuningJobFromMldev","converters.listTuningJobsParametersToVertex","converters.listTuningJobsResponseFromVertex","types.ListTuningJobsResponse","converters.listTuningJobsParametersToMldev","converters.listTuningJobsResponseFromMldev","converters.createTuningJobParametersToVertex","converters.createTuningJobParametersToMldev","converters.tuningOperationFromMldev"],"mappings":"AAAA;;;;AAIG;AAIH,IAAI,qBAAqB,GAAuB,SAAS;AACzD,IAAI,qBAAqB,GAAuB,SAAS;AAUzD;;;;;;;;;;;;;;;;;;;AAmBG;AACG,SAAU,kBAAkB,CAAC,aAAgC,EAAA;AACjE,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AAC/C,IAAA,qBAAqB,GAAG,aAAa,CAAC,SAAS;AACjD;AAEA;;AAEG;SACa,kBAAkB,GAAA;IAChC,OAAO;AACL,QAAA,SAAS,EAAE,qBAAqB;AAChC,QAAA,SAAS,EAAE,qBAAqB;KACjC;AACH;AAEA;;;;;AAKG;AACG,SAAU,UAAU,CACxB,WAAoC,EACpC,QAA6B,EAC7B,oBAAwC,EACxC,oBAAwC,EAAA;;IAExC,IAAI,EAAC,WAAW,KAAX,IAAA,IAAA,WAAW,uBAAX,WAAW,CAAE,OAAO,CAAA,EAAE;AACzB,QAAA,MAAM,eAAe,GAAG,kBAAkB,EAAE;AAC5C,QAAA,IAAI,QAAQ,EAAE;AACZ,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AAAM,aAAA;AACL,YAAA,OAAO,MAAA,eAAe,CAAC,SAAS,MAAA,IAAA,IAAA,EAAA,KAAA,MAAA,GAAA,EAAA,GAAI,oBAAoB;AACzD;AACF;IAED,OAAO,WAAW,CAAC,OAAO;AAC5B;;AC5EA;;;;A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;QACF,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;AACxC,QAAA,IAAI,CAAC,IAAI,GAAG,IAAI,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,IAAI,EAAE,IAAI,uBAAuB,EAAE,CAAC;QACzE,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;AAC1C,QAAA,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC,SAAS,CAAC;QACnD,IAAI,CAAC,MAAM,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QACxC,IAAI,CAAC,KAAK,GAAG,IAAI,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC;QACtC,IAAI,CAAC,UAAU,GAAG,IAAI,UAAU,CAAC,IAAI,CAAC,SAAS,CAAC;QAChD,IAAI,CAAC,UAAU,GAAG,IAAI,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC;QAC5C,IAAI,CAAC,OAAO,GAAG,IAAI,OAAO,CAAC,IAAI,CAAC,SAAS,CAAC;;AAE7C;;;;"} \ No newline at end of file diff --git a/sdk/stagehand-ts/google-ts-sdk/package/dist/web/web.d.ts b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/web.d.ts new file mode 100644 index 0000000..f313062 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/dist/web/web.d.ts @@ -0,0 +1,7422 @@ +// @ts-ignore +import type { Client } from "@modelcontextprotocol/sdk/client/index.js"; +import { GoogleAuthOptions } from "google-auth-library"; + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityEnd {} + +/** The different ways of handling user activity. */ +export declare enum ActivityHandling { + /** + * If unspecified, the default behavior is `START_OF_ACTIVITY_INTERRUPTS`. + */ + ACTIVITY_HANDLING_UNSPECIFIED = "ACTIVITY_HANDLING_UNSPECIFIED", + /** + * If true, start of activity will interrupt the model's response (also called "barge in"). The model's current response will be cut-off in the moment of the interruption. This is the default behavior. + */ + START_OF_ACTIVITY_INTERRUPTS = "START_OF_ACTIVITY_INTERRUPTS", + /** + * The model's response will not be interrupted. + */ + NO_INTERRUPTION = "NO_INTERRUPTION", +} + +/** Marks the start of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface ActivityStart {} + +/** Optional. Adapter size for tuning. */ +export declare enum AdapterSize { + /** + * Adapter size is unspecified. + */ + ADAPTER_SIZE_UNSPECIFIED = "ADAPTER_SIZE_UNSPECIFIED", + /** + * Adapter size 1. + */ + ADAPTER_SIZE_ONE = "ADAPTER_SIZE_ONE", + /** + * Adapter size 2. + */ + ADAPTER_SIZE_TWO = "ADAPTER_SIZE_TWO", + /** + * Adapter size 4. + */ + ADAPTER_SIZE_FOUR = "ADAPTER_SIZE_FOUR", + /** + * Adapter size 8. + */ + ADAPTER_SIZE_EIGHT = "ADAPTER_SIZE_EIGHT", + /** + * Adapter size 16. + */ + ADAPTER_SIZE_SIXTEEN = "ADAPTER_SIZE_SIXTEEN", + /** + * Adapter size 32. + */ + ADAPTER_SIZE_THIRTY_TWO = "ADAPTER_SIZE_THIRTY_TWO", +} + +/** The generic reusable api auth config. Deprecated. Please use AuthConfig (google/cloud/aiplatform/master/auth.proto) instead. */ +export declare interface ApiAuth { + /** The API secret. */ + apiKeyConfig?: ApiAuthApiKeyConfig; +} + +/** The API secret. */ +export declare interface ApiAuthApiKeyConfig { + /** Required. The SecretManager secret version resource name storing API key. e.g. projects/{project}/secrets/{secret}/versions/{version} */ + apiKeySecretVersion?: string; + /** The API key string. Either this or `api_key_secret_version` must be set. */ + apiKeyString?: string; +} + +/** + * The ApiClient class is used to send requests to the Gemini API or Vertex AI + * endpoints. + */ +declare class ApiClient { + readonly clientOptions: ApiClientInitOptions; + constructor(opts: ApiClientInitOptions); + /** + * Determines the base URL for Vertex AI based on project and location. + * Uses the global endpoint if location is 'global' or if project/location + * are not specified (implying API key usage). + * @private + */ + private baseUrlFromProjectLocation; + /** + * Normalizes authentication parameters for Vertex AI. + * If project and location are provided, API key is cleared. + * If project and location are not provided (implying API key usage), + * project and location are cleared. + * @private + */ + private normalizeAuthParameters; + isVertexAI(): boolean; + getProject(): string | undefined; + getLocation(): string | undefined; + getApiVersion(): string; + getBaseUrl(): string; + getRequestUrl(): string; + getHeaders(): Record; + private getRequestUrlInternal; + getBaseResourcePath(): string; + getApiKey(): string | undefined; + getWebsocketBaseUrl(): string; + setBaseUrl(url: string): void; + private constructUrl; + private shouldPrependVertexProjectPath; + request(request: HttpRequest): Promise; + private patchHttpOptions; + requestStream(request: HttpRequest): Promise>; + private includeExtraHttpOptionsToRequestInit; + private unaryApiCall; + private streamApiCall; + processStreamResponse(response: Response): AsyncGenerator; + private apiCall; + getDefaultHeaders(): Record; + private getHeadersInternal; + /** + * Uploads a file asynchronously using Gemini API only, this is not supported + * in Vertex AI. + * + * @param file The string path to the file to be uploaded or a Blob object. + * @param config Optional parameters specified in the `UploadFileConfig` + * interface. @see {@link UploadFileConfig} + * @return A promise that resolves to a `File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + */ + uploadFile(file: string | Blob, config?: UploadFileConfig): Promise; + /** + * Downloads a file asynchronously to the specified path. + * + * @params params - The parameters for the download request, see {@link + * DownloadFileParameters} + */ + downloadFile(params: DownloadFileParameters): Promise; + private fetchUploadUrl; +} + +/** + * Options for initializing the ApiClient. The ApiClient uses the parameters + * for authentication purposes as well as to infer if SDK should send the + * request to Vertex AI or Gemini API. + */ +declare interface ApiClientInitOptions { + /** + * The object used for adding authentication headers to API requests. + */ + auth: Auth; + /** + * The uploader to use for uploading files. This field is required for + * creating a client, will be set through the Node_client or Web_client. + */ + uploader: Uploader; + /** + * Optional. The downloader to use for downloading files. This field is + * required for creating a client, will be set through the Node_client or + * Web_client. + */ + downloader: Downloader; + /** + * Optional. The Google Cloud project ID for Vertex AI users. + * It is not the numeric project name. + * If not provided, SDK will try to resolve it from runtime environment. + */ + project?: string; + /** + * Optional. The Google Cloud project location for Vertex AI users. + * If not provided, SDK will try to resolve it from runtime environment. + */ + location?: string; + /** + * The API Key. This is required for Gemini API users. + */ + apiKey?: string; + /** + * Optional. Set to true if you intend to call Vertex AI endpoints. + * If unset, default SDK behavior is to call Gemini API. + */ + vertexai?: boolean; + /** + * Optional. The API version for the endpoint. + * If unset, SDK will choose a default api version. + */ + apiVersion?: string; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional. An extra string to append at the end of the User-Agent header. + * + * This can be used to e.g specify the runtime and its version. + */ + userAgentExtra?: string; +} + +/** + * API errors raised by the GenAI API. + */ +export declare class ApiError extends Error { + /** HTTP status code */ + status: number; + constructor(options: ApiErrorInfo); +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * Details for errors from calling the API. + */ +export declare interface ApiErrorInfo { + /** The error message. */ + message: string; + /** The HTTP status code. */ + status: number; +} + +/** Config for authentication with API key. */ +export declare interface ApiKeyConfig { + /** The API key to be used in the request directly. */ + apiKeyString?: string; +} + +/** The API spec that the external API implements. */ +export declare enum ApiSpec { + /** + * Unspecified API spec. This value should not be used. + */ + API_SPEC_UNSPECIFIED = "API_SPEC_UNSPECIFIED", + /** + * Simple search API spec. + */ + SIMPLE_SEARCH = "SIMPLE_SEARCH", + /** + * Elastic search API spec. + */ + ELASTIC_SEARCH = "ELASTIC_SEARCH", +} + +/** Representation of an audio chunk. */ +export declare interface AudioChunk { + /** Raw bytes of audio data. + * @remarks Encoded as base64 string. */ + data?: string; + /** MIME type of the audio chunk. */ + mimeType?: string; + /** Prompts and config used for generating this audio chunk. */ + sourceMetadata?: LiveMusicSourceMetadata; +} + +/** The audio transcription configuration in Setup. */ +export declare interface AudioTranscriptionConfig {} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +/** + * The Auth interface is used to authenticate with the API service. + */ +declare interface Auth { + /** + * Sets the headers needed to authenticate with the API service. + * + * @param headers - The Headers object that will be updated with the authentication headers. + */ + addAuthHeaders(headers: Headers): Promise; +} + +/** Auth configuration to run the extension. */ +export declare interface AuthConfig { + /** Config for API key auth. */ + apiKeyConfig?: ApiKeyConfig; + /** Type of auth scheme. */ + authType?: AuthType; + /** Config for Google Service Account auth. */ + googleServiceAccountConfig?: AuthConfigGoogleServiceAccountConfig; + /** Config for HTTP Basic auth. */ + httpBasicAuthConfig?: AuthConfigHttpBasicAuthConfig; + /** Config for user oauth. */ + oauthConfig?: AuthConfigOauthConfig; + /** Config for user OIDC auth. */ + oidcConfig?: AuthConfigOidcConfig; +} + +/** Config for Google Service Account Authentication. */ +export declare interface AuthConfigGoogleServiceAccountConfig { + /** Optional. The service account that the extension execution service runs as. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified service account. - If not specified, the Vertex AI Extension Service Agent will be used to execute the Extension. */ + serviceAccount?: string; +} + +/** Config for HTTP Basic Authentication. */ +export declare interface AuthConfigHttpBasicAuthConfig { + /** Required. The name of the SecretManager secret version resource storing the base64 encoded credentials. Format: `projects/{project}/secrets/{secrete}/versions/{version}` - If specified, the `secretmanager.versions.access` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the specified resource. */ + credentialSecret?: string; +} + +/** Config for user oauth. */ +export declare interface AuthConfigOauthConfig { + /** Access token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + accessToken?: string; + /** The service account used to generate access tokens for executing the Extension. - If the service account is specified, the `iam.serviceAccounts.getAccessToken` permission should be granted to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents) on the provided service account. */ + serviceAccount?: string; +} + +/** Config for user OIDC auth. */ +export declare interface AuthConfigOidcConfig { + /** OpenID Connect formatted ID token for extension endpoint. Only used to propagate token from [[ExecuteExtensionRequest.runtime_auth_config]] at request time. */ + idToken?: string; + /** The service account used to generate an OpenID Connect (OIDC)-compatible JWT token signed by the Google OIDC Provider (accounts.google.com) for extension endpoint (https://cloud.google.com/iam/docs/create-short-lived-credentials-direct#sa-credentials-oidc). - The audience for the token will be set to the URL in the server url defined in the OpenApi spec. - If the service account is provided, the service account should grant `iam.serviceAccounts.getOpenIdToken` permission to Vertex AI Extension Service Agent (https://cloud.google.com/vertex-ai/docs/general/access-control#service-agents). */ + serviceAccount?: string; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface AuthToken { + /** The name of the auth token. */ + name?: string; +} + +/** Type of auth scheme. */ +export declare enum AuthType { + AUTH_TYPE_UNSPECIFIED = "AUTH_TYPE_UNSPECIFIED", + /** + * No Auth. + */ + NO_AUTH = "NO_AUTH", + /** + * API Key Auth. + */ + API_KEY_AUTH = "API_KEY_AUTH", + /** + * HTTP Basic Auth. + */ + HTTP_BASIC_AUTH = "HTTP_BASIC_AUTH", + /** + * Google Service Account Auth. + */ + GOOGLE_SERVICE_ACCOUNT_AUTH = "GOOGLE_SERVICE_ACCOUNT_AUTH", + /** + * OAuth auth. + */ + OAUTH = "OAUTH", + /** + * OpenID Connect (OIDC) Auth. + */ + OIDC_AUTH = "OIDC_AUTH", +} + +/** Configures automatic detection of activity. */ +export declare interface AutomaticActivityDetection { + /** If enabled, detected voice and text input count as activity. If disabled, the client must send activity signals. */ + disabled?: boolean; + /** Determines how likely speech is to be detected. */ + startOfSpeechSensitivity?: StartSensitivity; + /** Determines how likely detected speech is ended. */ + endOfSpeechSensitivity?: EndSensitivity; + /** The required duration of detected speech before start-of-speech is committed. The lower this value the more sensitive the start-of-speech detection is and the shorter speech can be recognized. However, this also increases the probability of false positives. */ + prefixPaddingMs?: number; + /** The required duration of detected non-speech (e.g. silence) before end-of-speech is committed. The larger this value, the longer speech gaps can be without interrupting the user's activity but this will increase the model's latency. */ + silenceDurationMs?: number; +} + +/** The configuration for automatic function calling. */ +export declare interface AutomaticFunctionCallingConfig { + /** Whether to disable automatic function calling. + If not set or set to False, will enable automatic function calling. + If set to True, will disable automatic function calling. + */ + disable?: boolean; + /** If automatic function calling is enabled, + maximum number of remote calls for automatic function calling. + This number should be a positive integer. + If not set, SDK will set maximum number of remote calls to 10. + */ + maximumRemoteCalls?: number; + /** If automatic function calling is enabled, + whether to ignore call history to the response. + If not set, SDK will set ignore_call_history to false, + and will append the call history to + GenerateContentResponse.automatic_function_calling_history. + */ + ignoreCallHistory?: boolean; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare class BaseModule {} + +/** + * Parameters for setting the base URLs for the Gemini API and Vertex AI API. + */ +export declare interface BaseUrlParameters { + geminiUrl?: string; + vertexUrl?: string; +} + +export declare class Batches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + * @example + * ```ts + * const response = await ai.batches.create({ + * model: 'gemini-2.0-flash', + * src: {gcsUri: 'gs://bucket/path/to/file.jsonl', format: 'jsonl'}, + * config: { + * dest: {gcsUri: 'gs://bucket/path/output/directory', format: 'jsonl'}, + * } + * }); + * console.log(response); + * ``` + */ + create: (params: types.CreateBatchJobParameters) => Promise; + /** + * Lists batch job configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of batch jobs. + * + * @example + * ```ts + * const batchJobs = await ai.batches.list({config: {'pageSize': 2}}); + * for await (const batchJob of batchJobs) { + * console.log(batchJob); + * } + * ``` + */ + list: ( + params?: types.ListBatchJobsParameters, + ) => Promise>; + /** + * Internal method to create batch job. + * + * @param params - The parameters for create batch job request. + * @return The created batch job. + * + */ + private createInternal; + /** + * Gets batch job configurations. + * + * @param params - The parameters for the get request. + * @return The batch job. + * + * @example + * ```ts + * await ai.batches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetBatchJobParameters): Promise; + /** + * Cancels a batch job. + * + * @param params - The parameters for the cancel request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.cancel({name: '...'}); // The server-generated resource name. + * ``` + */ + cancel(params: types.CancelBatchJobParameters): Promise; + private listInternal; + /** + * Deletes a batch job. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.batches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteBatchJobParameters, + ): Promise; +} + +/** Config for batches.create return value. */ +export declare interface BatchJob { + /** The resource name of the BatchJob. Output only.". + */ + name?: string; + /** The display name of the BatchJob. + */ + displayName?: string; + /** The state of the BatchJob. + */ + state?: JobState; + /** Output only. Only populated when the job's state is JOB_STATE_FAILED or JOB_STATE_CANCELLED. */ + error?: JobError; + /** The time when the BatchJob was created. + */ + createTime?: string; + /** Output only. Time when the Job for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** The time when the BatchJob was completed. + */ + endTime?: string; + /** The time when the BatchJob was last updated. + */ + updateTime?: string; + /** The name of the model that produces the predictions via the BatchJob. + */ + model?: string; + /** Configuration for the input data. + */ + src?: BatchJobSource; + /** Configuration for the output data. + */ + dest?: BatchJobDestination; +} + +/** Config for `des` parameter. */ +export declare interface BatchJobDestination { + /** Storage format of the output files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URI to the output file. + */ + gcsUri?: string; + /** The BigQuery URI to the output table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the output data + (e.g. "files/12345"). The file will be a JSONL file with a single response + per line. The responses will be GenerateContentResponse messages formatted + as JSON. The responses will be written in the same order as the input + requests. + */ + fileName?: string; + /** The responses to the requests in the batch. Returned when the batch was + built using inlined requests. The responses will be in the same order as + the input requests. + */ + inlinedResponses?: InlinedResponse[]; +} + +export declare type BatchJobDestinationUnion = BatchJobDestination | string; + +/** Config for `src` parameter. */ +export declare interface BatchJobSource { + /** Storage format of the input files. Must be one of: + 'jsonl', 'bigquery'. + */ + format?: string; + /** The Google Cloud Storage URIs to input files. + */ + gcsUri?: string[]; + /** The BigQuery URI to input table. + */ + bigqueryUri?: string; + /** The Gemini Developer API's file resource name of the input data + (e.g. "files/12345"). + */ + fileName?: string; + /** The Gemini Developer API's inlined input data to run batch job. + */ + inlinedRequests?: InlinedRequest[]; +} + +export declare type BatchJobSourceUnion = + | BatchJobSource + | InlinedRequest[] + | string; + +/** Defines the function behavior. Defaults to `BLOCKING`. */ +export declare enum Behavior { + /** + * This value is unused. + */ + UNSPECIFIED = "UNSPECIFIED", + /** + * If set, the system will wait to receive the function response before continuing the conversation. + */ + BLOCKING = "BLOCKING", + /** + * If set, the system will not wait to receive the function response. Instead, it will attempt to handle function responses as they become available while maintaining the conversation between the user and the model. + */ + NON_BLOCKING = "NON_BLOCKING", +} + +/** Content blob. */ +declare interface Blob_2 { + /** Optional. Display name of the blob. Used to provide a label or filename to distinguish blobs. This field is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. Raw bytes. + * @remarks Encoded as base64 string. */ + data?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} +export { Blob_2 as Blob }; + +export declare type BlobImageUnion = Blob_2; + +/** Output only. Blocked reason. */ +export declare enum BlockedReason { + /** + * Unspecified blocked reason. + */ + BLOCKED_REASON_UNSPECIFIED = "BLOCKED_REASON_UNSPECIFIED", + /** + * Candidates blocked due to safety. + */ + SAFETY = "SAFETY", + /** + * Candidates blocked due to other reason. + */ + OTHER = "OTHER", + /** + * Candidates blocked due to the terms which are included from the terminology blocklist. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Candidates blocked due to prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Candidates blocked due to unsafe image generation content. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", +} + +/** A resource used in LLM queries for users to explicitly specify what to cache. */ +export declare interface CachedContent { + /** The server-generated resource name of the cached content. */ + name?: string; + /** The user-generated meaningful display name of the cached content. */ + displayName?: string; + /** The name of the publisher model to use for cached content. */ + model?: string; + /** Creation time of the cache entry. */ + createTime?: string; + /** When the cache entry was last updated in UTC time. */ + updateTime?: string; + /** Expiration time of the cached content. */ + expireTime?: string; + /** Metadata on the usage of the cached content. */ + usageMetadata?: CachedContentUsageMetadata; +} + +/** Metadata on the usage of the cached content. */ +export declare interface CachedContentUsageMetadata { + /** Duration of audio in seconds. */ + audioDurationSeconds?: number; + /** Number of images. */ + imageCount?: number; + /** Number of text characters. */ + textCount?: number; + /** Total number of tokens that the cached content consumes. */ + totalTokenCount?: number; + /** Duration of video in seconds. */ + videoDurationSeconds?: number; +} + +export declare class Caches extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists cached content configurations. + * + * @param params - The parameters for the list request. + * @return The paginated results of the list of cached contents. + * + * @example + * ```ts + * const cachedContents = await ai.caches.list({config: {'pageSize': 2}}); + * for await (const cachedContent of cachedContents) { + * console.log(cachedContent); + * } + * ``` + */ + list: ( + params?: types.ListCachedContentsParameters, + ) => Promise>; + /** + * Creates a cached contents resource. + * + * @remarks + * Context caching is only supported for specific models. See [Gemini + * Developer API reference](https://ai.google.dev/gemini-api/docs/caching?lang=node/context-cac) + * and [Vertex AI reference](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview#supported_models) + * for more information. + * + * @param params - The parameters for the create request. + * @return The created cached content. + * + * @example + * ```ts + * const contents = ...; // Initialize the content to cache. + * const response = await ai.caches.create({ + * model: 'gemini-2.0-flash-001', + * config: { + * 'contents': contents, + * 'displayName': 'test cache', + * 'systemInstruction': 'What is the sum of the two pdfs?', + * 'ttl': '86400s', + * } + * }); + * ``` + */ + create( + params: types.CreateCachedContentParameters, + ): Promise; + /** + * Gets cached content configurations. + * + * @param params - The parameters for the get request. + * @return The cached content. + * + * @example + * ```ts + * await ai.caches.get({name: '...'}); // The server-generated resource name. + * ``` + */ + get(params: types.GetCachedContentParameters): Promise; + /** + * Deletes cached content. + * + * @param params - The parameters for the delete request. + * @return The empty response returned by the API. + * + * @example + * ```ts + * await ai.caches.delete({name: '...'}); // The server-generated resource name. + * ``` + */ + delete( + params: types.DeleteCachedContentParameters, + ): Promise; + /** + * Updates cached content configurations. + * + * @param params - The parameters for the update request. + * @return The updated cached content. + * + * @example + * ```ts + * const response = await ai.caches.update({ + * name: '...', // The server-generated resource name. + * config: {'ttl': '7600s'} + * }); + * ``` + */ + update( + params: types.UpdateCachedContentParameters, + ): Promise; + private listInternal; +} + +/** + * CallableTool is an invokable tool that can be executed with external + * application (e.g., via Model Context Protocol) or local functions with + * function calling. + */ +export declare interface CallableTool { + /** + * Returns tool that can be called by Gemini. + */ + tool(): Promise; + /** + * Executes the callable tool with the given function call arguments and + * returns the response parts from the tool execution. + */ + callTool(functionCalls: FunctionCall[]): Promise; +} + +/** + * CallableToolConfig is the configuration for a callable tool. + */ +export declare interface CallableToolConfig { + /** + * Specifies the model's behavior after invoking this tool. + */ + behavior?: Behavior; + /** + * Timeout for remote calls in milliseconds. Note this timeout applies only to + * tool remote calls, and not making HTTP requests to the API. */ + timeout?: number; +} + +/** Optional parameters. */ +export declare interface CancelBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.cancel parameters. */ +export declare interface CancelBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: CancelBatchJobConfig; +} + +/** A response candidate generated from the model. */ +export declare interface Candidate { + /** Contains the multi-part content of the response. + */ + content?: Content; + /** Source attribution of the generated content. + */ + citationMetadata?: CitationMetadata; + /** Describes the reason the model stopped generating tokens. + */ + finishMessage?: string; + /** Number of tokens for this candidate. + */ + tokenCount?: number; + /** The reason why the model stopped generating tokens. + If empty, the model has not stopped generating the tokens. + */ + finishReason?: FinishReason; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; + /** Output only. Average log probability score of the candidate. */ + avgLogprobs?: number; + /** Output only. Metadata specifies sources used to ground generated content. */ + groundingMetadata?: GroundingMetadata; + /** Output only. Index of the candidate. */ + index?: number; + /** Output only. Log-likelihood scores for the response tokens and top tokens */ + logprobsResult?: LogprobsResult; + /** Output only. List of ratings for the safety of a response candidate. There is at most one rating per category. */ + safetyRatings?: SafetyRating[]; +} + +/** + * Chat session that enables sending messages to the model with previous + * conversation context. + * + * @remarks + * The session maintains all the turns between user and model. + */ +export declare class Chat { + private readonly apiClient; + private readonly modelsModule; + private readonly model; + private readonly config; + private history; + private sendPromise; + constructor( + apiClient: ApiClient, + modelsModule: Models, + model: string, + config?: types.GenerateContentConfig, + history?: types.Content[], + ); + /** + * Sends a message to the model and returns the response. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessageStream} for streaming method. + * @param params - parameters for sending messages within a chat session. + * @returns The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessage({ + * message: 'Why is the sky blue?' + * }); + * console.log(response.text); + * ``` + */ + sendMessage( + params: types.SendMessageParameters, + ): Promise; + /** + * Sends a message to the model and returns the response in chunks. + * + * @remarks + * This method will wait for the previous message to be processed before + * sending the next message. + * + * @see {@link Chat#sendMessage} for non-streaming method. + * @param params - parameters for sending the message. + * @return The model's response. + * + * @example + * ```ts + * const chat = ai.chats.create({model: 'gemini-2.0-flash'}); + * const response = await chat.sendMessageStream({ + * message: 'Why is the sky blue?' + * }); + * for await (const chunk of response) { + * console.log(chunk.text); + * } + * ``` + */ + sendMessageStream( + params: types.SendMessageParameters, + ): Promise>; + /** + * Returns the chat history. + * + * @remarks + * The history is a list of contents alternating between user and model. + * + * There are two types of history: + * - The `curated history` contains only the valid turns between user and + * model, which will be included in the subsequent requests sent to the model. + * - The `comprehensive history` contains all turns, including invalid or + * empty model outputs, providing a complete record of the history. + * + * The history is updated after receiving the response from the model, + * for streaming response, it means receiving the last chunk of the response. + * + * The `comprehensive history` is returned by default. To get the `curated + * history`, set the `curated` parameter to `true`. + * + * @param curated - whether to return the curated history or the comprehensive + * history. + * @return History contents alternating between user and model for the entire + * chat session. + */ + getHistory(curated?: boolean): types.Content[]; + private processStreamResponse; + private recordHistory; +} + +/** + * A utility class to create a chat session. + */ +export declare class Chats { + private readonly modelsModule; + private readonly apiClient; + constructor(modelsModule: Models, apiClient: ApiClient); + /** + * Creates a new chat session. + * + * @remarks + * The config in the params will be used for all requests within the chat + * session unless overridden by a per-request `config` in + * @see {@link types.SendMessageParameters#config}. + * + * @param params - Parameters for creating a chat session. + * @returns A new chat session. + * + * @example + * ```ts + * const chat = ai.chats.create({ + * model: 'gemini-2.0-flash' + * config: { + * temperature: 0.5, + * maxOutputTokens: 1024, + * } + * }); + * ``` + */ + create(params: types.CreateChatParameters): Chat; +} + +/** Describes the machine learning model version checkpoint. */ +export declare interface Checkpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; +} + +/** Source attributions for content. */ +export declare interface Citation { + /** Output only. End index into the content. */ + endIndex?: number; + /** Output only. License of the attribution. */ + license?: string; + /** Output only. Publication date of the attribution. */ + publicationDate?: GoogleTypeDate; + /** Output only. Start index into the content. */ + startIndex?: number; + /** Output only. Title of the attribution. */ + title?: string; + /** Output only. Url reference of the attribution. */ + uri?: string; +} + +/** Citation information when the model quotes another source. */ +export declare interface CitationMetadata { + /** Contains citation information when the model directly quotes, at + length, from another source. Can include traditional websites and code + repositories. + */ + citations?: Citation[]; +} + +/** Result of executing the [ExecutableCode]. Only generated when using the [CodeExecution] tool, and always follows a `part` containing the [ExecutableCode]. */ +export declare interface CodeExecutionResult { + /** Required. Outcome of the code execution. */ + outcome?: Outcome; + /** Optional. Contains stdout when code execution is successful, stderr or other description otherwise. */ + output?: string; +} + +/** Optional parameters for computing tokens. */ +export declare interface ComputeTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for computing tokens. */ +export declare interface ComputeTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Optional parameters for the request. + */ + config?: ComputeTokensConfig; +} + +/** Response for computing tokens. */ +export declare class ComputeTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Lists of tokens info from the input. A ComputeTokensRequest could have multiple instances with a prompt in each instance. We also need to return lists of tokens info for the request with multiple instances. */ + tokensInfo?: TokensInfo[]; +} + +/** Contains the multi-part content of a message. */ +export declare interface Content { + /** List of parts that constitute a single message. Each part may have + a different IANA MIME type. */ + parts?: Part[]; + /** Optional. The producer of the content. Must be either 'user' or + 'model'. Useful to set for multi-turn conversations, otherwise can be + empty. If role is not specified, SDK will determine the role. */ + role?: string; +} + +/** The embedding generated from an input content. */ +export declare interface ContentEmbedding { + /** A list of floats representing an embedding. + */ + values?: number[]; + /** Vertex API only. Statistics of the input text associated with this + embedding. + */ + statistics?: ContentEmbeddingStatistics; +} + +/** Statistics of the input text associated with the result of content embedding. */ +export declare interface ContentEmbeddingStatistics { + /** Vertex API only. If the input text was truncated due to having + a length longer than the allowed maximum input. + */ + truncated?: boolean; + /** Vertex API only. Number of tokens of the input text. + */ + tokenCount?: number; +} + +export declare type ContentListUnion = + | Content + | Content[] + | PartUnion + | PartUnion[]; + +export declare type ContentUnion = Content | PartUnion[] | PartUnion; + +/** Enables context window compression -- mechanism managing model context window so it does not exceed given length. */ +export declare interface ContextWindowCompressionConfig { + /** Number of tokens (before running turn) that triggers context window compression mechanism. */ + triggerTokens?: string; + /** Sliding window compression mechanism. */ + slidingWindow?: SlidingWindow; +} + +/** Configuration for a Control reference image. */ +export declare interface ControlReferenceConfig { + /** The type of control reference image to use. */ + controlType?: ControlReferenceType; + /** Defaults to False. When set to True, the control image will be + computed by the model based on the control type. When set to False, + the control image must be provided by the user. */ + enableControlImageComputation?: boolean; +} + +/** A control reference image. + + The image of the control reference image is either a control image provided + by the user, or a regular image which the backend will use to generate a + control image of. In the case of the latter, the + enable_control_image_computation field in the config should be set to True. + + A control image is an image that represents a sketch image of areas for the + model to fill in based on the prompt. + */ +export declare class ControlReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the control reference image. */ + config?: ControlReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the control type of a control reference image. */ +export declare enum ControlReferenceType { + CONTROL_TYPE_DEFAULT = "CONTROL_TYPE_DEFAULT", + CONTROL_TYPE_CANNY = "CONTROL_TYPE_CANNY", + CONTROL_TYPE_SCRIBBLE = "CONTROL_TYPE_SCRIBBLE", + CONTROL_TYPE_FACE_MESH = "CONTROL_TYPE_FACE_MESH", +} + +/** Config for the count_tokens method. */ +export declare interface CountTokensConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + */ + systemInstruction?: ContentUnion; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: Tool[]; + /** Configuration that the model uses to generate the response. Not + supported by the Gemini Developer API. + */ + generationConfig?: GenerationConfig; +} + +/** Parameters for counting tokens. */ +export declare interface CountTokensParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Input content. */ + contents: ContentListUnion; + /** Configuration for counting tokens. */ + config?: CountTokensConfig; +} + +/** Response for counting tokens. */ +export declare class CountTokensResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Total number of tokens. */ + totalTokens?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; +} + +/** Optional parameters. */ +export declare interface CreateAuthTokenConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** An optional time after which, when using the resulting token, + messages in Live API sessions will be rejected. (Gemini may + preemptively close the session after this time.) + + If not set then this defaults to 30 minutes in the future. If set, this + value must be less than 20 hours in the future. */ + expireTime?: string; + /** The time after which new Live API sessions using the token + resulting from this request will be rejected. + + If not set this defaults to 60 seconds in the future. If set, this value + must be less than 20 hours in the future. */ + newSessionExpireTime?: string; + /** The number of times the token can be used. If this value is zero + then no limit is applied. Default is 1. Resuming a Live API session does + not count as a use. */ + uses?: number; + /** Configuration specific to Live API connections created using this token. */ + liveConnectConstraints?: LiveConnectConstraints; + /** Additional fields to lock in the effective LiveConnectParameters. */ + lockAdditionalFields?: string[]; +} + +/** Config for auth_tokens.create parameters. */ +export declare interface CreateAuthTokenParameters { + /** Optional parameters for the request. */ + config?: CreateAuthTokenConfig; +} + +/** Config for optional parameters. */ +export declare interface CreateBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The user-defined name of this BatchJob. + */ + displayName?: string; + /** GCS or BigQuery URI prefix for the output predictions. Example: + "gs://path/to/output/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + dest?: BatchJobDestinationUnion; +} + +/** Config for batches.create parameters. */ +export declare interface CreateBatchJobParameters { + /** The name of the model to produces the predictions via the BatchJob. + */ + model?: string; + /** GCS URI(-s) or BigQuery URI to your input data to run batch job. + Example: "gs://path/to/input/data" or "bq://projectId.bqDatasetId.bqTableId". + */ + src: BatchJobSourceUnion; + /** Optional parameters for creating a BatchJob. + */ + config?: CreateBatchJobConfig; +} + +/** Optional configuration for cached content creation. */ +export declare interface CreateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; + /** The user-generated meaningful display name of the cached content. + */ + displayName?: string; + /** The content to cache. + */ + contents?: ContentListUnion; + /** Developer set system instruction. + */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + */ + tools?: Tool[]; + /** Configuration for the tools to use. This config is shared for all tools. + */ + toolConfig?: ToolConfig; + /** The Cloud KMS resource identifier of the customer managed + encryption key used to protect a resource. + The key needs to be in the same region as where the compute resource is + created. See + https://cloud.google.com/vertex-ai/docs/general/cmek for more + details. If this is set, then all created CachedContent objects + will be encrypted with the provided encryption key. + Allowed formats: projects/{project}/locations/{location}/keyRings/{key_ring}/cryptoKeys/{crypto_key} + */ + kmsKeyName?: string; +} + +/** Parameters for caches.create method. */ +export declare interface CreateCachedContentParameters { + /** ID of the model to use. Example: gemini-2.0-flash */ + model: string; + /** Configuration that contains optional parameters. + */ + config?: CreateCachedContentConfig; +} + +/** Parameters for initializing a new chat session. + + These parameters are used when creating a chat session with the + `chats.create()` method. + */ +export declare interface CreateChatParameters { + /** The name of the model to use for the chat session. + + For example: 'gemini-2.0-flash', 'gemini-2.0-flash-lite', etc. See Gemini API + docs to find the available models. + */ + model: string; + /** Config for the entire chat session. + + This config applies to all requests within the session + unless overridden by a per-request `config` in `SendMessageParameters`. + */ + config?: GenerateContentConfig; + /** The initial conversation history for the chat session. + + This allows you to start the chat with a pre-existing history. The history + must be a list of `Content` alternating between 'user' and 'model' roles. + It should start with a 'user' message. + */ + history?: Content[]; +} + +/** Used to override the default configuration. */ +export declare interface CreateFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the private _create method. */ +export declare interface CreateFileParameters { + /** The file to be uploaded. + mime_type: (Required) The MIME type of the file. Must be provided. + name: (Optional) The name of the file in the destination (e.g. + 'files/sample-image'). + display_name: (Optional) The display name of the file. + */ + file: File_2; + /** Used to override the default configuration. */ + config?: CreateFileConfig; +} + +/** Response for the create file method. */ +export declare class CreateFileResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; +} + +/** + * Creates a `Content` object with a model role from a `PartListUnion` object or `string`. + */ +export declare function createModelContent( + partOrString: PartListUnion | string, +): Content; + +/** + * Creates a `Part` object from a `base64` encoded `string`. + */ +export declare function createPartFromBase64( + data: string, + mimeType: string, +): Part; + +/** + * Creates a `Part` object from the `outcome` and `output` of a `CodeExecutionResult` object. + */ +export declare function createPartFromCodeExecutionResult( + outcome: Outcome, + output: string, +): Part; + +/** + * Creates a `Part` object from the `code` and `language` of an `ExecutableCode` object. + */ +export declare function createPartFromExecutableCode( + code: string, + language: Language, +): Part; + +/** + * Creates a `Part` object from a `FunctionCall` object. + */ +export declare function createPartFromFunctionCall( + name: string, + args: Record, +): Part; + +/** + * Creates a `Part` object from a `FunctionResponse` object. + */ +export declare function createPartFromFunctionResponse( + id: string, + name: string, + response: Record, +): Part; + +/** + * Creates a `Part` object from a `text` string. + */ +export declare function createPartFromText(text: string): Part; + +/** + * Creates a `Part` object from a `URI` string. + */ +export declare function createPartFromUri(uri: string, mimeType: string): Part; + +/** Supervised fine-tuning job creation request - optional fields. */ +export declare interface CreateTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDataset?: TuningValidationDataset; + /** The display name of the tuned Model. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; + /** The description of the TuningJob */ + description?: string; + /** Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: number; + /** Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; + /** If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. */ + exportLastCheckpointOnly?: boolean; + /** Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** The batch size hyperparameter for tuning. If not set, a default of 4 or 16 will be used based on the number of training examples. */ + batchSize?: number; + /** The learning rate hyperparameter for tuning. If not set, a default of 0.001 or 0.0002 will be calculated based on the number of training examples. */ + learningRate?: number; +} + +/** Supervised fine-tuning job creation parameters - optional fields. */ +export declare interface CreateTuningJobParameters { + /** The base model that is being tuned, e.g., "gemini-1.0-pro-002". */ + baseModel: string; + /** Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDataset: TuningDataset; + /** Configuration for the tuning job. */ + config?: CreateTuningJobConfig; +} + +/** + * Creates a `Content` object with a user role from a `PartListUnion` object or `string`. + */ +export declare function createUserContent( + partOrString: PartListUnion | string, +): Content; + +/** Distribution computed over a tuning dataset. */ +export declare interface DatasetDistribution { + /** Output only. Defines the histogram bucket. */ + buckets?: DatasetDistributionDistributionBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: number; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface DatasetDistributionDistributionBucket { + /** Output only. Number of values in the bucket. */ + count?: string; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Statistics computed over a tuning dataset. */ +export declare interface DatasetStats { + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: DatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: DatasetDistribution; +} + +/** Optional parameters for models.get method. */ +export declare interface DeleteBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.delete parameters. */ +export declare interface DeleteBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: DeleteBatchJobConfig; +} + +/** Optional parameters for caches.delete method. */ +export declare interface DeleteCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.delete method. */ +export declare interface DeleteCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: DeleteCachedContentConfig; +} + +/** Empty response for caches.delete method. */ +export declare class DeleteCachedContentResponse {} + +/** Used to override the default configuration. */ +export declare interface DeleteFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface DeleteFileParameters { + /** The name identifier for the file to be deleted. */ + name: string; + /** Used to override the default configuration. */ + config?: DeleteFileConfig; +} + +/** Response for the delete file method. */ +export declare class DeleteFileResponse {} + +/** Configuration for deleting a tuned model. */ +export declare interface DeleteModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for deleting a tuned model. */ +export declare interface DeleteModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: DeleteModelConfig; +} + +export declare class DeleteModelResponse {} + +/** The return value of delete operation. */ +export declare interface DeleteResourceJob { + name?: string; + done?: boolean; + error?: JobError; +} + +/** Statistics computed for datasets used for distillation. */ +export declare interface DistillationDataStats { + /** Output only. Statistics computed for the training dataset. */ + trainingDatasetStats?: DatasetStats; +} + +/** Hyperparameters for Distillation. */ +export declare interface DistillationHyperParameters { + /** Optional. Adapter size for distillation. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. */ + learningRateMultiplier?: number; +} + +/** Tuning Spec for Distillation. */ +export declare interface DistillationSpec { + /** The base teacher model that is being distilled. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseTeacherModel?: string; + /** Optional. Hyperparameters for Distillation. */ + hyperParameters?: DistillationHyperParameters; + /** Deprecated. A path in a Cloud Storage bucket, which will be treated as the root output directory of the distillation pipeline. It is used by the system to generate the paths of output artifacts. */ + pipelineRootDirectory?: string; + /** The student model that is being tuned, e.g., "google/gemma-2b-1.1-it". Deprecated. Use base_model instead. */ + studentModel?: string; + /** Deprecated. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** The resource name of the Tuned teacher model. Format: `projects/{project}/locations/{location}/models/{model}`. */ + tunedTeacherModelSource?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type DownloadableFileUnion = + | string + | File_2 + | GeneratedVideo + | Video; + +declare interface Downloader { + /** + * Downloads a file to the given location. + * + * @param params The parameters for downloading the file. + * @param apiClient The ApiClient to use for uploading. + * @return A Promises that resolves when the download is complete. + */ + download(params: DownloadFileParameters, apiClient: ApiClient): Promise; +} + +/** Used to override the default configuration. */ +export declare interface DownloadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters used to download a file. */ +export declare interface DownloadFileParameters { + /** The file to download. It can be a file name, a file object or a generated video. */ + file: DownloadableFileUnion; + /** Location where the file should be downloaded to. */ + downloadPath: string; + /** Configuration to for the download operation. */ + config?: DownloadFileConfig; +} + +/** Describes the options to customize dynamic retrieval. */ +export declare interface DynamicRetrievalConfig { + /** The mode of the predictor to be used in dynamic retrieval. */ + mode?: DynamicRetrievalConfigMode; + /** Optional. The threshold to be used in dynamic retrieval. If not set, a system default value is used. */ + dynamicThreshold?: number; +} + +/** Config for the dynamic retrieval config mode. */ +export declare enum DynamicRetrievalConfigMode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** Configuration for editing an image. */ +export declare interface EditImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** Describes the editing mode for the request. */ + editMode?: EditMode; + /** The number of sampling steps. A higher value has better image + quality, while a lower value has better latency. */ + baseSteps?: number; +} + +/** Parameters for the request to edit an image. */ +export declare interface EditImageParameters { + /** The model to use. */ + model: string; + /** A text description of the edit to apply to the image. */ + prompt: string; + /** The reference images for Imagen 3 editing. */ + referenceImages: ReferenceImage[]; + /** Configuration for editing. */ + config?: EditImageConfig; +} + +/** Response for the request to edit an image. */ +export declare class EditImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Enum representing the Imagen 3 Edit mode. */ +export declare enum EditMode { + EDIT_MODE_DEFAULT = "EDIT_MODE_DEFAULT", + EDIT_MODE_INPAINT_REMOVAL = "EDIT_MODE_INPAINT_REMOVAL", + EDIT_MODE_INPAINT_INSERTION = "EDIT_MODE_INPAINT_INSERTION", + EDIT_MODE_OUTPAINT = "EDIT_MODE_OUTPAINT", + EDIT_MODE_CONTROLLED_EDITING = "EDIT_MODE_CONTROLLED_EDITING", + EDIT_MODE_STYLE = "EDIT_MODE_STYLE", + EDIT_MODE_BGSWAP = "EDIT_MODE_BGSWAP", + EDIT_MODE_PRODUCT_IMAGE = "EDIT_MODE_PRODUCT_IMAGE", +} + +/** Optional parameters for the embed_content method. */ +export declare interface EmbedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Type of task for which the embedding will be used. + */ + taskType?: string; + /** Title for the text. Only applicable when TaskType is + `RETRIEVAL_DOCUMENT`. + */ + title?: string; + /** Reduced dimension for the output embedding. If set, + excessive values in the output embedding are truncated from the end. + Supported by newer models since 2024 only. You cannot set this value if + using the earlier model (`models/embedding-001`). + */ + outputDimensionality?: number; + /** Vertex API only. The MIME type of the input. + */ + mimeType?: string; + /** Vertex API only. Whether to silently truncate inputs longer than + the max sequence length. If this option is set to false, oversized inputs + will lead to an INVALID_ARGUMENT error, similar to other text APIs. + */ + autoTruncate?: boolean; +} + +/** Request-level metadata for the Vertex Embed Content API. */ +export declare interface EmbedContentMetadata { + /** Vertex API only. The total number of billable characters included + in the request. + */ + billableCharacterCount?: number; +} + +/** Parameters for the embed_content method. */ +export declare interface EmbedContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The content to embed. Only the `parts.text` fields will be counted. + */ + contents: ContentListUnion; + /** Configuration that contains optional parameters. + */ + config?: EmbedContentConfig; +} + +/** Response for the embed_content method. */ +export declare class EmbedContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The embeddings for each request, in the same order as provided in + the batch request. + */ + embeddings?: ContentEmbedding[]; + /** Vertex API only. Metadata about the request. + */ + metadata?: EmbedContentMetadata; +} + +/** Represents a customer-managed encryption key spec that can be applied to a top-level resource. */ +export declare interface EncryptionSpec { + /** Required. The Cloud KMS resource identifier of the customer managed encryption key used to protect a resource. Has the form: `projects/my-project/locations/my-region/keyRings/my-kr/cryptoKeys/my-key`. The key needs to be in the same region as where the compute resource is created. */ + kmsKeyName?: string; +} + +/** An endpoint where you deploy models. */ +export declare interface Endpoint { + /** Resource name of the endpoint. */ + name?: string; + /** ID of the model that's deployed to the endpoint. */ + deployedModelId?: string; +} + +/** End of speech sensitivity. */ +export declare enum EndSensitivity { + /** + * The default is END_SENSITIVITY_LOW. + */ + END_SENSITIVITY_UNSPECIFIED = "END_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection ends speech more often. + */ + END_SENSITIVITY_HIGH = "END_SENSITIVITY_HIGH", + /** + * Automatic detection ends speech less often. + */ + END_SENSITIVITY_LOW = "END_SENSITIVITY_LOW", +} + +/** Tool to search public web data, powered by Vertex AI Search and Sec4 compliance. */ +export declare interface EnterpriseWebSearch {} + +/** Required. The environment being operated. */ +export declare enum Environment { + /** + * Defaults to browser. + */ + ENVIRONMENT_UNSPECIFIED = "ENVIRONMENT_UNSPECIFIED", + /** + * Operates in a web browser. + */ + ENVIRONMENT_BROWSER = "ENVIRONMENT_BROWSER", +} + +/** Code generated by the model that is meant to be executed, and the result returned to the model. Generated when using the [CodeExecution] tool, in which the code will be automatically executed, and a corresponding [CodeExecutionResult] will also be generated. */ +export declare interface ExecutableCode { + /** Required. The code to be executed. */ + code?: string; + /** Required. Programming language of the `code`. */ + language?: Language; +} + +/** Retrieve from data source powered by external API for grounding. The external API is not owned by Google, but need to follow the pre-defined API spec. */ +export declare interface ExternalApi { + /** The authentication config to access the API. Deprecated. Please use auth_config instead. */ + apiAuth?: ApiAuth; + /** The API spec that the external API implements. */ + apiSpec?: ApiSpec; + /** The authentication config to access the API. */ + authConfig?: AuthConfig; + /** Parameters for the elastic search API. */ + elasticSearchParams?: ExternalApiElasticSearchParams; + /** The endpoint of the external API. The system will call the API at this endpoint to retrieve the data for grounding. Example: https://acme.com:443/search */ + endpoint?: string; + /** Parameters for the simple search API. */ + simpleSearchParams?: ExternalApiSimpleSearchParams; +} + +/** The search parameters to use for the ELASTIC_SEARCH spec. */ +export declare interface ExternalApiElasticSearchParams { + /** The ElasticSearch index to use. */ + index?: string; + /** Optional. Number of hits (chunks) to request. When specified, it is passed to Elasticsearch as the `num_hits` param. */ + numHits?: number; + /** The ElasticSearch search template to use. */ + searchTemplate?: string; +} + +/** The search parameters to use for SIMPLE_SEARCH spec. */ +export declare interface ExternalApiSimpleSearchParams {} + +/** Options for feature selection preference. */ +export declare enum FeatureSelectionPreference { + FEATURE_SELECTION_PREFERENCE_UNSPECIFIED = "FEATURE_SELECTION_PREFERENCE_UNSPECIFIED", + PRIORITIZE_QUALITY = "PRIORITIZE_QUALITY", + BALANCED = "BALANCED", + PRIORITIZE_COST = "PRIORITIZE_COST", +} + +export declare interface FetchPredictOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the fetchPredictOperation method. */ +export declare interface FetchPredictOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + resourceName: string; + /** Used to override the default configuration. */ + config?: FetchPredictOperationConfig; +} + +/** A file uploaded to the API. */ +declare interface File_2 { + /** The `File` resource name. The ID (name excluding the "files/" prefix) can contain up to 40 characters that are lowercase alphanumeric or dashes (-). The ID cannot start or end with a dash. If the name is empty on create, a unique name will be generated. Example: `files/123-456` */ + name?: string; + /** Optional. The human-readable display name for the `File`. The display name must be no more than 512 characters in length, including spaces. Example: 'Welcome Image' */ + displayName?: string; + /** Output only. MIME type of the file. */ + mimeType?: string; + /** Output only. Size of the file in bytes. */ + sizeBytes?: string; + /** Output only. The timestamp of when the `File` was created. */ + createTime?: string; + /** Output only. The timestamp of when the `File` will be deleted. Only set if the `File` is scheduled to expire. */ + expirationTime?: string; + /** Output only. The timestamp of when the `File` was last updated. */ + updateTime?: string; + /** Output only. SHA-256 hash of the uploaded bytes. The hash value is encoded in base64 format. */ + sha256Hash?: string; + /** Output only. The URI of the `File`. */ + uri?: string; + /** Output only. The URI of the `File`, only set for downloadable (generated) files. */ + downloadUri?: string; + /** Output only. Processing state of the File. */ + state?: FileState; + /** Output only. The source of the `File`. */ + source?: FileSource; + /** Output only. Metadata for a video. */ + videoMetadata?: Record; + /** Output only. Error status if File processing failed. */ + error?: FileStatus; +} +export { File_2 as File }; + +/** URI based data. */ +export declare interface FileData { + /** Optional. Display name of the file data. Used to provide a label or filename to distinguish file datas. It is not currently used in the Gemini GenerateContent calls. */ + displayName?: string; + /** Required. URI. */ + fileUri?: string; + /** Required. The IANA standard MIME type of the source data. */ + mimeType?: string; +} + +export declare class Files extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Lists all current project files from the service. + * + * @param params - The parameters for the list request + * @return The paginated results of the list of files + * + * @example + * The following code prints the names of all files from the service, the + * size of each page is 10. + * + * ```ts + * const listResponse = await ai.files.list({config: {'pageSize': 10}}); + * for await (const file of listResponse) { + * console.log(file.name); + * } + * ``` + */ + list: (params?: types.ListFilesParameters) => Promise>; + /** + * Uploads a file asynchronously to the Gemini API. + * This method is not available in Vertex AI. + * Supported upload sources: + * - Node.js: File path (string) or Blob object. + * - Browser: Blob object (e.g., File). + * + * @remarks + * The `mimeType` can be specified in the `config` parameter. If omitted: + * - For file path (string) inputs, the `mimeType` will be inferred from the + * file extension. + * - For Blob object inputs, the `mimeType` will be set to the Blob's `type` + * property. + * Somex eamples for file extension to mimeType mapping: + * .txt -> text/plain + * .json -> application/json + * .jpg -> image/jpeg + * .png -> image/png + * .mp3 -> audio/mpeg + * .mp4 -> video/mp4 + * + * This section can contain multiple paragraphs and code examples. + * + * @param params - Optional parameters specified in the + * `types.UploadFileParameters` interface. + * @see {@link types.UploadFileParameters#config} for the optional + * config in the parameters. + * @return A promise that resolves to a `types.File` object. + * @throws An error if called on a Vertex AI client. + * @throws An error if the `mimeType` is not provided and can not be inferred, + * the `mimeType` can be provided in the `params.config` parameter. + * @throws An error occurs if a suitable upload location cannot be established. + * + * @example + * The following code uploads a file to Gemini API. + * + * ```ts + * const file = await ai.files.upload({file: 'file.txt', config: { + * mimeType: 'text/plain', + * }}); + * console.log(file.name); + * ``` + */ + upload(params: types.UploadFileParameters): Promise; + /** + * Downloads a remotely stored file asynchronously to a location specified in + * the `params` object. This method only works on Node environment, to + * download files in the browser, use a browser compliant method like an + * tag. + * + * @param params - The parameters for the download request. + * + * @example + * The following code downloads an example file named "files/mehozpxf877d" as + * "file.txt". + * + * ```ts + * await ai.files.download({file: file.name, downloadPath: 'file.txt'}); + * ``` + */ + download(params: types.DownloadFileParameters): Promise; + private listInternal; + private createInternal; + /** + * Retrieves the file information from the service. + * + * @param params - The parameters for the get request + * @return The Promise that resolves to the types.File object requested. + * + * @example + * ```ts + * const config: GetFileParameters = { + * name: fileName, + * }; + * file = await ai.files.get(config); + * console.log(file.name); + * ``` + */ + get(params: types.GetFileParameters): Promise; + /** + * Deletes a remotely stored file. + * + * @param params - The parameters for the delete request. + * @return The DeleteFileResponse, the response for the delete method. + * + * @example + * The following code deletes an example file named "files/mehozpxf877d". + * + * ```ts + * await ai.files.delete({name: file.name}); + * ``` + */ + delete(params: types.DeleteFileParameters): Promise; +} + +/** Source of the File. */ +export declare enum FileSource { + SOURCE_UNSPECIFIED = "SOURCE_UNSPECIFIED", + UPLOADED = "UPLOADED", + GENERATED = "GENERATED", +} + +/** + * Represents the size and mimeType of a file. The information is used to + * request the upload URL from the https://generativelanguage.googleapis.com/upload/v1beta/files endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface FileStat { + /** + * The size of the file in bytes. + */ + size: number; + /** + * The MIME type of the file. + */ + type: string | undefined; +} + +/** State for the lifecycle of a File. */ +export declare enum FileState { + STATE_UNSPECIFIED = "STATE_UNSPECIFIED", + PROCESSING = "PROCESSING", + ACTIVE = "ACTIVE", + FAILED = "FAILED", +} + +/** Status of a File that uses a common error model. */ +export declare interface FileStatus { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + message?: string; + /** The status code. 0 for OK, 1 for CANCELLED */ + code?: number; +} + +/** Output only. The reason why the model stopped generating tokens. + + If empty, the model has not stopped generating the tokens. + */ +export declare enum FinishReason { + /** + * The finish reason is unspecified. + */ + FINISH_REASON_UNSPECIFIED = "FINISH_REASON_UNSPECIFIED", + /** + * Token generation reached a natural stopping point or a configured stop sequence. + */ + STOP = "STOP", + /** + * Token generation reached the configured maximum output tokens. + */ + MAX_TOKENS = "MAX_TOKENS", + /** + * Token generation stopped because the content potentially contains safety violations. NOTE: When streaming, [content][] is empty if content filters blocks the output. + */ + SAFETY = "SAFETY", + /** + * The token generation stopped because of potential recitation. + */ + RECITATION = "RECITATION", + /** + * The token generation stopped because of using an unsupported language. + */ + LANGUAGE = "LANGUAGE", + /** + * All other reasons that stopped the token generation. + */ + OTHER = "OTHER", + /** + * Token generation stopped because the content contains forbidden terms. + */ + BLOCKLIST = "BLOCKLIST", + /** + * Token generation stopped for potentially containing prohibited content. + */ + PROHIBITED_CONTENT = "PROHIBITED_CONTENT", + /** + * Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + */ + SPII = "SPII", + /** + * The function call generated by the model is invalid. + */ + MALFORMED_FUNCTION_CALL = "MALFORMED_FUNCTION_CALL", + /** + * Token generation stopped because generated images have safety violations. + */ + IMAGE_SAFETY = "IMAGE_SAFETY", + /** + * The tool call generated by the model is invalid. + */ + UNEXPECTED_TOOL_CALL = "UNEXPECTED_TOOL_CALL", +} + +/** A function call. */ +export declare interface FunctionCall { + /** The unique id of the function call. If populated, the client to execute the + `function_call` and return the response with the matching `id`. */ + id?: string; + /** Optional. The function parameters and values in JSON object format. See [FunctionDeclaration.parameters] for parameter details. */ + args?: Record; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name]. */ + name?: string; +} + +/** Function calling config. */ +export declare interface FunctionCallingConfig { + /** Optional. Function calling mode. */ + mode?: FunctionCallingConfigMode; + /** Optional. Function names to call. Only set when the Mode is ANY. Function names should match [FunctionDeclaration.name]. With mode set to ANY, model will predict a function call from the set of function names provided. */ + allowedFunctionNames?: string[]; +} + +/** Config for the function calling config mode. */ +export declare enum FunctionCallingConfigMode { + /** + * The function calling config mode is unspecified. Should not be used. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Default model behavior, model decides to predict either function calls or natural language response. + */ + AUTO = "AUTO", + /** + * Model is constrained to always predicting function calls only. If "allowed_function_names" are set, the predicted function calls will be limited to any one of "allowed_function_names", else the predicted function calls will be any one of the provided "function_declarations". + */ + ANY = "ANY", + /** + * Model will not predict any function calls. Model behavior is same as when not passing any function declarations. + */ + NONE = "NONE", +} + +/** Defines a function that the model can generate JSON inputs for. + + The inputs are based on `OpenAPI 3.0 specifications + `_. + */ +export declare interface FunctionDeclaration { + /** Defines the function behavior. */ + behavior?: Behavior; + /** Optional. Description and purpose of the function. Model uses it to decide how and whether to call the function. */ + description?: string; + /** Required. The name of the function to call. Must start with a letter or an underscore. Must be a-z, A-Z, 0-9, or contain underscores, dots and dashes, with a maximum length of 64. */ + name?: string; + /** Optional. Describes the parameters to this function in JSON Schema Object format. Reflects the Open API 3.03 Parameter Object. string Key: the name of the parameter. Parameter names are case sensitive. Schema Value: the Schema defining the type used for the parameter. For function with no parameters, this can be left unset. Parameter names must start with a letter or an underscore and must only contain chars a-z, A-Z, 0-9, or underscores with a maximum length of 64. Example with 1 required and 1 optional parameter: type: OBJECT properties: param1: type: STRING param2: type: INTEGER required: - param1 */ + parameters?: Schema; + /** Optional. Describes the parameters to the function in JSON Schema format. The schema must describe an object where the properties are the parameters to the function. For example: ``` { "type": "object", "properties": { "name": { "type": "string" }, "age": { "type": "integer" } }, "additionalProperties": false, "required": ["name", "age"], "propertyOrdering": ["name", "age"] } ``` This field is mutually exclusive with `parameters`. */ + parametersJsonSchema?: unknown; + /** Optional. Describes the output from this function in JSON Schema format. Reflects the Open API 3.03 Response Object. The Schema defines the type used for the response value of the function. */ + response?: Schema; + /** Optional. Describes the output from this function in JSON Schema format. The value specified by the schema is the response value of the function. This field is mutually exclusive with `response`. */ + responseJsonSchema?: unknown; +} + +/** A function response. */ +export declare class FunctionResponse { + /** Signals that function call continues, and more responses will be returned, turning the function call into a generator. Is only applicable to NON_BLOCKING function calls (see FunctionDeclaration.behavior for details), ignored otherwise. If false, the default, future responses will not be considered. Is only applicable to NON_BLOCKING function calls, is ignored otherwise. If set to false, future responses will not be considered. It is allowed to return empty `response` with `will_continue=False` to signal that the function call is finished. */ + willContinue?: boolean; + /** Specifies how the response should be scheduled in the conversation. Only applicable to NON_BLOCKING function calls, is ignored otherwise. Defaults to WHEN_IDLE. */ + scheduling?: FunctionResponseScheduling; + /** Ordered `Parts` that constitute a function response. Parts may have different IANA MIME types. */ + data?: Part[]; + /** Optional. The id of the function call this response is for. Populated by the client to match the corresponding function call `id`. */ + id?: string; + /** Required. The name of the function to call. Matches [FunctionDeclaration.name] and [FunctionCall.name]. */ + name?: string; + /** Required. The function response in JSON object format. Use "output" key to specify function output and "error" key to specify error details (if any). If "output" and "error" keys are not specified, then whole "response" is treated as function output. */ + response?: Record; +} + +/** Specifies how the response should be scheduled in the conversation. */ +export declare enum FunctionResponseScheduling { + /** + * This value is unused. + */ + SCHEDULING_UNSPECIFIED = "SCHEDULING_UNSPECIFIED", + /** + * Only add the result to the conversation context, do not interrupt or trigger generation. + */ + SILENT = "SILENT", + /** + * Add the result to the conversation context, and prompt to generate output without interrupting ongoing generation. + */ + WHEN_IDLE = "WHEN_IDLE", + /** + * Add the result to the conversation context, interrupt ongoing generation and prompt to generate output. + */ + INTERRUPT = "INTERRUPT", +} + +/** Optional model configuration parameters. + + For more information, see `Content generation parameters + `_. + */ +export declare interface GenerateContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Instructions for the model to steer it toward better performance. + For example, "Answer as concisely as possible" or "Don't use technical + terms in your response". + */ + systemInstruction?: ContentUnion; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Number of response variations to return. + */ + candidateCount?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** List of strings that tells the model to stop generating text if one + of the strings is encountered in the response. + */ + stopSequences?: string[]; + /** Whether to return the log probabilities of the tokens that were + chosen by the model at each step. + */ + responseLogprobs?: boolean; + /** Number of top candidate tokens to return the log probabilities for + at each generation step. + */ + logprobs?: number; + /** Positive values penalize tokens that already appear in the + generated text, increasing the probability of generating more diverse + content. + */ + presencePenalty?: number; + /** Positive values penalize tokens that repeatedly appear in the + generated text, increasing the probability of generating more diverse + content. + */ + frequencyPenalty?: number; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** Output response mimetype of the generated candidate text. + Supported mimetype: + - `text/plain`: (default) Text output. + - `application/json`: JSON response in the candidates. + The model needs to be prompted to output the appropriate response type, + otherwise the behavior is undefined. + This is a preview feature. + */ + responseMimeType?: string; + /** The `Schema` object allows the definition of input and output data types. + These types can be objects, but also primitives and arrays. + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema). + If set, a compatible response_mime_type must also be set. + Compatible mimetypes: `application/json`: Schema for JSON response. + */ + responseSchema?: SchemaUnion; + /** Optional. Output schema of the generated response. + This is an alternative to `response_schema` that accepts [JSON + Schema](https://json-schema.org/). If set, `response_schema` must be + omitted, but `response_mime_type` is required. While the full JSON Schema + may be sent, not all features are supported. Specifically, only the + following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` + - `type` - `format` - `title` - `description` - `enum` (for strings and + numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - + `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - + `properties` - `additionalProperties` - `required` The non-standard + `propertyOrdering` property may also be set. Cyclic references are + unrolled to a limited degree and, as such, may only be used within + non-required properties. (Nullable properties are not sufficient.) If + `$ref` is set on a sub-schema, no other properties, except for than those + starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Configuration for model router requests. + */ + routingConfig?: GenerationConfigRoutingConfig; + /** Configuration for model selection. + */ + modelSelectionConfig?: ModelSelectionConfig; + /** Safety settings in the request to block unsafe content in the + response. + */ + safetySettings?: SafetySetting[]; + /** Code that enables the system to interact with external systems to + perform an action outside of the knowledge and scope of the model. + */ + tools?: ToolListUnion; + /** Associates model output to a specific function call. + */ + toolConfig?: ToolConfig; + /** Labels with user-defined metadata to break down billed charges. */ + labels?: Record; + /** Resource name of a context cache that can be used in subsequent + requests. + */ + cachedContent?: string; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. + */ + responseModalities?: string[]; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfigUnion; + /** If enabled, audio timestamp will be included in the request to the + model. + */ + audioTimestamp?: boolean; + /** The configuration for automatic function calling. + */ + automaticFunctionCalling?: AutomaticFunctionCallingConfig; + /** The thinking features configuration. + */ + thinkingConfig?: ThinkingConfig; +} + +/** Config for models.generate_content parameters. */ +export declare interface GenerateContentParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Content of the request. + */ + contents: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Response message for PredictionService.GenerateContent. */ +export declare class GenerateContentResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Response variations returned by the model. + */ + candidates?: Candidate[]; + /** Timestamp when the request is made to the server. + */ + createTime?: string; + /** Identifier for each response. + */ + responseId?: string; + /** The history of automatic function calling. + */ + automaticFunctionCallingHistory?: Content[]; + /** Output only. The model version used to generate the response. */ + modelVersion?: string; + /** Output only. Content filter results for a prompt sent in the request. Note: Sent only in the first stream chunk. Only happens when no candidates were generated due to content violations. */ + promptFeedback?: GenerateContentResponsePromptFeedback; + /** Usage metadata about the response(s). */ + usageMetadata?: GenerateContentResponseUsageMetadata; + /** + * Returns the concatenation of all text parts from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the text from the first + * one will be returned. + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + * If there are thought parts in the response, the concatenation of all text + * parts excluding the thought parts will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'Why is the sky blue?', + * }); + * + * console.debug(response.text); + * ``` + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the first candidate + * in the response. + * + * @remarks + * If there are multiple candidates in the response, the inline data from the + * first one will be returned. If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; + /** + * Returns the function calls from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the function calls from + * the first one will be returned. + * If there are no function calls in the response, undefined will be returned. + * + * @example + * ```ts + * const controlLightFunctionDeclaration: FunctionDeclaration = { + * name: 'controlLight', + * parameters: { + * type: Type.OBJECT, + * description: 'Set the brightness and color temperature of a room light.', + * properties: { + * brightness: { + * type: Type.NUMBER, + * description: + * 'Light level from 0 to 100. Zero is off and 100 is full brightness.', + * }, + * colorTemperature: { + * type: Type.STRING, + * description: + * 'Color temperature of the light fixture which can be `daylight`, `cool` or `warm`.', + * }, + * }, + * required: ['brightness', 'colorTemperature'], + * }; + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'Dim the lights so the room feels cozy and warm.', + * config: { + * tools: [{functionDeclarations: [controlLightFunctionDeclaration]}], + * toolConfig: { + * functionCallingConfig: { + * mode: FunctionCallingConfigMode.ANY, + * allowedFunctionNames: ['controlLight'], + * }, + * }, + * }, + * }); + * console.debug(JSON.stringify(response.functionCalls)); + * ``` + */ + get functionCalls(): FunctionCall[] | undefined; + /** + * Returns the first executable code from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the executable code from + * the first one will be returned. + * If there are no executable code in the response, undefined will be + * returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.executableCode); + * ``` + */ + get executableCode(): string | undefined; + /** + * Returns the first code execution result from the first candidate in the response. + * + * @remarks + * If there are multiple candidates in the response, the code execution result from + * the first one will be returned. + * If there are no code execution result in the response, undefined will be returned. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: + * 'What is the sum of the first 50 prime numbers? Generate and run code for the calculation, and make sure you get all 50.' + * config: { + * tools: [{codeExecution: {}}], + * }, + * }); + * + * console.debug(response.codeExecutionResult); + * ``` + */ + get codeExecutionResult(): string | undefined; +} + +/** Content filter results for a prompt sent in the request. */ +export declare class GenerateContentResponsePromptFeedback { + /** Output only. Blocked reason. */ + blockReason?: BlockedReason; + /** Output only. A readable block reason message. */ + blockReasonMessage?: string; + /** Output only. Safety ratings. */ + safetyRatings?: SafetyRating[]; +} + +/** Usage metadata about response(s). */ +export declare class GenerateContentResponseUsageMetadata { + /** Output only. List of modalities of the cached content in the request input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens in the cached part in the input (the cached content). */ + cachedContentTokenCount?: number; + /** Number of tokens in the response(s). */ + candidatesTokenCount?: number; + /** Output only. List of modalities that were returned in the response. */ + candidatesTokensDetails?: ModalityTokenCount[]; + /** Number of tokens in the request. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Output only. List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** Output only. Number of tokens present in thoughts output. */ + thoughtsTokenCount?: number; + /** Output only. Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Output only. List of modalities that were processed for tool-use request inputs. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Total token count for prompt, response candidates, and tool-use prompts (if present). */ + totalTokenCount?: number; + /** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** An output image. */ +export declare interface GeneratedImage { + /** The output image data. + */ + image?: Image_2; + /** Responsible AI filter reason if the image is filtered out of the + response. + */ + raiFilteredReason?: string; + /** Safety attributes of the image. Lists of RAI categories and their + scores of each content. + */ + safetyAttributes?: SafetyAttributes; + /** The rewritten prompt used for the image generation if the prompt + enhancer is enabled. + */ + enhancedPrompt?: string; +} + +/** A generated video. */ +export declare interface GeneratedVideo { + /** The output video */ + video?: Video; +} + +/** The config for generating an images. */ +export declare interface GenerateImagesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Cloud Storage URI used to store the generated images. + */ + outputGcsUri?: string; + /** Description of what to discourage in the generated images. + */ + negativePrompt?: string; + /** Number of images to generate. + */ + numberOfImages?: number; + /** Aspect ratio of the generated images. Supported values are + "1:1", "3:4", "4:3", "9:16", and "16:9". + */ + aspectRatio?: string; + /** Controls how much the model adheres to the text prompt. Large + values increase output and prompt alignment, but may compromise image + quality. + */ + guidanceScale?: number; + /** Random seed for image generation. This is not available when + ``add_watermark`` is set to true. + */ + seed?: number; + /** Filter level for safety filtering. + */ + safetyFilterLevel?: SafetyFilterLevel; + /** Allows generation of people by the model. + */ + personGeneration?: PersonGeneration; + /** Whether to report the safety scores of each generated image and + the positive prompt in the response. + */ + includeSafetyAttributes?: boolean; + /** Whether to include the Responsible AI filter reason if the image + is filtered out of the response. + */ + includeRaiReason?: boolean; + /** Language of the text in the prompt. + */ + language?: ImagePromptLanguage; + /** MIME type of the generated image. + */ + outputMimeType?: string; + /** Compression quality of the generated image (for ``image/jpeg`` + only). + */ + outputCompressionQuality?: number; + /** Whether to add a watermark to the generated images. + */ + addWatermark?: boolean; + /** The size of the largest dimension of the generated image. + Supported sizes are 1K and 2K (not supported for Imagen 3 models). + */ + imageSize?: string; + /** Whether to use the prompt rewriting logic. + */ + enhancePrompt?: boolean; +} + +/** The parameters for generating images. */ +export declare interface GenerateImagesParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** Text prompt that typically describes the images to output. + */ + prompt: string; + /** Configuration for generating images. + */ + config?: GenerateImagesConfig; +} + +/** The output images response. */ +export declare class GenerateImagesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** List of generated images. + */ + generatedImages?: GeneratedImage[]; + /** Safety attributes of the positive prompt. Only populated if + ``include_safety_attributes`` is set to True. + */ + positivePromptSafetyAttributes?: SafetyAttributes; +} + +/** Configuration for generating videos. */ +export declare interface GenerateVideosConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Number of output videos. */ + numberOfVideos?: number; + /** The gcs bucket where to save the generated videos. */ + outputGcsUri?: string; + /** Frames per second for video generation. */ + fps?: number; + /** Duration of the clip for video generation in seconds. */ + durationSeconds?: number; + /** The RNG seed. If RNG seed is exactly same for each request with unchanged inputs, the prediction results will be consistent. Otherwise, a random RNG seed will be used each time to produce a different result. */ + seed?: number; + /** The aspect ratio for the generated video. 16:9 (landscape) and 9:16 (portrait) are supported. */ + aspectRatio?: string; + /** The resolution for the generated video. 720p and 1080p are supported. */ + resolution?: string; + /** Whether allow to generate person videos, and restrict to specific ages. Supported values are: dont_allow, allow_adult. */ + personGeneration?: string; + /** The pubsub topic where to publish the video generation progress. */ + pubsubTopic?: string; + /** Optional field in addition to the text content. Negative prompts can be explicitly stated here to help generate the video. */ + negativePrompt?: string; + /** Whether to use the prompt rewriting logic. */ + enhancePrompt?: boolean; + /** Whether to generate audio along with the video. */ + generateAudio?: boolean; + /** Image to use as the last frame of generated videos. Only supported for image to video use cases. */ + lastFrame?: Image_2; + /** Compression quality of the generated videos. */ + compressionQuality?: VideoCompressionQuality; +} + +/** A video generation long-running operation. */ +export declare class GenerateVideosOperation + implements Operation +{ + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: GenerateVideosResponse; + /** The full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Class that represents the parameters for generating videos. */ +export declare interface GenerateVideosParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** The text prompt for generating the videos. Optional for image to video use cases. */ + prompt?: string; + /** The input image for generating the videos. + Optional if prompt or video is provided. */ + image?: Image_2; + /** The input video for video extension use cases. + Optional if prompt or image is provided. */ + video?: Video; + /** Configuration for generating videos. */ + config?: GenerateVideosConfig; +} + +/** Response with generated videos. */ +export declare class GenerateVideosResponse { + /** List of the generated videos */ + generatedVideos?: GeneratedVideo[]; + /** Returns if any videos were filtered due to RAI policies. */ + raiMediaFilteredCount?: number; + /** Returns rai failure reasons if any. */ + raiMediaFilteredReasons?: string[]; +} + +/** Generation config. */ +export declare interface GenerationConfig { + /** Optional. Config for model selection. */ + modelSelectionConfig?: ModelSelectionConfig; + /** Optional. If enabled, audio timestamp will be included in the request to the model. */ + audioTimestamp?: boolean; + /** Optional. Number of candidates to generate. */ + candidateCount?: number; + /** Optional. If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** Optional. Frequency penalties. */ + frequencyPenalty?: number; + /** Optional. Logit probabilities. */ + logprobs?: number; + /** Optional. The maximum number of output tokens to generate per message. */ + maxOutputTokens?: number; + /** Optional. If specified, the media resolution specified will be used. */ + mediaResolution?: MediaResolution; + /** Optional. Positive penalties. */ + presencePenalty?: number; + /** Optional. Output schema of the generated response. This is an alternative to `response_schema` that accepts [JSON Schema](https://json-schema.org/). If set, `response_schema` must be omitted, but `response_mime_type` is required. While the full JSON Schema may be sent, not all features are supported. Specifically, only the following properties are supported: - `$id` - `$defs` - `$ref` - `$anchor` - `type` - `format` - `title` - `description` - `enum` (for strings and numbers) - `items` - `prefixItems` - `minItems` - `maxItems` - `minimum` - `maximum` - `anyOf` - `oneOf` (interpreted the same as `anyOf`) - `properties` - `additionalProperties` - `required` The non-standard `propertyOrdering` property may also be set. Cyclic references are unrolled to a limited degree and, as such, may only be used within non-required properties. (Nullable properties are not sufficient.) If `$ref` is set on a sub-schema, no other properties, except for than those starting as a `$`, may be set. */ + responseJsonSchema?: unknown; + /** Optional. If true, export the logprobs results in response. */ + responseLogprobs?: boolean; + /** Optional. Output response mimetype of the generated candidate text. Supported mimetype: - `text/plain`: (default) Text output. - `application/json`: JSON response in the candidates. The model needs to be prompted to output the appropriate response type, otherwise the behavior is undefined. This is a preview feature. */ + responseMimeType?: string; + /** Optional. The modalities of the response. */ + responseModalities?: Modality[]; + /** Optional. The `Schema` object allows the definition of input and output data types. These types can be objects, but also primitives and arrays. Represents a select subset of an [OpenAPI 3.0 schema object](https://spec.openapis.org/oas/v3.0.3#schema). If set, a compatible response_mime_type must also be set. Compatible mimetypes: `application/json`: Schema for JSON response. */ + responseSchema?: Schema; + /** Optional. Routing configuration. */ + routingConfig?: GenerationConfigRoutingConfig; + /** Optional. Seed. */ + seed?: number; + /** Optional. The speech generation config. */ + speechConfig?: SpeechConfig; + /** Optional. Stop sequences. */ + stopSequences?: string[]; + /** Optional. Controls the randomness of predictions. */ + temperature?: number; + /** Optional. Config for thinking features. An error will be returned if this field is set for models that don't support thinking. */ + thinkingConfig?: GenerationConfigThinkingConfig; + /** Optional. If specified, top-k sampling will be used. */ + topK?: number; + /** Optional. If specified, nucleus sampling will be used. */ + topP?: number; +} + +/** The configuration for routing the request to a specific model. */ +export declare interface GenerationConfigRoutingConfig { + /** Automated routing. */ + autoMode?: GenerationConfigRoutingConfigAutoRoutingMode; + /** Manual routing. */ + manualMode?: GenerationConfigRoutingConfigManualRoutingMode; +} + +/** When automated routing is specified, the routing will be determined by the pretrained routing model and customer provided model routing preference. */ +export declare interface GenerationConfigRoutingConfigAutoRoutingMode { + /** The model routing preference. */ + modelRoutingPreference?: + | "UNKNOWN" + | "PRIORITIZE_QUALITY" + | "BALANCED" + | "PRIORITIZE_COST"; +} + +/** When manual routing is set, the specified model will be used directly. */ +export declare interface GenerationConfigRoutingConfigManualRoutingMode { + /** The model name to use. Only the public LLM models are accepted. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for thinking features. */ +export declare interface GenerationConfigThinkingConfig { + /** Optional. Indicates whether to include thoughts in the response. If true, thoughts are returned only when available. */ + includeThoughts?: boolean; + /** Optional. Indicates the thinking budget in tokens. This is only applied when enable_thinking is true. */ + thinkingBudget?: number; +} + +/** Optional parameters. */ +export declare interface GetBatchJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Config for batches.get parameters. */ +export declare interface GetBatchJobParameters { + /** A fully-qualified BatchJob resource name or ID. + Example: "projects/.../locations/.../batchPredictionJobs/456" + or "456" when project and location are initialized in the client. + */ + name: string; + /** Optional parameters for the request. */ + config?: GetBatchJobConfig; +} + +/** Optional parameters for caches.get method. */ +export declare interface GetCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for caches.get method. */ +export declare interface GetCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Optional parameters for the request. + */ + config?: GetCachedContentConfig; +} + +/** Used to override the default configuration. */ +export declare interface GetFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Generates the parameters for the get method. */ +export declare interface GetFileParameters { + /** The name identifier for the file to retrieve. */ + name: string; + /** Used to override the default configuration. */ + config?: GetFileConfig; +} + +/** Optional parameters for models.get method. */ +export declare interface GetModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +export declare interface GetModelParameters { + model: string; + /** Optional parameters for the request. */ + config?: GetModelConfig; +} + +export declare interface GetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the GET method. */ +export declare interface GetOperationParameters { + /** The server-assigned name for the operation. */ + operationName: string; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +/** Optional parameters for tunings.get method. */ +export declare interface GetTuningJobConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for the get method. */ +export declare interface GetTuningJobParameters { + name: string; + /** Optional parameters for the request. */ + config?: GetTuningJobConfig; +} + +/** + * The Google GenAI SDK. + * + * @remarks + * Provides access to the GenAI features through either the {@link + * https://cloud.google.com/vertex-ai/docs/reference/rest | Gemini API} or + * the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI + * API}. + * + * The {@link GoogleGenAIOptions.vertexai} value determines which of the API + * services to use. + * + * When using the Gemini API, a {@link GoogleGenAIOptions.apiKey} must also be + * set. When using Vertex AI, currently only {@link GoogleGenAIOptions.apiKey} + * is supported via Express mode. {@link GoogleGenAIOptions.project} and {@link + * GoogleGenAIOptions.location} should not be set. + * + * @example + * Initializing the SDK for using the Gemini API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + * + * @example + * Initializing the SDK for using the Vertex AI API: + * ```ts + * import {GoogleGenAI} from '@google/genai'; + * const ai = new GoogleGenAI({ + * vertexai: true, + * project: 'PROJECT_ID', + * location: 'PROJECT_LOCATION' + * }); + * ``` + * + */ +export declare class GoogleGenAI { + protected readonly apiClient: ApiClient; + private readonly apiKey?; + readonly vertexai: boolean; + private readonly apiVersion?; + readonly models: Models; + readonly live: Live; + readonly batches: Batches; + readonly chats: Chats; + readonly caches: Caches; + readonly files: Files; + readonly operations: Operations; + readonly authTokens: Tokens; + readonly tunings: Tunings; + constructor(options: GoogleGenAIOptions); +} + +/** + * Google Gen AI SDK's configuration options. + * + * See {@link GoogleGenAI} for usage samples. + */ +export declare interface GoogleGenAIOptions { + /** + * Optional. Determines whether to use the Vertex AI or the Gemini API. + * + * @remarks + * When true, the {@link https://cloud.google.com/vertex-ai/docs/reference/rest | Vertex AI API} will used. + * When false, the {@link https://ai.google.dev/api | Gemini API} will be used. + * + * If unset, default SDK behavior is to use the Gemini API service. + */ + vertexai?: boolean; + /** + * Optional. The Google Cloud project ID for Vertex AI clients. + * + * Find your project ID: https://cloud.google.com/resource-manager/docs/creating-managing-projects#identifying_projects + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + */ + project?: string; + /** + * Optional. The Google Cloud project {@link https://cloud.google.com/vertex-ai/generative-ai/docs/learn/locations | location} for Vertex AI clients. + * + * @remarks + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + location?: string; + /** + * The API Key, required for Gemini API clients. + * + * @remarks + * Required on browser runtimes. + */ + apiKey?: string; + /** + * Optional. The API version to use. + * + * @remarks + * If unset, the default API version will be used. + */ + apiVersion?: string; + /** + * Optional. Authentication options defined by the by google-auth-library for Vertex AI clients. + * + * @remarks + * @see {@link https://github.com/googleapis/google-auth-library-nodejs/blob/v9.15.0/src/auth/googleauth.ts | GoogleAuthOptions interface in google-auth-library-nodejs}. + * + * Only supported on Node runtimes, ignored on browser runtimes. + * + */ + googleAuthOptions?: GoogleAuthOptions; + /** + * Optional. A set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; +} + +/** Tool to support Google Maps in Model. */ +export declare interface GoogleMaps { + /** Optional. Auth config for the Google Maps tool. */ + authConfig?: AuthConfig; +} + +/** The `Status` type defines a logical error model that is suitable for different programming environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). Each `Status` message contains three pieces of data: error code, error message, and error details. You can find out more about this error model and how to work with it in the [API Design Guide](https://cloud.google.com/apis/design/errors). */ +export declare interface GoogleRpcStatus { + /** The status code, which should be an enum value of google.rpc.Code. */ + code?: number; + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: Record[]; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the google.rpc.Status.details field, or localized by the client. */ + message?: string; +} + +/** Tool to support Google Search in Model. Powered by Google. */ +export declare interface GoogleSearch { + /** Optional. Filter search results to a specific time range. + If customers set a start time, they must set an end time (and vice versa). + */ + timeRangeFilter?: Interval; +} + +/** Tool to retrieve public web data for grounding, powered by Google. */ +export declare interface GoogleSearchRetrieval { + /** Specifies the dynamic retrieval configuration for the given source. */ + dynamicRetrievalConfig?: DynamicRetrievalConfig; +} + +/** Represents a whole or partial calendar date, such as a birthday. The time of day and time zone are either specified elsewhere or are insignificant. The date is relative to the Gregorian Calendar. This can represent one of the following: * A full date, with non-zero year, month, and day values. * A month and day, with a zero year (for example, an anniversary). * A year on its own, with a zero month and a zero day. * A year and month, with a zero day (for example, a credit card expiration date). Related types: * google.type.TimeOfDay * google.type.DateTime * google.protobuf.Timestamp */ +export declare interface GoogleTypeDate { + /** Day of a month. Must be from 1 to 31 and valid for the year and month, or 0 to specify a year by itself or a year and month where the day isn't significant. */ + day?: number; + /** Month of a year. Must be from 1 to 12, or 0 to specify a year without a month and day. */ + month?: number; + /** Year of the date. Must be from 1 to 9999, or 0 to specify a date without a year. */ + year?: number; +} + +/** Grounding chunk. */ +export declare interface GroundingChunk { + /** Grounding chunk from context retrieved by the retrieval tools. */ + retrievedContext?: GroundingChunkRetrievedContext; + /** Grounding chunk from the web. */ + web?: GroundingChunkWeb; +} + +/** Chunk from context retrieved by the retrieval tools. */ +export declare interface GroundingChunkRetrievedContext { + /** Additional context for the RAG retrieval result. This is only populated when using the RAG retrieval tool. */ + ragChunk?: RagChunk; + /** Text of the attribution. */ + text?: string; + /** Title of the attribution. */ + title?: string; + /** URI reference of the attribution. */ + uri?: string; +} + +/** Chunk from the web. */ +export declare interface GroundingChunkWeb { + /** Domain of the (original) URI. */ + domain?: string; + /** Title of the chunk. */ + title?: string; + /** URI reference of the chunk. */ + uri?: string; +} + +/** Metadata returned to client when grounding is enabled. */ +export declare interface GroundingMetadata { + /** List of supporting references retrieved from specified grounding source. */ + groundingChunks?: GroundingChunk[]; + /** Optional. List of grounding support. */ + groundingSupports?: GroundingSupport[]; + /** Optional. Output only. Retrieval metadata. */ + retrievalMetadata?: RetrievalMetadata; + /** Optional. Queries executed by the retrieval tools. */ + retrievalQueries?: string[]; + /** Optional. Google search entry for the following-up web searches. */ + searchEntryPoint?: SearchEntryPoint; + /** Optional. Web search queries for the following-up web search. */ + webSearchQueries?: string[]; +} + +/** Grounding support. */ +export declare interface GroundingSupport { + /** Confidence score of the support references. Ranges from 0 to 1. 1 is the most confident. For Gemini 2.0 and before, this list must have the same size as the grounding_chunk_indices. For Gemini 2.5 and after, this list will be empty and should be ignored. */ + confidenceScores?: number[]; + /** A list of indices (into 'grounding_chunk') specifying the citations associated with the claim. For instance [1,3,4] means that grounding_chunk[1], grounding_chunk[3], grounding_chunk[4] are the retrieved content attributed to the claim. */ + groundingChunkIndices?: number[]; + /** Segment of the content this support belongs to. */ + segment?: Segment; +} + +/** Optional. Specify if the threshold is used for probability or severity score. If not specified, the threshold is used for probability score. */ +export declare enum HarmBlockMethod { + /** + * The harm block method is unspecified. + */ + HARM_BLOCK_METHOD_UNSPECIFIED = "HARM_BLOCK_METHOD_UNSPECIFIED", + /** + * The harm block method uses both probability and severity scores. + */ + SEVERITY = "SEVERITY", + /** + * The harm block method uses the probability score. + */ + PROBABILITY = "PROBABILITY", +} + +/** Required. The harm block threshold. */ +export declare enum HarmBlockThreshold { + /** + * Unspecified harm block threshold. + */ + HARM_BLOCK_THRESHOLD_UNSPECIFIED = "HARM_BLOCK_THRESHOLD_UNSPECIFIED", + /** + * Block low threshold and above (i.e. block more). + */ + BLOCK_LOW_AND_ABOVE = "BLOCK_LOW_AND_ABOVE", + /** + * Block medium threshold and above. + */ + BLOCK_MEDIUM_AND_ABOVE = "BLOCK_MEDIUM_AND_ABOVE", + /** + * Block only high threshold (i.e. block less). + */ + BLOCK_ONLY_HIGH = "BLOCK_ONLY_HIGH", + /** + * Block none. + */ + BLOCK_NONE = "BLOCK_NONE", + /** + * Turn off the safety filter. + */ + OFF = "OFF", +} + +/** Required. Harm category. */ +export declare enum HarmCategory { + /** + * The harm category is unspecified. + */ + HARM_CATEGORY_UNSPECIFIED = "HARM_CATEGORY_UNSPECIFIED", + /** + * The harm category is hate speech. + */ + HARM_CATEGORY_HATE_SPEECH = "HARM_CATEGORY_HATE_SPEECH", + /** + * The harm category is dangerous content. + */ + HARM_CATEGORY_DANGEROUS_CONTENT = "HARM_CATEGORY_DANGEROUS_CONTENT", + /** + * The harm category is harassment. + */ + HARM_CATEGORY_HARASSMENT = "HARM_CATEGORY_HARASSMENT", + /** + * The harm category is sexually explicit content. + */ + HARM_CATEGORY_SEXUALLY_EXPLICIT = "HARM_CATEGORY_SEXUALLY_EXPLICIT", + /** + * Deprecated: Election filter is not longer supported. The harm category is civic integrity. + */ + HARM_CATEGORY_CIVIC_INTEGRITY = "HARM_CATEGORY_CIVIC_INTEGRITY", + /** + * The harm category is image hate. + */ + HARM_CATEGORY_IMAGE_HATE = "HARM_CATEGORY_IMAGE_HATE", + /** + * The harm category is image dangerous content. + */ + HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT = "HARM_CATEGORY_IMAGE_DANGEROUS_CONTENT", + /** + * The harm category is image harassment. + */ + HARM_CATEGORY_IMAGE_HARASSMENT = "HARM_CATEGORY_IMAGE_HARASSMENT", + /** + * The harm category is image sexually explicit content. + */ + HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT = "HARM_CATEGORY_IMAGE_SEXUALLY_EXPLICIT", +} + +/** Output only. Harm probability levels in the content. */ +export declare enum HarmProbability { + /** + * Harm probability unspecified. + */ + HARM_PROBABILITY_UNSPECIFIED = "HARM_PROBABILITY_UNSPECIFIED", + /** + * Negligible level of harm. + */ + NEGLIGIBLE = "NEGLIGIBLE", + /** + * Low level of harm. + */ + LOW = "LOW", + /** + * Medium level of harm. + */ + MEDIUM = "MEDIUM", + /** + * High level of harm. + */ + HIGH = "HIGH", +} + +/** Output only. Harm severity levels in the content. */ +export declare enum HarmSeverity { + /** + * Harm severity unspecified. + */ + HARM_SEVERITY_UNSPECIFIED = "HARM_SEVERITY_UNSPECIFIED", + /** + * Negligible level of harm severity. + */ + HARM_SEVERITY_NEGLIGIBLE = "HARM_SEVERITY_NEGLIGIBLE", + /** + * Low level of harm severity. + */ + HARM_SEVERITY_LOW = "HARM_SEVERITY_LOW", + /** + * Medium level of harm severity. + */ + HARM_SEVERITY_MEDIUM = "HARM_SEVERITY_MEDIUM", + /** + * High level of harm severity. + */ + HARM_SEVERITY_HIGH = "HARM_SEVERITY_HIGH", +} + +/** HTTP options to be used in each of the requests. */ +export declare interface HttpOptions { + /** The base URL for the AI platform service endpoint. */ + baseUrl?: string; + /** Specifies the version of the API to use. */ + apiVersion?: string; + /** Additional HTTP headers to be sent with the request. */ + headers?: Record; + /** Timeout for the request in milliseconds. */ + timeout?: number; + /** Extra parameters to add to the request body. + The structure must match the backend API's request structure. + - VertexAI backend API docs: https://cloud.google.com/vertex-ai/docs/reference/rest + - GeminiAPI backend API docs: https://ai.google.dev/api/rest */ + extraBody?: Record; +} + +/** + * Represents the necessary information to send a request to an API endpoint. + * This interface defines the structure for constructing and executing HTTP + * requests. + */ +declare interface HttpRequest { + /** + * URL path from the modules, this path is appended to the base API URL to + * form the complete request URL. + * + * If you wish to set full URL, use httpOptions.baseUrl instead. Example to + * set full URL in the request: + * + * const request: HttpRequest = { + * path: '', + * httpOptions: { + * baseUrl: 'https://', + * apiVersion: '', + * }, + * httpMethod: 'GET', + * }; + * + * The result URL will be: https:// + * + */ + path: string; + /** + * Optional query parameters to be appended to the request URL. + */ + queryParams?: Record; + /** + * Optional request body in json string or Blob format, GET request doesn't + * need a request body. + */ + body?: string | Blob; + /** + * The HTTP method to be used for the request. + */ + httpMethod: "GET" | "POST" | "PATCH" | "DELETE"; + /** + * Optional set of customizable configuration for HTTP requests. + */ + httpOptions?: HttpOptions; + /** + * Optional abort signal which can be used to cancel the request. + */ + abortSignal?: AbortSignal; +} + +/** A wrapper class for the http response. */ +export declare class HttpResponse { + /** Used to retain the processed HTTP headers in the response. */ + headers?: Record; + /** + * The original http response. + */ + responseInternal: Response; + constructor(response: Response); + json(): Promise; +} + +/** An image. */ +declare interface Image_2 { + /** The Cloud Storage URI of the image. ``Image`` can contain a value + for this field or the ``image_bytes`` field but not both. + */ + gcsUri?: string; + /** The image bytes data. ``Image`` can contain a value for this field + or the ``gcs_uri`` field but not both. + + * @remarks Encoded as base64 string. */ + imageBytes?: string; + /** The MIME type of the image. */ + mimeType?: string; +} +export { Image_2 as Image }; + +/** Enum that specifies the language of the text in the prompt. */ +export declare enum ImagePromptLanguage { + /** + * Auto-detect the language. + */ + auto = "auto", + /** + * English + */ + en = "en", + /** + * Japanese + */ + ja = "ja", + /** + * Korean + */ + ko = "ko", + /** + * Hindi + */ + hi = "hi", + /** + * Chinese + */ + zh = "zh", + /** + * Portuguese + */ + pt = "pt", + /** + * Spanish + */ + es = "es", +} + +/** Config for inlined request. */ +export declare interface InlinedRequest { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model?: string; + /** Content of the request. + */ + contents?: ContentListUnion; + /** Configuration that contains optional model parameters. + */ + config?: GenerateContentConfig; +} + +/** Config for `inlined_responses` parameter. */ +export declare class InlinedResponse { + /** The response to the request. + */ + response?: GenerateContentResponse; + /** The error encountered while processing the request. + */ + error?: JobError; +} + +/** Represents a time interval, encoded as a start time (inclusive) and an end time (exclusive). + + The start time must be less than or equal to the end time. + When the start equals the end time, the interval is an empty interval. + (matches no time) + When both start and end are unspecified, the interval matches any time. + */ +export declare interface Interval { + /** The start time of the interval. */ + startTime?: string; + /** The end time of the interval. */ + endTime?: string; +} + +/** Job error. */ +export declare interface JobError { + /** A list of messages that carry the error details. There is a common set of message types for APIs to use. */ + details?: string[]; + /** The status code. */ + code?: number; + /** A developer-facing error message, which should be in English. Any user-facing error message should be localized and sent in the `details` field. */ + message?: string; +} + +/** Job state. */ +export declare enum JobState { + /** + * The job state is unspecified. + */ + JOB_STATE_UNSPECIFIED = "JOB_STATE_UNSPECIFIED", + /** + * The job has been just created or resumed and processing has not yet begun. + */ + JOB_STATE_QUEUED = "JOB_STATE_QUEUED", + /** + * The service is preparing to run the job. + */ + JOB_STATE_PENDING = "JOB_STATE_PENDING", + /** + * The job is in progress. + */ + JOB_STATE_RUNNING = "JOB_STATE_RUNNING", + /** + * The job completed successfully. + */ + JOB_STATE_SUCCEEDED = "JOB_STATE_SUCCEEDED", + /** + * The job failed. + */ + JOB_STATE_FAILED = "JOB_STATE_FAILED", + /** + * The job is being cancelled. From this state the job may only go to either `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. + */ + JOB_STATE_CANCELLING = "JOB_STATE_CANCELLING", + /** + * The job has been cancelled. + */ + JOB_STATE_CANCELLED = "JOB_STATE_CANCELLED", + /** + * The job has been stopped, and can be resumed. + */ + JOB_STATE_PAUSED = "JOB_STATE_PAUSED", + /** + * The job has expired. + */ + JOB_STATE_EXPIRED = "JOB_STATE_EXPIRED", + /** + * The job is being updated. Only jobs in the `JOB_STATE_RUNNING` state can be updated. After updating, the job goes back to the `JOB_STATE_RUNNING` state. + */ + JOB_STATE_UPDATING = "JOB_STATE_UPDATING", + /** + * The job is partially succeeded, some results may be missing due to errors. + */ + JOB_STATE_PARTIALLY_SUCCEEDED = "JOB_STATE_PARTIALLY_SUCCEEDED", +} + +/** Required. Programming language of the `code`. */ +export declare enum Language { + /** + * Unspecified language. This value should not be used. + */ + LANGUAGE_UNSPECIFIED = "LANGUAGE_UNSPECIFIED", + /** + * Python >= 3.10, with numpy and simpy available. + */ + PYTHON = "PYTHON", +} + +/** An object that represents a latitude/longitude pair. + + This is expressed as a pair of doubles to represent degrees latitude and + degrees longitude. Unless specified otherwise, this object must conform to the + + WGS84 standard. Values must be within normalized ranges. + */ +export declare interface LatLng { + /** The latitude in degrees. It must be in the range [-90.0, +90.0]. */ + latitude?: number; + /** The longitude in degrees. It must be in the range [-180.0, +180.0] */ + longitude?: number; +} + +/** Config for optional parameters. */ +export declare interface ListBatchJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Config for batches.list parameters. */ +export declare interface ListBatchJobsParameters { + config?: ListBatchJobsConfig; +} + +/** Config for batches.list return value. */ +export declare class ListBatchJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + batchJobs?: BatchJob[]; +} + +/** Config for caches.list method. */ +export declare interface ListCachedContentsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Parameters for caches.list method. */ +export declare interface ListCachedContentsParameters { + /** Configuration that contains optional parameters. + */ + config?: ListCachedContentsConfig; +} + +export declare class ListCachedContentsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + /** List of cached contents. + */ + cachedContents?: CachedContent[]; +} + +/** Used to override the default configuration. */ +export declare interface ListFilesConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; +} + +/** Generates the parameters for the list method. */ +export declare interface ListFilesParameters { + /** Used to override the default configuration. */ + config?: ListFilesConfig; +} + +/** Response for the list files method. */ +export declare class ListFilesResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve next page of results. */ + nextPageToken?: string; + /** The list of files. */ + files?: File_2[]; +} + +export declare interface ListModelsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; + /** Set true to list base models, false to list tuned models. */ + queryBase?: boolean; +} + +export declare interface ListModelsParameters { + config?: ListModelsConfig; +} + +export declare class ListModelsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + nextPageToken?: string; + models?: Model[]; +} + +/** Configuration for the list tuning jobs method. */ +export declare interface ListTuningJobsConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + filter?: string; +} + +/** Parameters for the list tuning jobs method. */ +export declare interface ListTuningJobsParameters { + config?: ListTuningJobsConfig; +} + +/** Response for the list tuning jobs method. */ +export declare class ListTuningJobsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** A token to retrieve the next page of results. Pass to ListTuningJobsRequest.page_token to obtain that page. */ + nextPageToken?: string; + /** List of TuningJobs in the requested page. */ + tuningJobs?: TuningJob[]; +} + +/** + Live class encapsulates the configuration for live interaction with the + Generative Language API. It embeds ApiClient for general API settings. + + @experimental + */ +export declare class Live { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + readonly music: LiveMusic; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model with the given + configuration and returns a Session object representing that connection. + + @experimental Built-in MCP support is an experimental feature, may change in + future versions. + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + }, + callbacks: { + onopen: () => { + console.log('Connected to the socket.'); + }, + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveConnectParameters): Promise; + private isCallableTool; +} + +/** Callbacks for the live API. */ +export declare interface LiveCallbacks { + /** + * Called when the websocket connection is established. + */ + onopen?: (() => void) | null; + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** Incremental update of the current conversation delivered from the client. + + All the content here will unconditionally be appended to the conversation + history and used as part of the prompt to the model to generate content. + + A message here will interrupt any current model generation. + */ +export declare interface LiveClientContent { + /** The content appended to the current conversation with the model. + + For single-turn queries, this is a single instance. For multi-turn + queries, this is a repeated field that contains conversation history and + latest request. + */ + turns?: Content[]; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Messages sent by the client in the API call. */ +export declare interface LiveClientMessage { + /** Message to be sent by the system when connecting to the API. SDK users should not send this message. */ + setup?: LiveClientSetup; + /** Incremental update of the current conversation delivered from the client. */ + clientContent?: LiveClientContent; + /** User input that is sent in real time. */ + realtimeInput?: LiveClientRealtimeInput; + /** Response to a `ToolCallMessage` received from the server. */ + toolResponse?: LiveClientToolResponse; +} + +/** User input that is sent in real time. + + This is different from `LiveClientContent` in a few ways: + + - Can be sent continuously without interruption to model generation. + - If there is a need to mix data interleaved across the + `LiveClientContent` and the `LiveClientRealtimeInput`, server attempts to + optimize for best response, but there are no guarantees. + - End of turn is not explicitly specified, but is rather derived from user + activity (for example, end of speech). + - Even before the end of turn, the data is processed incrementally + to optimize for a fast start of the response from the model. + - Is always assumed to be the user's input (cannot be used to populate + conversation history). + */ +export declare interface LiveClientRealtimeInput { + /** Inlined bytes data for media input. */ + mediaChunks?: Blob_2[]; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: Blob_2; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Message contains configuration that will apply for the duration of the streaming session. */ +export declare interface LiveClientSetup { + /** + The fully qualified name of the publisher model or tuned model endpoint to + use. + */ + model?: string; + /** The generation configuration for the session. + Note: only a subset of fields are supported. + */ + generationConfig?: GenerationConfig; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures session resumption mechanism. + + If included server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Client generated response to a `ToolCall` received from the server. + + Individual `FunctionResponse` objects are matched to the respective + `FunctionCall` objects by the `id` field. + + Note that in the unary and server-streaming GenerateContent APIs function + calling happens by exchanging the `Content` parts, while in the bidi + GenerateContent APIs function calling happens over this dedicated set of + messages. + */ +export declare class LiveClientToolResponse { + /** The response to the function calls. */ + functionResponses?: FunctionResponse[]; +} + +/** Session config for the API connection. */ +export declare interface LiveConnectConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The generation configuration for the session. */ + generationConfig?: GenerationConfig; + /** The requested modalities of the response. Represents the set of + modalities that the model can return. Defaults to AUDIO if not specified. + */ + responseModalities?: Modality[]; + /** Value that controls the degree of randomness in token selection. + Lower temperatures are good for prompts that require a less open-ended or + creative response, while higher temperatures can lead to more diverse or + creative results. + */ + temperature?: number; + /** Tokens are selected from the most to least probable until the sum + of their probabilities equals this value. Use a lower value for less + random responses and a higher value for more random responses. + */ + topP?: number; + /** For each token selection step, the ``top_k`` tokens with the + highest probabilities are sampled. Then tokens are further filtered based + on ``top_p`` with the final token selected using temperature sampling. Use + a lower number for less random responses and a higher number for more + random responses. + */ + topK?: number; + /** Maximum number of tokens that can be generated in the response. + */ + maxOutputTokens?: number; + /** If specified, the media resolution specified will be used. + */ + mediaResolution?: MediaResolution; + /** When ``seed`` is fixed to a specific number, the model makes a best + effort to provide the same response for repeated requests. By default, a + random number is used. + */ + seed?: number; + /** The speech generation configuration. + */ + speechConfig?: SpeechConfig; + /** If enabled, the model will detect emotions and adapt its responses accordingly. */ + enableAffectiveDialog?: boolean; + /** The user provided system instructions for the model. + Note: only text should be used in parts and content in each part will be + in a separate paragraph. */ + systemInstruction?: ContentUnion; + /** A list of `Tools` the model may use to generate the next response. + + A `Tool` is a piece of code that enables the system to interact with + external systems to perform an action, or set of actions, outside of + knowledge and scope of the model. */ + tools?: ToolListUnion; + /** Configures session resumption mechanism. + + If included the server will send SessionResumptionUpdate messages. */ + sessionResumption?: SessionResumptionConfig; + /** The transcription of the input aligns with the input audio language. + */ + inputAudioTranscription?: AudioTranscriptionConfig; + /** The transcription of the output aligns with the language code + specified for the output audio. + */ + outputAudioTranscription?: AudioTranscriptionConfig; + /** Configures the realtime input behavior in BidiGenerateContent. */ + realtimeInputConfig?: RealtimeInputConfig; + /** Configures context window compression mechanism. + + If included, server will compress context window to fit into given length. */ + contextWindowCompression?: ContextWindowCompressionConfig; + /** Configures the proactivity of the model. This allows the model to respond proactively to + the input and to ignore irrelevant input. */ + proactivity?: ProactivityConfig; +} + +/** Config for LiveConnectConstraints for Auth Token creation. */ +export declare interface LiveConnectConstraints { + /** ID of the model to configure in the ephemeral token for Live API. + For a list of models, see `Gemini models + `. */ + model?: string; + /** Configuration specific to Live API connections created using this token. */ + config?: LiveConnectConfig; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveConnectParameters { + /** ID of the model to use. For a list of models, see `Google models + `_. */ + model: string; + /** callbacks */ + callbacks: LiveCallbacks; + /** Optional configuration parameters for the request. + */ + config?: LiveConnectConfig; +} + +/** + LiveMusic class encapsulates the configuration for live music + generation via Lyria Live models. + + @experimental + */ +declare class LiveMusic { + private readonly apiClient; + private readonly auth; + private readonly webSocketFactory; + constructor( + apiClient: ApiClient, + auth: Auth, + webSocketFactory: WebSocketFactory, + ); + /** + Establishes a connection to the specified model and returns a + LiveMusicSession object representing that connection. + + @experimental + + @remarks + + @param params - The parameters for establishing a connection to the model. + @return A live session. + + @example + ```ts + let model = 'models/lyria-realtime-exp'; + const session = await ai.live.music.connect({ + model: model, + callbacks: { + onmessage: (e: MessageEvent) => { + console.log('Received message from the server: %s\n', debug(e.data)); + }, + onerror: (e: ErrorEvent) => { + console.log('Error occurred: %s\n', debug(e.error)); + }, + onclose: (e: CloseEvent) => { + console.log('Connection closed.'); + }, + }, + }); + ``` + */ + connect(params: types.LiveMusicConnectParameters): Promise; +} + +/** Callbacks for the realtime music API. */ +export declare interface LiveMusicCallbacks { + /** + * Called when a message is received from the server. + */ + onmessage: (e: LiveMusicServerMessage) => void; + /** + * Called when an error occurs. + */ + onerror?: ((e: ErrorEvent) => void) | null; + /** + * Called when the websocket connection is closed. + */ + onclose?: ((e: CloseEvent) => void) | null; +} + +/** User input to start or steer the music. */ +export declare interface LiveMusicClientContent { + /** Weighted prompts as the model input. */ + weightedPrompts?: WeightedPrompt[]; +} + +/** Messages sent by the client in the LiveMusicClientMessage call. */ +export declare interface LiveMusicClientMessage { + /** Message to be sent in the first (and only in the first) `LiveMusicClientMessage`. + Clients should wait for a `LiveMusicSetupComplete` message before + sending any additional messages. */ + setup?: LiveMusicClientSetup; + /** User input to influence music generation. */ + clientContent?: LiveMusicClientContent; + /** Configuration for music generation. */ + musicGenerationConfig?: LiveMusicGenerationConfig; + /** Playback control signal for the music generation. */ + playbackControl?: LiveMusicPlaybackControl; +} + +/** Message to be sent by the system when connecting to the API. */ +export declare interface LiveMusicClientSetup { + /** The model's resource name. Format: `models/{model}`. */ + model?: string; +} + +/** Parameters for connecting to the live API. */ +export declare interface LiveMusicConnectParameters { + /** The model's resource name. */ + model: string; + /** Callbacks invoked on server events. */ + callbacks: LiveMusicCallbacks; +} + +/** A prompt that was filtered with the reason. */ +export declare interface LiveMusicFilteredPrompt { + /** The text prompt that was filtered. */ + text?: string; + /** The reason the prompt was filtered. */ + filteredReason?: string; +} + +/** Configuration for music generation. */ +export declare interface LiveMusicGenerationConfig { + /** Controls the variance in audio generation. Higher values produce + higher variance. Range is [0.0, 3.0]. */ + temperature?: number; + /** Controls how the model selects tokens for output. Samples the topK + tokens with the highest probabilities. Range is [1, 1000]. */ + topK?: number; + /** Seeds audio generation. If not set, the request uses a randomly + generated seed. */ + seed?: number; + /** Controls how closely the model follows prompts. + Higher guidance follows more closely, but will make transitions more + abrupt. Range is [0.0, 6.0]. */ + guidance?: number; + /** Beats per minute. Range is [60, 200]. */ + bpm?: number; + /** Density of sounds. Range is [0.0, 1.0]. */ + density?: number; + /** Brightness of the music. Range is [0.0, 1.0]. */ + brightness?: number; + /** Scale of the generated music. */ + scale?: Scale; + /** Whether the audio output should contain bass. */ + muteBass?: boolean; + /** Whether the audio output should contain drums. */ + muteDrums?: boolean; + /** Whether the audio output should contain only bass and drums. */ + onlyBassAndDrums?: boolean; +} + +/** The playback control signal to apply to the music generation. */ +export declare enum LiveMusicPlaybackControl { + /** + * This value is unused. + */ + PLAYBACK_CONTROL_UNSPECIFIED = "PLAYBACK_CONTROL_UNSPECIFIED", + /** + * Start generating the music. + */ + PLAY = "PLAY", + /** + * Hold the music generation. Use PLAY to resume from the current position. + */ + PAUSE = "PAUSE", + /** + * Stop the music generation and reset the context (prompts retained). + Use PLAY to restart the music generation. + */ + STOP = "STOP", + /** + * Reset the context of the music generation without stopping it. + Retains the current prompts and config. + */ + RESET_CONTEXT = "RESET_CONTEXT", +} + +/** Server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. + Clients may choose to buffer and play it out in real time. + */ +export declare interface LiveMusicServerContent { + /** The audio chunks that the model has generated. */ + audioChunks?: AudioChunk[]; +} + +/** Response message for the LiveMusicClientMessage call. */ +export declare class LiveMusicServerMessage { + /** Message sent in response to a `LiveMusicClientSetup` message from the client. + Clients should wait for this message before sending any additional messages. */ + setupComplete?: LiveMusicServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveMusicServerContent; + /** A prompt that was filtered with the reason. */ + filteredPrompt?: LiveMusicFilteredPrompt; + /** + * Returns the first audio chunk from the server content, if present. + * + * @remarks + * If there are no audio chunks in the response, undefined will be returned. + */ + get audioChunk(): AudioChunk | undefined; +} + +/** Sent in response to a `LiveMusicClientSetup` message from the client. */ +export declare interface LiveMusicServerSetupComplete {} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class LiveMusicSession { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + /** + Sets inputs to steer music generation. Updates the session's current + weighted prompts. + + @param params - Contains one property, `weightedPrompts`. + + - `weightedPrompts` to send to the model; weights are normalized to + sum to 1.0. + + @experimental + */ + setWeightedPrompts( + params: types.LiveMusicSetWeightedPromptsParameters, + ): Promise; + /** + Sets a configuration to the model. Updates the session's current + music generation config. + + @param params - Contains one property, `musicGenerationConfig`. + + - `musicGenerationConfig` to set in the model. Passing an empty or + undefined config to the model will reset the config to defaults. + + @experimental + */ + setMusicGenerationConfig( + params: types.LiveMusicSetConfigParameters, + ): Promise; + private sendPlaybackControl; + /** + * Start the music stream. + * + * @experimental + */ + play(): void; + /** + * Temporarily halt the music stream. Use `play` to resume from the current + * position. + * + * @experimental + */ + pause(): void; + /** + * Stop the music stream and reset the state. Retains the current prompts + * and config. + * + * @experimental + */ + stop(): void; + /** + * Resets the context of the music generation without stopping it. + * Retains the current prompts and config. + * + * @experimental + */ + resetContext(): void; + /** + Terminates the WebSocket connection. + + @experimental + */ + close(): void; +} + +/** Parameters for setting config for the live music API. */ +export declare interface LiveMusicSetConfigParameters { + /** Configuration for music generation. */ + musicGenerationConfig: LiveMusicGenerationConfig; +} + +/** Parameters for setting weighted prompts for the live music API. */ +export declare interface LiveMusicSetWeightedPromptsParameters { + /** A map of text prompts to weights to use for the generation request. */ + weightedPrompts: WeightedPrompt[]; +} + +/** Prompts and config used for generating this audio chunk. */ +export declare interface LiveMusicSourceMetadata { + /** Weighted prompts for generating this audio chunk. */ + clientContent?: LiveMusicClientContent; + /** Music generation config for generating this audio chunk. */ + musicGenerationConfig?: LiveMusicGenerationConfig; +} + +/** Parameters for sending client content to the live API. */ +export declare interface LiveSendClientContentParameters { + /** Client content to send to the session. */ + turns?: ContentListUnion; + /** If true, indicates that the server content generation should start with + the currently accumulated prompt. Otherwise, the server will await + additional messages before starting generation. */ + turnComplete?: boolean; +} + +/** Parameters for sending realtime input to the live API. */ +export declare interface LiveSendRealtimeInputParameters { + /** Realtime input to send to the session. */ + media?: BlobImageUnion; + /** The realtime audio input stream. */ + audio?: Blob_2; + /** + Indicates that the audio stream has ended, e.g. because the microphone was + turned off. + + This should only be sent when automatic activity detection is enabled + (which is the default). + + The client can reopen the stream by sending an audio message. + */ + audioStreamEnd?: boolean; + /** The realtime video input stream. */ + video?: BlobImageUnion; + /** The realtime text input stream. */ + text?: string; + /** Marks the start of user activity. */ + activityStart?: ActivityStart; + /** Marks the end of user activity. */ + activityEnd?: ActivityEnd; +} + +/** Parameters for sending tool responses to the live API. */ +export declare class LiveSendToolResponseParameters { + /** Tool responses to send to the session. */ + functionResponses: FunctionResponse[] | FunctionResponse; +} + +/** Incremental server update generated by the model in response to client messages. + + Content is generated as quickly as possible, and not in real time. Clients + may choose to buffer and play it out in real time. + */ +export declare interface LiveServerContent { + /** The content that the model has generated as part of the current conversation with the user. */ + modelTurn?: Content; + /** If true, indicates that the model is done generating. Generation will only start in response to additional client messages. Can be set alongside `content`, indicating that the `content` is the last in the turn. */ + turnComplete?: boolean; + /** If true, indicates that a client message has interrupted current model generation. If the client is playing out the content in realtime, this is a good signal to stop and empty the current queue. */ + interrupted?: boolean; + /** Metadata returned to client when grounding is enabled. */ + groundingMetadata?: GroundingMetadata; + /** If true, indicates that the model is done generating. When model is + interrupted while generating there will be no generation_complete message + in interrupted turn, it will go through interrupted > turn_complete. + When model assumes realtime playback there will be delay between + generation_complete and turn_complete that is caused by model + waiting for playback to finish. If true, indicates that the model + has finished generating all content. This is a signal to the client + that it can stop sending messages. */ + generationComplete?: boolean; + /** Input transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. */ + inputTranscription?: Transcription; + /** Output transcription. The transcription is independent to the model + turn which means it doesn’t imply any ordering between transcription and + model turn. + */ + outputTranscription?: Transcription; + /** Metadata related to url context retrieval tool. */ + urlContextMetadata?: UrlContextMetadata; +} + +/** Server will not be able to service client soon. */ +export declare interface LiveServerGoAway { + /** The remaining time before the connection will be terminated as ABORTED. The minimal time returned here is specified differently together with the rate limits for a given model. */ + timeLeft?: string; +} + +/** Response message for API call. */ +export declare class LiveServerMessage { + /** Sent in response to a `LiveClientSetup` message from the client. */ + setupComplete?: LiveServerSetupComplete; + /** Content generated by the model in response to client messages. */ + serverContent?: LiveServerContent; + /** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ + toolCall?: LiveServerToolCall; + /** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. */ + toolCallCancellation?: LiveServerToolCallCancellation; + /** Usage metadata about model response(s). */ + usageMetadata?: UsageMetadata; + /** Server will disconnect soon. */ + goAway?: LiveServerGoAway; + /** Update of the session resumption state. */ + sessionResumptionUpdate?: LiveServerSessionResumptionUpdate; + /** + * Returns the concatenation of all text parts from the server content if present. + * + * @remarks + * If there are non-text parts in the response, the concatenation of all text + * parts will be returned, and a warning will be logged. + */ + get text(): string | undefined; + /** + * Returns the concatenation of all inline data parts from the server content if present. + * + * @remarks + * If there are non-inline data parts in the + * response, the concatenation of all inline data parts will be returned, and + * a warning will be logged. + */ + get data(): string | undefined; +} + +/** Update of the session resumption state. + + Only sent if `session_resumption` was set in the connection config. + */ +export declare interface LiveServerSessionResumptionUpdate { + /** New handle that represents state that can be resumed. Empty if `resumable`=false. */ + newHandle?: string; + /** True if session can be resumed at this point. It might be not possible to resume session at some points. In that case we send update empty new_handle and resumable=false. Example of such case could be model executing function calls or just generating. Resuming session (using previous session token) in such state will result in some data loss. */ + resumable?: boolean; + /** Index of last message sent by client that is included in state represented by this SessionResumptionToken. Only sent when `SessionResumptionConfig.transparent` is set. + + Presence of this index allows users to transparently reconnect and avoid issue of losing some part of realtime audio input/video. If client wishes to temporarily disconnect (for example as result of receiving GoAway) they can do it without losing state by buffering messages sent since last `SessionResmumptionTokenUpdate`. This field will enable them to limit buffering (avoid keeping all requests in RAM). + + Note: This should not be used for when resuming a session at some time later -- in those cases partial audio and video frames arelikely not needed. */ + lastConsumedClientMessageIndex?: string; +} + +export declare interface LiveServerSetupComplete { + /** The session id of the live session. */ + sessionId?: string; +} + +/** Request for the client to execute the `function_calls` and return the responses with the matching `id`s. */ +export declare interface LiveServerToolCall { + /** The function call to be executed. */ + functionCalls?: FunctionCall[]; +} + +/** Notification for the client that a previously issued `ToolCallMessage` with the specified `id`s should have been not executed and should be cancelled. + + If there were side-effects to those tool calls, clients may attempt to undo + the tool calls. This message occurs only in cases where the clients interrupt + server turns. + */ +export declare interface LiveServerToolCallCancellation { + /** The ids of the tool calls to be cancelled. */ + ids?: string[]; +} + +/** Logprobs Result */ +export declare interface LogprobsResult { + /** Length = total number of decoding steps. The chosen candidates may or may not be in top_candidates. */ + chosenCandidates?: LogprobsResultCandidate[]; + /** Length = total number of decoding steps. */ + topCandidates?: LogprobsResultTopCandidates[]; +} + +/** Candidate for the logprobs token and score. */ +export declare interface LogprobsResultCandidate { + /** The candidate's log probability. */ + logProbability?: number; + /** The candidate's token string value. */ + token?: string; + /** The candidate's token id value. */ + tokenId?: number; +} + +/** Candidates with top log probabilities at each decoding step. */ +export declare interface LogprobsResultTopCandidates { + /** Sorted by log probability in descending order. */ + candidates?: LogprobsResultCandidate[]; +} + +/** Configuration for a Mask reference image. */ +export declare interface MaskReferenceConfig { + /** Prompts the model to generate a mask instead of you needing to + provide one (unless MASK_MODE_USER_PROVIDED is used). */ + maskMode?: MaskReferenceMode; + /** A list of up to 5 class ids to use for semantic segmentation. + Automatically creates an image mask based on specific objects. */ + segmentationClasses?: number[]; + /** Dilation percentage of the mask provided. + Float between 0 and 1. */ + maskDilation?: number; +} + +/** A mask reference image. + + This encapsulates either a mask image provided by the user and configs for + the user provided mask, or only config parameters for the model to generate + a mask. + + A mask image is an image whose non-zero values indicate where to edit the base + image. If the user provides a mask image, the mask must be in the same + dimensions as the raw image. + */ +export declare class MaskReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + config?: MaskReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the mask mode of a mask reference image. */ +export declare enum MaskReferenceMode { + MASK_MODE_DEFAULT = "MASK_MODE_DEFAULT", + MASK_MODE_USER_PROVIDED = "MASK_MODE_USER_PROVIDED", + MASK_MODE_BACKGROUND = "MASK_MODE_BACKGROUND", + MASK_MODE_FOREGROUND = "MASK_MODE_FOREGROUND", + MASK_MODE_SEMANTIC = "MASK_MODE_SEMANTIC", +} + +/** + * Creates a McpCallableTool from MCP clients and an optional config. + * + * The callable tool can invoke the MCP clients with given function call + * arguments. (often for automatic function calling). + * Use the config to modify tool parameters such as behavior. + * + * @experimental Built-in MCP support is an experimental feature, may change in future + * versions. + */ +export declare function mcpToTool( + ...args: [...Client[], CallableToolConfig | Client] +): CallableTool; + +/** Server content modalities. */ +export declare enum MediaModality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Plain text. + */ + TEXT = "TEXT", + /** + * Images. + */ + IMAGE = "IMAGE", + /** + * Video. + */ + VIDEO = "VIDEO", + /** + * Audio. + */ + AUDIO = "AUDIO", + /** + * Document, e.g. PDF. + */ + DOCUMENT = "DOCUMENT", +} + +/** The media resolution to use. */ +export declare enum MediaResolution { + /** + * Media resolution has not been set + */ + MEDIA_RESOLUTION_UNSPECIFIED = "MEDIA_RESOLUTION_UNSPECIFIED", + /** + * Media resolution set to low (64 tokens). + */ + MEDIA_RESOLUTION_LOW = "MEDIA_RESOLUTION_LOW", + /** + * Media resolution set to medium (256 tokens). + */ + MEDIA_RESOLUTION_MEDIUM = "MEDIA_RESOLUTION_MEDIUM", + /** + * Media resolution set to high (zoomed reframing with 256 tokens). + */ + MEDIA_RESOLUTION_HIGH = "MEDIA_RESOLUTION_HIGH", +} + +/** Server content modalities. */ +export declare enum Modality { + /** + * The modality is unspecified. + */ + MODALITY_UNSPECIFIED = "MODALITY_UNSPECIFIED", + /** + * Indicates the model should return text + */ + TEXT = "TEXT", + /** + * Indicates the model should return images. + */ + IMAGE = "IMAGE", + /** + * Indicates the model should return audio. + */ + AUDIO = "AUDIO", +} + +/** Represents token counting info for a single modality. */ +export declare interface ModalityTokenCount { + /** The modality associated with this token count. */ + modality?: MediaModality; + /** Number of tokens. */ + tokenCount?: number; +} + +/** The mode of the predictor to be used in dynamic retrieval. */ +export declare enum Mode { + /** + * Always trigger retrieval. + */ + MODE_UNSPECIFIED = "MODE_UNSPECIFIED", + /** + * Run retrieval only when system decides it is necessary. + */ + MODE_DYNAMIC = "MODE_DYNAMIC", +} + +/** A trained machine learning model. */ +export declare interface Model { + /** Resource name of the model. */ + name?: string; + /** Display name of the model. */ + displayName?: string; + /** Description of the model. */ + description?: string; + /** Version ID of the model. A new version is committed when a new + model version is uploaded or trained under an existing model ID. The + version ID is an auto-incrementing decimal number in string + representation. */ + version?: string; + /** List of deployed models created from this base model. Note that a + model could have been deployed to endpoints in different locations. */ + endpoints?: Endpoint[]; + /** Labels with user-defined metadata to organize your models. */ + labels?: Record; + /** Information about the tuned model from the base model. */ + tunedModelInfo?: TunedModelInfo; + /** The maximum number of input tokens that the model can handle. */ + inputTokenLimit?: number; + /** The maximum number of output tokens that the model can generate. */ + outputTokenLimit?: number; + /** List of actions that are supported by the model. */ + supportedActions?: string[]; + /** The default checkpoint id of a model version. + */ + defaultCheckpointId?: string; + /** The checkpoints of the model. */ + checkpoints?: Checkpoint[]; +} + +export declare class Models extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Makes an API request to generate content with a given model. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContent({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * candidateCount: 2, + * } + * }); + * console.log(response); + * ``` + */ + generateContent: ( + params: types.GenerateContentParameters, + ) => Promise; + /** + * This logic is needed for GenerateContentConfig only. + * Previously we made GenerateContentConfig.responseSchema field to accept + * unknown. Since v1.9.0, we switch to use backend JSON schema support. + * To maintain backward compatibility, we move the data that was treated as + * JSON schema from the responseSchema field to the responseJsonSchema field. + */ + private maybeMoveToResponseJsonSchem; + /** + * Makes an API request to generate content with a given model and yields the + * response in chunks. + * + * For the `model` parameter, supported formats for Vertex AI API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The full resource name starts with 'projects/', for example: + * 'projects/my-project-id/locations/us-central1/publishers/google/models/gemini-2.0-flash' + * - The partial resource name with 'publishers/', for example: + * 'publishers/google/models/gemini-2.0-flash' or + * 'publishers/meta/models/llama-3.1-405b-instruct-maas' + * - `/` separated publisher and model name, for example: + * 'google/gemini-2.0-flash' or 'meta/llama-3.1-405b-instruct-maas' + * + * For the `model` parameter, supported formats for Gemini API include: + * - The Gemini model ID, for example: 'gemini-2.0-flash' + * - The model name starts with 'models/', for example: + * 'models/gemini-2.0-flash' + * - For tuned models, the model name starts with 'tunedModels/', + * for example: + * 'tunedModels/1234567890123456789' + * + * Some models support multimodal input and output. + * + * @param params - The parameters for generating content with streaming response. + * @return The response from generating content. + * + * @example + * ```ts + * const response = await ai.models.generateContentStream({ + * model: 'gemini-2.0-flash', + * contents: 'why is the sky blue?', + * config: { + * maxOutputTokens: 200, + * } + * }); + * for await (const chunk of response) { + * console.log(chunk); + * } + * ``` + */ + generateContentStream: ( + params: types.GenerateContentParameters, + ) => Promise>; + /** + * Transforms the CallableTools in the parameters to be simply Tools, it + * copies the params into a new object and replaces the tools, it does not + * modify the original params. Also sets the MCP usage header if there are + * MCP tools in the parameters. + */ + private processParamsMaybeAddMcpUsage; + private initAfcToolsMap; + private processAfcStream; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + generateImages: ( + params: types.GenerateImagesParameters, + ) => Promise; + list: (params?: types.ListModelsParameters) => Promise>; + /** + * Edits an image based on a prompt, list of reference images, and configuration. + * + * @param params - The parameters for editing an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.editImage({ + * model: 'imagen-3.0-capability-001', + * prompt: 'Generate an image containing a mug with the product logo [1] visible on the side of the mug.', + * referenceImages: [subjectReferenceImage] + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + editImage: ( + params: types.EditImageParameters, + ) => Promise; + /** + * Upscales an image based on an image, upscale factor, and configuration. + * Only supported in Vertex AI currently. + * + * @param params - The parameters for upscaling an image. + * @return The response from the API. + * + * @example + * ```ts + * const response = await client.models.upscaleImage({ + * model: 'imagen-3.0-generate-002', + * image: image, + * upscaleFactor: 'x2', + * config: { + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + upscaleImage: ( + params: types.UpscaleImageParameters, + ) => Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + generateVideos: ( + params: types.GenerateVideosParameters, + ) => Promise; + private generateContentInternal; + private generateContentStreamInternal; + /** + * Calculates embeddings for the given contents. Only text is supported. + * + * @param params - The parameters for embedding contents. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.embedContent({ + * model: 'text-embedding-004', + * contents: [ + * 'What is your name?', + * 'What is your favorite color?', + * ], + * config: { + * outputDimensionality: 64, + * }, + * }); + * console.log(response); + * ``` + */ + embedContent( + params: types.EmbedContentParameters, + ): Promise; + /** + * Generates an image based on a text description and configuration. + * + * @param params - The parameters for generating images. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.generateImages({ + * model: 'imagen-3.0-generate-002', + * prompt: 'Robot holding a red skateboard', + * config: { + * numberOfImages: 1, + * includeRaiReason: true, + * }, + * }); + * console.log(response?.generatedImages?.[0]?.image?.imageBytes); + * ``` + */ + private generateImagesInternal; + private editImageInternal; + private upscaleImageInternal; + /** + * Fetches information about a model by name. + * + * @example + * ```ts + * const modelInfo = await ai.models.get({model: 'gemini-2.0-flash'}); + * ``` + */ + get(params: types.GetModelParameters): Promise; + private listInternal; + /** + * Updates a tuned model by its name. + * + * @param params - The parameters for updating the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.update({ + * model: 'tuned-model-name', + * config: { + * displayName: 'New display name', + * description: 'New description', + * }, + * }); + * ``` + */ + update(params: types.UpdateModelParameters): Promise; + /** + * Deletes a tuned model by its name. + * + * @param params - The parameters for deleting the model. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.delete({model: 'tuned-model-name'}); + * ``` + */ + delete( + params: types.DeleteModelParameters, + ): Promise; + /** + * Counts the number of tokens in the given contents. Multimodal input is + * supported for Gemini models. + * + * @param params - The parameters for counting tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.countTokens({ + * model: 'gemini-2.0-flash', + * contents: 'The quick brown fox jumps over the lazy dog.' + * }); + * console.log(response); + * ``` + */ + countTokens( + params: types.CountTokensParameters, + ): Promise; + /** + * Given a list of contents, returns a corresponding TokensInfo containing + * the list of tokens and list of token ids. + * + * This method is not supported by the Gemini Developer API. + * + * @param params - The parameters for computing tokens. + * @return The response from the API. + * + * @example + * ```ts + * const response = await ai.models.computeTokens({ + * model: 'gemini-2.0-flash', + * contents: 'What is your name?' + * }); + * console.log(response); + * ``` + */ + computeTokens( + params: types.ComputeTokensParameters, + ): Promise; + /** + * Generates videos based on a text description and configuration. + * + * @param params - The parameters for generating videos. + * @return A Promise which allows you to track the progress and eventually retrieve the generated videos using the operations.get method. + * + * @example + * ```ts + * const operation = await ai.models.generateVideos({ + * model: 'veo-2.0-generate-001', + * prompt: 'A neon hologram of a cat driving at top speed', + * config: { + * numberOfVideos: 1 + * }); + * + * while (!operation.done) { + * await new Promise(resolve => setTimeout(resolve, 10000)); + * operation = await ai.operations.getVideosOperation({operation: operation}); + * } + * + * console.log(operation.response?.generatedVideos?.[0]?.video?.uri); + * ``` + */ + private generateVideosInternal; +} + +/** Config for model selection. */ +export declare interface ModelSelectionConfig { + /** Options for feature selection preference. */ + featureSelectionPreference?: FeatureSelectionPreference; +} + +/** The configuration for the multi-speaker setup. */ +export declare interface MultiSpeakerVoiceConfig { + /** The configuration for the speaker to use. */ + speakerVoiceConfigs?: SpeakerVoiceConfig[]; +} + +/** A long-running operation. */ +export declare interface Operation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The response if the operation is successful. */ + response?: T; + /** + * Instantiates an Operation of the same type as the one being called with the fields set from the API response. + * @internal + */ + _fromAPIResponse({ + apiResponse, + isVertexAI, + }: OperationFromAPIResponseParameters): Operation; +} + +/** Parameters of the fromAPIResponse method of the Operation class. */ +export declare interface OperationFromAPIResponseParameters { + /** The API response to be converted to an Operation. */ + apiResponse: Record; + /** Whether the API response is from Vertex AI. */ + isVertexAI: boolean; +} + +/** Parameters for the get method of the operations module. */ +export declare interface OperationGetParameters> { + /** The operation to be retrieved. */ + operation: U; + /** Used to override the default configuration. */ + config?: GetOperationConfig; +} + +export declare class Operations extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + getVideosOperation( + parameters: types.OperationGetParameters< + types.GenerateVideosResponse, + types.GenerateVideosOperation + >, + ): Promise; + /** + * Gets the status of a long-running operation. + * + * @param parameters The parameters for the get operation request. + * @return The updated Operation object, with the latest status or result. + */ + get>( + parameters: types.OperationGetParameters, + ): Promise>; + private getVideosOperationInternal; + private fetchPredictVideosOperationInternal; +} + +/** Required. Outcome of the code execution. */ +export declare enum Outcome { + /** + * Unspecified status. This value should not be used. + */ + OUTCOME_UNSPECIFIED = "OUTCOME_UNSPECIFIED", + /** + * Code execution completed successfully. + */ + OUTCOME_OK = "OUTCOME_OK", + /** + * Code execution finished but with a failure. `stderr` should contain the reason. + */ + OUTCOME_FAILED = "OUTCOME_FAILED", + /** + * Code execution ran for too long, and was cancelled. There may or may not be a partial output present. + */ + OUTCOME_DEADLINE_EXCEEDED = "OUTCOME_DEADLINE_EXCEEDED", +} + +export declare enum PagedItem { + PAGED_ITEM_BATCH_JOBS = "batchJobs", + PAGED_ITEM_MODELS = "models", + PAGED_ITEM_TUNING_JOBS = "tuningJobs", + PAGED_ITEM_FILES = "files", + PAGED_ITEM_CACHED_CONTENTS = "cachedContents", +} + +declare interface PagedItemConfig { + config?: { + pageToken?: string; + pageSize?: number; + }; +} + +declare interface PagedItemResponse { + nextPageToken?: string; + sdkHttpResponse?: types.HttpResponse; + batchJobs?: T[]; + models?: T[]; + tuningJobs?: T[]; + files?: T[]; + cachedContents?: T[]; +} + +/** + * Pager class for iterating through paginated results. + */ +export declare class Pager implements AsyncIterable { + private nameInternal; + private pageInternal; + private paramsInternal; + private pageInternalSize; + private sdkHttpResponseInternal?; + protected requestInternal: ( + params: PagedItemConfig, + ) => Promise>; + protected idxInternal: number; + constructor( + name: PagedItem, + request: (params: PagedItemConfig) => Promise>, + response: PagedItemResponse, + params: PagedItemConfig, + ); + private init; + private initNextPage; + /** + * Returns the current page, which is a list of items. + * + * @remarks + * The first page is retrieved when the pager is created. The returned list of + * items could be a subset of the entire list. + */ + get page(): T[]; + /** + * Returns the type of paged item (for example, ``batch_jobs``). + */ + get name(): PagedItem; + /** + * Returns the length of the page fetched each time by this pager. + * + * @remarks + * The number of items in the page is less than or equal to the page length. + */ + get pageSize(): number; + /** + * Returns the headers of the API response. + */ + get sdkHttpResponse(): types.HttpResponse | undefined; + /** + * Returns the parameters when making the API request for the next page. + * + * @remarks + * Parameters contain a set of optional configs that can be + * used to customize the API request. For example, the `pageToken` parameter + * contains the token to request the next page. + */ + get params(): PagedItemConfig; + /** + * Returns the total number of items in the current page. + */ + get pageLength(): number; + /** + * Returns the item at the given index. + */ + getItem(index: number): T; + /** + * Returns an async iterator that support iterating through all items + * retrieved from the API. + * + * @remarks + * The iterator will automatically fetch the next page if there are more items + * to fetch from the API. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * for await (const file of pager) { + * console.log(file.name); + * } + * ``` + */ + [Symbol.asyncIterator](): AsyncIterator; + /** + * Fetches the next page of items. This makes a new API request. + * + * @throws {Error} If there are no more pages to fetch. + * + * @example + * + * ```ts + * const pager = await ai.files.list({config: {pageSize: 10}}); + * let page = pager.page; + * while (true) { + * for (const file of page) { + * console.log(file.name); + * } + * if (!pager.hasNextPage()) { + * break; + * } + * page = await pager.nextPage(); + * } + * ``` + */ + nextPage(): Promise; + /** + * Returns true if there are more pages to fetch from the API. + */ + hasNextPage(): boolean; +} + +/** A datatype containing media content. + + Exactly one field within a Part should be set, representing the specific type + of content being conveyed. Using multiple fields within the same `Part` + instance is considered invalid. + */ +export declare interface Part { + /** Metadata for a given video. */ + videoMetadata?: VideoMetadata; + /** Indicates if the part is thought from the model. */ + thought?: boolean; + /** Optional. Inlined bytes data. */ + inlineData?: Blob_2; + /** Optional. URI based data. */ + fileData?: FileData; + /** An opaque signature for the thought so it can be reused in subsequent requests. + * @remarks Encoded as base64 string. */ + thoughtSignature?: string; + /** Optional. Result of executing the [ExecutableCode]. */ + codeExecutionResult?: CodeExecutionResult; + /** Optional. Code generated by the model that is meant to be executed. */ + executableCode?: ExecutableCode; + /** Optional. A predicted [FunctionCall] returned from the model that contains a string representing the [FunctionDeclaration.name] with the parameters and their values. */ + functionCall?: FunctionCall; + /** Optional. The result output of a [FunctionCall] that contains a string representing the [FunctionDeclaration.name] and a structured JSON object containing any output from the function call. It is used as context to the model. */ + functionResponse?: FunctionResponse; + /** Optional. Text part (can be code). */ + text?: string; +} + +export declare type PartListUnion = PartUnion[] | PartUnion; + +/** Tuning spec for Partner models. */ +export declare interface PartnerModelTuningSpec { + /** Hyperparameters for tuning. The accepted hyper_parameters and their valid range of values will differ depending on the base model. */ + hyperParameters?: Record; + /** Required. Cloud Storage path to file containing training dataset for tuning. The dataset must be formatted as a JSONL file. */ + trainingDatasetUri?: string; + /** Optional. Cloud Storage path to file containing validation dataset for tuning. The dataset must be formatted as a JSONL file. */ + validationDatasetUri?: string; +} + +export declare type PartUnion = Part | string; + +/** Enum that controls the generation of people. */ +export declare enum PersonGeneration { + /** + * Block generation of images of people. + */ + DONT_ALLOW = "DONT_ALLOW", + /** + * Generate images of adults, but not children. + */ + ALLOW_ADULT = "ALLOW_ADULT", + /** + * Generate images that include adults and children. + */ + ALLOW_ALL = "ALLOW_ALL", +} + +/** The configuration for the prebuilt speaker to use. */ +export declare interface PrebuiltVoiceConfig { + /** The name of the prebuilt voice to use. */ + voiceName?: string; +} + +/** Config for proactivity features. */ +export declare interface ProactivityConfig { + /** If enabled, the model can reject responding to the last prompt. For + example, this allows the model to ignore out of context speech or to stay + silent if the user did not make a request, yet. */ + proactiveAudio?: boolean; +} + +/** A RagChunk includes the content of a chunk of a RagFile, and associated metadata. */ +export declare interface RagChunk { + /** If populated, represents where the chunk starts and ends in the document. */ + pageSpan?: RagChunkPageSpan; + /** The content of the chunk. */ + text?: string; +} + +/** Represents where the chunk starts and ends in the document. */ +export declare interface RagChunkPageSpan { + /** Page where chunk starts in the document. Inclusive. 1-indexed. */ + firstPage?: number; + /** Page where chunk ends in the document. Inclusive. 1-indexed. */ + lastPage?: number; +} + +/** Specifies the context retrieval config. */ +export declare interface RagRetrievalConfig { + /** Optional. Config for filters. */ + filter?: RagRetrievalConfigFilter; + /** Optional. Config for Hybrid Search. */ + hybridSearch?: RagRetrievalConfigHybridSearch; + /** Optional. Config for ranking and reranking. */ + ranking?: RagRetrievalConfigRanking; + /** Optional. The number of contexts to retrieve. */ + topK?: number; +} + +/** Config for filters. */ +export declare interface RagRetrievalConfigFilter { + /** Optional. String for metadata filtering. */ + metadataFilter?: string; + /** Optional. Only returns contexts with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; + /** Optional. Only returns contexts with vector similarity larger than the threshold. */ + vectorSimilarityThreshold?: number; +} + +/** Config for Hybrid Search. */ +export declare interface RagRetrievalConfigHybridSearch { + /** Optional. Alpha value controls the weight between dense and sparse vector search results. The range is [0, 1], while 0 means sparse vector search only and 1 means dense vector search only. The default value is 0.5 which balances sparse and dense vector search equally. */ + alpha?: number; +} + +/** Config for ranking and reranking. */ +export declare interface RagRetrievalConfigRanking { + /** Optional. Config for LlmRanker. */ + llmRanker?: RagRetrievalConfigRankingLlmRanker; + /** Optional. Config for Rank Service. */ + rankService?: RagRetrievalConfigRankingRankService; +} + +/** Config for LlmRanker. */ +export declare interface RagRetrievalConfigRankingLlmRanker { + /** Optional. The model name used for ranking. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/inference#supported-models). */ + modelName?: string; +} + +/** Config for Rank Service. */ +export declare interface RagRetrievalConfigRankingRankService { + /** Optional. The model name of the rank service. Format: `semantic-ranker-512@latest` */ + modelName?: string; +} + +/** A raw reference image. + + A raw reference image represents the base image to edit, provided by the user. + It can optionally be provided in addition to a mask reference image or + a style reference image. + */ +export declare class RawReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Marks the end of user activity. + + This can only be sent if automatic (i.e. server-side) activity detection is + disabled. + */ +export declare interface RealtimeInputConfig { + /** If not set, automatic activity detection is enabled by default. If automatic voice detection is disabled, the client must send activity signals. */ + automaticActivityDetection?: AutomaticActivityDetection; + /** Defines what effect activity has. */ + activityHandling?: ActivityHandling; + /** Defines which input is included in the user's turn. */ + turnCoverage?: TurnCoverage; +} + +export declare type ReferenceImage = + | RawReferenceImage + | MaskReferenceImage + | ControlReferenceImage + | StyleReferenceImage + | SubjectReferenceImage; + +/** Private class that represents a Reference image that is sent to API. */ +declare interface ReferenceImageAPIInternal { + /** The reference image for the editing operation. */ + referenceImage?: types.Image; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the mask reference image. */ + maskImageConfig?: types.MaskReferenceConfig; + /** Configuration for the control reference image. */ + controlImageConfig?: types.ControlReferenceConfig; + /** Configuration for the style reference image. */ + styleImageConfig?: types.StyleReferenceConfig; + /** Configuration for the subject reference image. */ + subjectImageConfig?: types.SubjectReferenceConfig; +} + +/** Represents a recorded session. */ +export declare interface ReplayFile { + replayId?: string; + interactions?: ReplayInteraction[]; +} + +/** Represents a single interaction, request and response in a replay. */ +export declare interface ReplayInteraction { + request?: ReplayRequest; + response?: ReplayResponse; +} + +/** Represents a single request in a replay. */ +export declare interface ReplayRequest { + method?: string; + url?: string; + headers?: Record; + bodySegments?: Record[]; +} + +/** Represents a single response in a replay. */ +export declare class ReplayResponse { + statusCode?: number; + headers?: Record; + bodySegments?: Record[]; + sdkResponseSegments?: Record[]; +} + +/** Defines a retrieval tool that model can call to access external knowledge. */ +export declare interface Retrieval { + /** Optional. Deprecated. This option is no longer supported. */ + disableAttribution?: boolean; + /** Use data source powered by external API for grounding. */ + externalApi?: ExternalApi; + /** Set to use data source powered by Vertex AI Search. */ + vertexAiSearch?: VertexAISearch; + /** Set to use data source powered by Vertex RAG store. User data is uploaded via the VertexRagDataService. */ + vertexRagStore?: VertexRagStore; +} + +/** Retrieval config. + */ +export declare interface RetrievalConfig { + /** Optional. The location of the user. */ + latLng?: LatLng; + /** The language code of the user. */ + languageCode?: string; +} + +/** Metadata related to retrieval in the grounding flow. */ +export declare interface RetrievalMetadata { + /** Optional. Score indicating how likely information from Google Search could help answer the prompt. The score is in the range `[0, 1]`, where 0 is the least likely and 1 is the most likely. This score is only populated when Google Search grounding and dynamic retrieval is enabled. It will be compared to the threshold to determine whether to trigger Google Search. */ + googleSearchDynamicRetrievalScore?: number; +} + +/** Safety attributes of a GeneratedImage or the user-provided prompt. */ +export declare interface SafetyAttributes { + /** List of RAI categories. + */ + categories?: string[]; + /** List of scores of each categories. + */ + scores?: number[]; + /** Internal use only. + */ + contentType?: string; +} + +/** Enum that controls the safety filter level for objectionable content. */ +export declare enum SafetyFilterLevel { + 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", +} + +/** Safety rating corresponding to the generated content. */ +export declare interface SafetyRating { + /** Output only. Indicates whether the content was filtered out because of this rating. */ + blocked?: boolean; + /** Output only. Harm category. */ + category?: HarmCategory; + /** Output only. The overwritten threshold for the safety category of Gemini 2.0 image out. If minors are detected in the output image, the threshold of each safety category will be overwritten if user sets a lower threshold. */ + overwrittenThreshold?: HarmBlockThreshold; + /** Output only. Harm probability levels in the content. */ + probability?: HarmProbability; + /** Output only. Harm probability score. */ + probabilityScore?: number; + /** Output only. Harm severity levels in the content. */ + severity?: HarmSeverity; + /** Output only. Harm severity score. */ + severityScore?: number; +} + +/** Safety settings. */ +export declare interface SafetySetting { + /** Determines if the harm block method uses probability or probability + and severity scores. */ + method?: HarmBlockMethod; + /** Required. Harm category. */ + category?: HarmCategory; + /** Required. The harm block threshold. */ + threshold?: HarmBlockThreshold; +} + +/** Scale of the generated music. */ +export declare enum Scale { + /** + * Default value. This value is unused. + */ + SCALE_UNSPECIFIED = "SCALE_UNSPECIFIED", + /** + * C major or A minor. + */ + C_MAJOR_A_MINOR = "C_MAJOR_A_MINOR", + /** + * Db major or Bb minor. + */ + D_FLAT_MAJOR_B_FLAT_MINOR = "D_FLAT_MAJOR_B_FLAT_MINOR", + /** + * D major or B minor. + */ + D_MAJOR_B_MINOR = "D_MAJOR_B_MINOR", + /** + * Eb major or C minor + */ + E_FLAT_MAJOR_C_MINOR = "E_FLAT_MAJOR_C_MINOR", + /** + * E major or Db minor. + */ + E_MAJOR_D_FLAT_MINOR = "E_MAJOR_D_FLAT_MINOR", + /** + * F major or D minor. + */ + F_MAJOR_D_MINOR = "F_MAJOR_D_MINOR", + /** + * Gb major or Eb minor. + */ + G_FLAT_MAJOR_E_FLAT_MINOR = "G_FLAT_MAJOR_E_FLAT_MINOR", + /** + * G major or E minor. + */ + G_MAJOR_E_MINOR = "G_MAJOR_E_MINOR", + /** + * Ab major or F minor. + */ + A_FLAT_MAJOR_F_MINOR = "A_FLAT_MAJOR_F_MINOR", + /** + * A major or Gb minor. + */ + A_MAJOR_G_FLAT_MINOR = "A_MAJOR_G_FLAT_MINOR", + /** + * Bb major or G minor. + */ + B_FLAT_MAJOR_G_MINOR = "B_FLAT_MAJOR_G_MINOR", + /** + * B major or Ab minor. + */ + B_MAJOR_A_FLAT_MINOR = "B_MAJOR_A_FLAT_MINOR", +} + +/** Schema is used to define the format of input/output data. + + Represents a select subset of an [OpenAPI 3.0 schema + object](https://spec.openapis.org/oas/v3.0.3#schema-object). More fields may + be added in the future as needed. + */ +export declare interface Schema { + /** Optional. The value should be validated against any (one or more) of the subschemas in the list. */ + anyOf?: Schema[]; + /** Optional. Default value of the data. */ + default?: unknown; + /** Optional. The description of the data. */ + description?: string; + /** Optional. Possible values of the element of primitive type with enum format. Examples: 1. We can define direction as : {type:STRING, format:enum, enum:["EAST", NORTH", "SOUTH", "WEST"]} 2. We can define apartment number as : {type:INTEGER, format:enum, enum:["101", "201", "301"]} */ + enum?: string[]; + /** Optional. Example of the object. Will only populated when the object is the root. */ + example?: unknown; + /** Optional. The format of the data. Supported formats: for NUMBER type: "float", "double" for INTEGER type: "int32", "int64" for STRING type: "email", "byte", etc */ + format?: string; + /** Optional. SCHEMA FIELDS FOR TYPE ARRAY Schema of the elements of Type.ARRAY. */ + items?: Schema; + /** Optional. Maximum number of the elements for Type.ARRAY. */ + maxItems?: string; + /** Optional. Maximum length of the Type.STRING */ + maxLength?: string; + /** Optional. Maximum number of the properties for Type.OBJECT. */ + maxProperties?: string; + /** Optional. Maximum value of the Type.INTEGER and Type.NUMBER */ + maximum?: number; + /** Optional. Minimum number of the elements for Type.ARRAY. */ + minItems?: string; + /** Optional. SCHEMA FIELDS FOR TYPE STRING Minimum length of the Type.STRING */ + minLength?: string; + /** Optional. Minimum number of the properties for Type.OBJECT. */ + minProperties?: string; + /** Optional. SCHEMA FIELDS FOR TYPE INTEGER and NUMBER Minimum value of the Type.INTEGER and Type.NUMBER */ + minimum?: number; + /** Optional. Indicates if the value may be null. */ + nullable?: boolean; + /** Optional. Pattern of the Type.STRING to restrict a string to a regular expression. */ + pattern?: string; + /** Optional. SCHEMA FIELDS FOR TYPE OBJECT Properties of Type.OBJECT. */ + properties?: Record; + /** Optional. The order of the properties. Not a standard field in open api spec. Only used to support the order of the properties. */ + propertyOrdering?: string[]; + /** Optional. Required properties of Type.OBJECT. */ + required?: string[]; + /** Optional. The title of the Schema. */ + title?: string; + /** Optional. The type of the data. */ + type?: Type; +} + +export declare type SchemaUnion = Schema | unknown; + +/** Google search entry point. */ +export declare interface SearchEntryPoint { + /** Optional. Web content snippet that can be embedded in a web page or an app webview. */ + renderedContent?: string; + /** Optional. Base64 encoded JSON representing array of tuple. + * @remarks Encoded as base64 string. */ + sdkBlob?: string; +} + +/** Segment of the content. */ +export declare interface Segment { + /** Output only. End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero. */ + endIndex?: number; + /** Output only. The index of a Part object within its parent Content object. */ + partIndex?: number; + /** Output only. Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero. */ + startIndex?: number; + /** Output only. The text corresponding to the segment from the response. */ + text?: string; +} + +/** Parameters for sending a message within a chat session. + + These parameters are used with the `chat.sendMessage()` method. + */ +export declare interface SendMessageParameters { + /** The message to send to the model. + + The SDK will combine all parts into a single 'user' content to send to + the model. + */ + message: PartListUnion; + /** Config for this specific request. + + Please note that the per-request config does not change the chat level + config, nor inherit from it. If you intend to use some values from the + chat's default config, you must explicitly copy them into this per-request + config. + */ + config?: GenerateContentConfig; +} + +/** + Represents a connection to the API. + + @experimental + */ +export declare class Session { + readonly conn: WebSocket_2; + private readonly apiClient; + constructor(conn: WebSocket_2, apiClient: ApiClient); + private tLiveClientContent; + private tLiveClienttToolResponse; + /** + Send a message over the established connection. + + @param params - Contains two **optional** properties, `turns` and + `turnComplete`. + + - `turns` will be converted to a `Content[]` + - `turnComplete: true` [default] indicates that you are done sending + content and expect a response. If `turnComplete: false`, the server + will wait for additional messages before starting generation. + + @experimental + + @remarks + There are two ways to send messages to the live API: + `sendClientContent` and `sendRealtimeInput`. + + `sendClientContent` messages are added to the model context **in order**. + Having a conversation using `sendClientContent` messages is roughly + equivalent to using the `Chat.sendMessageStream`, except that the state of + the `chat` history is stored on the API server instead of locally. + + Because of `sendClientContent`'s order guarantee, the model cannot respons + as quickly to `sendClientContent` messages as to `sendRealtimeInput` + messages. This makes the biggest difference when sending objects that have + significant preprocessing time (typically images). + + The `sendClientContent` message sends a `Content[]` + which has more options than the `Blob` sent by `sendRealtimeInput`. + + So the main use-cases for `sendClientContent` over `sendRealtimeInput` are: + + - Sending anything that can't be represented as a `Blob` (text, + `sendClientContent({turns="Hello?"}`)). + - Managing turns when not using audio input and voice activity detection. + (`sendClientContent({turnComplete:true})` or the short form + `sendClientContent()`) + - Prefilling a conversation context + ``` + sendClientContent({ + turns: [ + Content({role:user, parts:...}), + Content({role:user, parts:...}), + ... + ] + }) + ``` + @experimental + */ + sendClientContent(params: types.LiveSendClientContentParameters): void; + /** + Send a realtime message over the established connection. + + @param params - Contains one property, `media`. + + - `media` will be converted to a `Blob` + + @experimental + + @remarks + Use `sendRealtimeInput` for realtime audio chunks and video frames (images). + + With `sendRealtimeInput` the api will respond to audio automatically + based on voice activity detection (VAD). + + `sendRealtimeInput` is optimized for responsivness at the expense of + deterministic ordering guarantees. Audio and video tokens are to the + context when they become available. + + Note: The Call signature expects a `Blob` object, but only a subset + of audio and image mimetypes are allowed. + */ + sendRealtimeInput(params: types.LiveSendRealtimeInputParameters): void; + /** + Send a function response message over the established connection. + + @param params - Contains property `functionResponses`. + + - `functionResponses` will be converted to a `functionResponses[]` + + @remarks + Use `sendFunctionResponse` to reply to `LiveServerToolCall` from the server. + + Use {@link types.LiveConnectConfig#tools} to configure the callable functions. + + @experimental + */ + sendToolResponse(params: types.LiveSendToolResponseParameters): void; + /** + Terminates the WebSocket connection. + + @experimental + + @example + ```ts + let model: string; + if (GOOGLE_GENAI_USE_VERTEXAI) { + model = 'gemini-2.0-flash-live-preview-04-09'; + } else { + model = 'gemini-live-2.5-flash-preview'; + } + const session = await ai.live.connect({ + model: model, + config: { + responseModalities: [Modality.AUDIO], + } + }); + + session.close(); + ``` + */ + close(): void; +} + +/** Configuration of session resumption mechanism. + + Included in `LiveConnectConfig.session_resumption`. If included server + will send `LiveServerSessionResumptionUpdate` messages. + */ +export declare interface SessionResumptionConfig { + /** Session resumption handle of previous session (session to restore). + + If not present new session will be started. */ + handle?: string; + /** If set the server will send `last_consumed_client_message_index` in the `session_resumption_update` messages to allow for transparent reconnections. */ + transparent?: boolean; +} + +/** + * Overrides the base URLs for the Gemini API and Vertex AI API. + * + * @remarks This function should be called before initializing the SDK. If the + * base URLs are set after initializing the SDK, the base URLs will not be + * updated. Base URLs provided in the HttpOptions will also take precedence over + * URLs set here. + * + * @example + * ```ts + * import {GoogleGenAI, setDefaultBaseUrls} from '@google/genai'; + * // Override the base URL for the Gemini API. + * setDefaultBaseUrls({geminiUrl:'https://gemini.google.com'}); + * + * // Override the base URL for the Vertex AI API. + * setDefaultBaseUrls({vertexUrl: 'https://vertexai.googleapis.com'}); + * + * const ai = new GoogleGenAI({apiKey: 'GEMINI_API_KEY'}); + * ``` + */ +export declare function setDefaultBaseUrls( + baseUrlParams: BaseUrlParameters, +): void; + +/** Context window will be truncated by keeping only suffix of it. + + Context window will always be cut at start of USER role turn. System + instructions and `BidiGenerateContentSetup.prefix_turns` will not be + subject to the sliding window mechanism, they will always stay at the + beginning of context window. + */ +export declare interface SlidingWindow { + /** Session reduction target -- how many tokens we should keep. Window shortening operation has some latency costs, so we should avoid running it on every turn. Should be < trigger_tokens. If not set, trigger_tokens/2 is assumed. */ + targetTokens?: string; +} + +/** The configuration for the speaker to use. */ +export declare interface SpeakerVoiceConfig { + /** The name of the speaker to use. Should be the same as in the + prompt. */ + speaker?: string; + /** The configuration for the voice to use. */ + voiceConfig?: VoiceConfig; +} + +/** The speech generation configuration. */ +export declare interface SpeechConfig { + /** The configuration for the speaker to use. + */ + voiceConfig?: VoiceConfig; + /** The configuration for the multi-speaker setup. + It is mutually exclusive with the voice_config field. + */ + multiSpeakerVoiceConfig?: MultiSpeakerVoiceConfig; + /** Language code (ISO 639. e.g. en-US) for the speech synthesization. + Only available for Live API. + */ + languageCode?: string; +} + +export declare type SpeechConfigUnion = SpeechConfig | string; + +/** Start of speech sensitivity. */ +export declare enum StartSensitivity { + /** + * The default is START_SENSITIVITY_LOW. + */ + START_SENSITIVITY_UNSPECIFIED = "START_SENSITIVITY_UNSPECIFIED", + /** + * Automatic detection will detect the start of speech more often. + */ + START_SENSITIVITY_HIGH = "START_SENSITIVITY_HIGH", + /** + * Automatic detection will detect the start of speech less often. + */ + START_SENSITIVITY_LOW = "START_SENSITIVITY_LOW", +} + +/** Configuration for a Style reference image. */ +export declare interface StyleReferenceConfig { + /** A text description of the style to use for the generated image. */ + styleDescription?: string; +} + +/** A style reference image. + + This encapsulates a style reference image provided by the user, and + additionally optional config parameters for the style reference image. + + A raw reference image can also be provided as a destination for the style to + be applied to. + */ +export declare class StyleReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the style reference image. */ + config?: StyleReferenceConfig; + /** Internal method to convert to ReferenceImageAPIInternal. */ + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Configuration for a Subject reference image. */ +export declare interface SubjectReferenceConfig { + /** The subject type of a subject reference image. */ + subjectType?: SubjectReferenceType; + /** Subject description for the image. */ + subjectDescription?: string; +} + +/** A subject reference image. + + This encapsulates a subject reference image provided by the user, and + additionally optional config parameters for the subject reference image. + + A raw reference image can also be provided as a destination for the subject to + be applied to. + */ +export declare class SubjectReferenceImage { + /** The reference image for the editing operation. */ + referenceImage?: Image_2; + /** The id of the reference image. */ + referenceId?: number; + /** The type of the reference image. Only set by the SDK. */ + referenceType?: string; + /** Configuration for the subject reference image. */ + config?: SubjectReferenceConfig; + toReferenceImageAPI(): ReferenceImageAPIInternal; +} + +/** Enum representing the subject type of a subject reference image. */ +export declare enum SubjectReferenceType { + SUBJECT_TYPE_DEFAULT = "SUBJECT_TYPE_DEFAULT", + SUBJECT_TYPE_PERSON = "SUBJECT_TYPE_PERSON", + SUBJECT_TYPE_ANIMAL = "SUBJECT_TYPE_ANIMAL", + SUBJECT_TYPE_PRODUCT = "SUBJECT_TYPE_PRODUCT", +} + +/** Hyperparameters for SFT. */ +export declare interface SupervisedHyperParameters { + /** Optional. Adapter size for tuning. */ + adapterSize?: AdapterSize; + /** Optional. Number of complete passes the model makes over the entire training dataset during training. */ + epochCount?: string; + /** Optional. Multiplier for adjusting the default learning rate. Mutually exclusive with `learning_rate`. */ + learningRateMultiplier?: number; +} + +/** Dataset distribution for Supervised Tuning. */ +export declare interface SupervisedTuningDatasetDistribution { + /** Output only. Sum of a given population of values that are billable. */ + billableSum?: string; + /** Output only. Defines the histogram bucket. */ + buckets?: SupervisedTuningDatasetDistributionDatasetBucket[]; + /** Output only. The maximum of the population values. */ + max?: number; + /** Output only. The arithmetic mean of the values in the population. */ + mean?: number; + /** Output only. The median of the values in the population. */ + median?: number; + /** Output only. The minimum of the population values. */ + min?: number; + /** Output only. The 5th percentile of the values in the population. */ + p5?: number; + /** Output only. The 95th percentile of the values in the population. */ + p95?: number; + /** Output only. Sum of a given population of values. */ + sum?: string; +} + +/** Dataset bucket used to create a histogram for the distribution given a population of values. */ +export declare interface SupervisedTuningDatasetDistributionDatasetBucket { + /** Output only. Number of values in the bucket. */ + count?: number; + /** Output only. Left bound of the bucket. */ + left?: number; + /** Output only. Right bound of the bucket. */ + right?: number; +} + +/** Tuning data statistics for Supervised Tuning. */ +export declare interface SupervisedTuningDataStats { + /** Output only. For each index in `truncated_example_indices`, the user-facing reason why the example was dropped. */ + droppedExampleReasons?: string[]; + /** Output only. Number of billable characters in the tuning dataset. */ + totalBillableCharacterCount?: string; + /** Output only. Number of billable tokens in the tuning dataset. */ + totalBillableTokenCount?: string; + /** Output only. The number of examples in the dataset that have been dropped. An example can be dropped for reasons including: too many tokens, contains an invalid image, contains too many images, etc. */ + totalTruncatedExampleCount?: string; + /** Output only. Number of tuning characters in the tuning dataset. */ + totalTuningCharacterCount?: string; + /** Output only. A partial sample of the indices (starting from 1) of the dropped examples. */ + truncatedExampleIndices?: string[]; + /** Output only. Number of examples in the tuning dataset. */ + tuningDatasetExampleCount?: string; + /** Output only. Number of tuning steps for this Tuning Job. */ + tuningStepCount?: string; + /** Output only. Sample user messages in the training dataset uri. */ + userDatasetExamples?: Content[]; + /** Output only. Dataset distributions for the user input tokens. */ + userInputTokenDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the messages per example. */ + userMessagePerExampleDistribution?: SupervisedTuningDatasetDistribution; + /** Output only. Dataset distributions for the user output tokens. */ + userOutputTokenDistribution?: SupervisedTuningDatasetDistribution; +} + +/** Tuning Spec for Supervised Tuning for first party models. */ +export declare interface SupervisedTuningSpec { + /** Optional. If set to true, disable intermediate checkpoints for SFT and only the last checkpoint will be exported. Otherwise, enable intermediate checkpoints for SFT. Default is false. */ + exportLastCheckpointOnly?: boolean; + /** Optional. Hyperparameters for SFT. */ + hyperParameters?: SupervisedHyperParameters; + /** Required. Training dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + trainingDatasetUri?: string; + /** Optional. Validation dataset used for tuning. The dataset can be specified as either a Cloud Storage path to a JSONL file or as the resource name of a Vertex Multimodal Dataset. */ + validationDatasetUri?: string; +} + +export declare interface TestTableFile { + comment?: string; + testMethod?: string; + parameterNames?: string[]; + testTable?: TestTableItem[]; +} + +export declare interface TestTableItem { + /** The name of the test. This is used to derive the replay id. */ + name?: string; + /** The parameters to the test. Use pydantic models. */ + parameters?: Record; + /** Expects an exception for MLDev matching the string. */ + exceptionIfMldev?: string; + /** Expects an exception for Vertex matching the string. */ + exceptionIfVertex?: string; + /** Use if you don't want to use the default replay id which is derived from the test name. */ + overrideReplayId?: string; + /** True if the parameters contain an unsupported union type. This test will be skipped for languages that do not support the union type. */ + hasUnion?: boolean; + /** When set to a reason string, this test will be skipped in the API mode. Use this flag for tests that can not be reproduced with the real API. E.g. a test that deletes a resource. */ + skipInApiMode?: string; + /** Keys to ignore when comparing the request and response. This is useful for tests that are not deterministic. */ + ignoreKeys?: string[]; +} + +/** The thinking features configuration. */ +export declare interface ThinkingConfig { + /** Indicates whether to include thoughts in the response. If true, thoughts are returned only if the model supports thought and thoughts are available. + */ + includeThoughts?: boolean; + /** Indicates the thinking budget in tokens. 0 is DISABLED. -1 is AUTOMATIC. The default values and allowed ranges are model dependent. + */ + thinkingBudget?: number; +} + +export declare class Tokens extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Creates an ephemeral auth token resource. + * + * @experimental + * + * @remarks + * Ephemeral auth tokens is only supported in the Gemini Developer API. + * It can be used for the session connection to the Live constrained API. + * Support in v1alpha only. + * + * @param params - The parameters for the create request. + * @return The created auth token. + * + * @example + * ```ts + * const ai = new GoogleGenAI({ + * apiKey: token.name, + * httpOptions: { apiVersion: 'v1alpha' } // Support in v1alpha only. + * }); + * + * // Case 1: If LiveEphemeralParameters is unset, unlock LiveConnectConfig + * // when using the token in Live API sessions. Each session connection can + * // use a different configuration. + * const config: CreateAuthTokenConfig = { + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * } + * const token = await ai.tokens.create(config); + * + * // Case 2: If LiveEphemeralParameters is set, lock all fields in + * // LiveConnectConfig when using the token in Live API sessions. For + * // example, changing `outputAudioTranscription` in the Live API + * // connection will be ignored by the API. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * } + * } + * const token = await ai.tokens.create(config); + * + * // Case 3: If LiveEphemeralParameters is set and lockAdditionalFields is + * // set, lock LiveConnectConfig with set and additional fields (e.g. + * // responseModalities, systemInstruction, temperature in this example) when + * // using the token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: ['temperature'], + * } + * const token = await ai.tokens.create(config); + * + * // Case 4: If LiveEphemeralParameters is set and lockAdditionalFields is + * // empty array, lock LiveConnectConfig with set fields (e.g. + * // responseModalities, systemInstruction in this example) when using the + * // token in Live API sessions. + * const config: CreateAuthTokenConfig = + * uses: 3, + * expireTime: '2025-05-01T00:00:00Z', + * LiveEphemeralParameters: { + * model: 'gemini-2.0-flash-001', + * config: { + * 'responseModalities': ['AUDIO'], + * 'systemInstruction': 'Always answer in English.', + * } + * }, + * lockAdditionalFields: [], + * } + * const token = await ai.tokens.create(config); + * ``` + */ + create(params: types.CreateAuthTokenParameters): Promise; +} + +/** Tokens info with a list of tokens and the corresponding list of token ids. */ +export declare interface TokensInfo { + /** Optional. Optional fields for the role from the corresponding Content. */ + role?: string; + /** A list of token ids from the input. */ + tokenIds?: string[]; + /** A list of tokens from the input. + * @remarks Encoded as base64 string. */ + tokens?: string[]; +} + +/** Tool details of a tool that the model may use to generate a response. */ +export declare interface Tool { + /** List of function declarations that the tool supports. */ + functionDeclarations?: FunctionDeclaration[]; + /** Optional. Retrieval tool type. System will always execute the provided retrieval tool(s) to get external knowledge to answer the prompt. Retrieval results are presented to the model for generation. */ + retrieval?: Retrieval; + /** Optional. Google Search tool type. Specialized retrieval tool + that is powered by Google Search. */ + googleSearch?: GoogleSearch; + /** Optional. GoogleSearchRetrieval tool type. Specialized retrieval tool that is powered by Google search. */ + googleSearchRetrieval?: GoogleSearchRetrieval; + /** Optional. Enterprise web search tool type. Specialized retrieval + tool that is powered by Vertex AI Search and Sec4 compliance. */ + enterpriseWebSearch?: EnterpriseWebSearch; + /** Optional. Google Maps tool type. Specialized retrieval tool + that is powered by Google Maps. */ + googleMaps?: GoogleMaps; + /** Optional. Tool to support URL context retrieval. */ + urlContext?: UrlContext; + /** + Tool to support the model interacting directly with the computer. + If enabled, it automatically populates computer-use specific Function + Declarations. */ + computerUse?: ToolComputerUse; + /** Optional. CodeExecution tool type. Enables the model to execute code as part of generation. */ + codeExecution?: ToolCodeExecution; +} + +/** Tool that executes code generated by the model, and automatically returns the result to the model. See also [ExecutableCode]and [CodeExecutionResult] which are input and output to this tool. */ +export declare interface ToolCodeExecution {} + +/** Computer Use tool type. */ +export declare interface ToolComputerUse { + /** A list of predefined functions that the should not be prepopulated. */ + excludedPredefinedFunctions?: string[]; + /** Required. The environment being operated. */ + environment?: Environment; +} + +/** Tool config. + + This config is shared for all tools provided in the request. + */ +export declare interface ToolConfig { + /** Optional. Function calling config. */ + functionCallingConfig?: FunctionCallingConfig; + /** Optional. Retrieval config. */ + retrievalConfig?: RetrievalConfig; +} + +export declare type ToolListUnion = ToolUnion[]; + +export declare type ToolUnion = Tool | CallableTool; + +/** Output only. Traffic type. This shows whether a request consumes Pay-As-You-Go or Provisioned Throughput quota. */ +export declare enum TrafficType { + /** + * Unspecified request traffic type. + */ + TRAFFIC_TYPE_UNSPECIFIED = "TRAFFIC_TYPE_UNSPECIFIED", + /** + * Type for Pay-As-You-Go traffic. + */ + ON_DEMAND = "ON_DEMAND", + /** + * Type for Provisioned Throughput traffic. + */ + PROVISIONED_THROUGHPUT = "PROVISIONED_THROUGHPUT", +} + +/** Audio transcription in Server Conent. */ +export declare interface Transcription { + /** Transcription text. + */ + text?: string; + /** The bool indicates the end of the transcription. + */ + finished?: boolean; +} + +export declare interface TunedModel { + /** Output only. The resource name of the TunedModel. Format: `projects/{project}/locations/{location}/models/{model}`. */ + model?: string; + /** Output only. A resource name of an Endpoint. Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. */ + endpoint?: string; + /** The checkpoints associated with this TunedModel. + This field is only populated for tuning jobs that enable intermediate + checkpoints. */ + checkpoints?: TunedModelCheckpoint[]; +} + +/** TunedModelCheckpoint for the Tuned Model of a Tuning Job. */ +export declare interface TunedModelCheckpoint { + /** The ID of the checkpoint. + */ + checkpointId?: string; + /** The epoch of the checkpoint. + */ + epoch?: string; + /** The step of the checkpoint. + */ + step?: string; + /** The Endpoint resource name that the checkpoint is deployed to. + Format: `projects/{project}/locations/{location}/endpoints/{endpoint}`. + */ + endpoint?: string; +} + +/** A tuned machine learning model. */ +export declare interface TunedModelInfo { + /** ID of the base model that you want to tune. */ + baseModel?: string; + /** Date and time when the base model was created. */ + createTime?: string; + /** Date and time when the base model was last updated. */ + updateTime?: string; +} + +/** Supervised fine-tuning training dataset. */ +export declare interface TuningDataset { + /** GCS URI of the file containing training dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; + /** Inline examples with simple input/output text. */ + examples?: TuningExample[]; +} + +/** The tuning data statistic values for TuningJob. */ +export declare interface TuningDataStats { + /** Output only. Statistics for distillation. */ + distillationDataStats?: DistillationDataStats; + /** The SFT Tuning data stats. */ + supervisedTuningDataStats?: SupervisedTuningDataStats; +} + +export declare interface TuningExample { + /** Text model input. */ + textInput?: string; + /** The expected model output. */ + output?: string; +} + +/** A tuning job. */ +export declare interface TuningJob { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Output only. Identifier. Resource name of a TuningJob. Format: `projects/{project}/locations/{location}/tuningJobs/{tuning_job}` */ + name?: string; + /** Output only. The detailed state of the job. */ + state?: JobState; + /** Output only. Time when the TuningJob was created. */ + createTime?: string; + /** Output only. Time when the TuningJob for the first time entered the `JOB_STATE_RUNNING` state. */ + startTime?: string; + /** Output only. Time when the TuningJob entered any of the following JobStates: `JOB_STATE_SUCCEEDED`, `JOB_STATE_FAILED`, `JOB_STATE_CANCELLED`, `JOB_STATE_EXPIRED`. */ + endTime?: string; + /** Output only. Time when the TuningJob was most recently updated. */ + updateTime?: string; + /** Output only. Only populated when job's state is `JOB_STATE_FAILED` or `JOB_STATE_CANCELLED`. */ + error?: GoogleRpcStatus; + /** Optional. The description of the TuningJob. */ + description?: string; + /** The base model that is being tuned. See [Supported models](https://cloud.google.com/vertex-ai/generative-ai/docs/model-reference/tuning#supported_models). */ + baseModel?: string; + /** Output only. The tuned model resources associated with this TuningJob. */ + tunedModel?: TunedModel; + /** Tuning Spec for Supervised Fine Tuning. */ + supervisedTuningSpec?: SupervisedTuningSpec; + /** Output only. The tuning data statistics associated with this TuningJob. */ + tuningDataStats?: TuningDataStats; + /** Customer-managed encryption key options for a TuningJob. If this is set, then all resources created by the TuningJob will be encrypted with the provided encryption key. */ + encryptionSpec?: EncryptionSpec; + /** Tuning Spec for open sourced and third party Partner models. */ + partnerModelTuningSpec?: PartnerModelTuningSpec; + /** Tuning Spec for Distillation. */ + distillationSpec?: DistillationSpec; + /** Output only. The Experiment associated with this TuningJob. */ + experiment?: string; + /** Optional. The labels with user-defined metadata to organize TuningJob and generated resources such as Model and Endpoint. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. See https://goo.gl/xmQnxf for more information and examples of labels. */ + labels?: Record; + /** Output only. The resource name of the PipelineJob associated with the TuningJob. Format: `projects/{project}/locations/{location}/pipelineJobs/{pipeline_job}`. */ + pipelineJob?: string; + /** Output only. Reserved for future use. */ + satisfiesPzi?: boolean; + /** Output only. Reserved for future use. */ + satisfiesPzs?: boolean; + /** The service account that the tuningJob workload runs as. If not specified, the Vertex AI Secure Fine-Tuned Service Agent in the project will be used. See https://cloud.google.com/iam/docs/service-agents#vertex-ai-secure-fine-tuning-service-agent Users starting the pipeline must have the `iam.serviceAccounts.actAs` permission on this service account. */ + serviceAccount?: string; + /** Optional. The display name of the TunedModel. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + tunedModelDisplayName?: string; +} + +/** A long-running operation. */ +export declare interface TuningOperation { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +declare class Tunings extends BaseModule { + private readonly apiClient; + constructor(apiClient: ApiClient); + /** + * Gets a TuningJob. + * + * @param name - The resource name of the tuning job. + * @return - A TuningJob object. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + get: (params: types.GetTuningJobParameters) => Promise; + /** + * Lists tuning jobs. + * + * @param config - The configuration for the list request. + * @return - A list of tuning jobs. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + list: ( + params?: types.ListTuningJobsParameters, + ) => Promise>; + /** + * Creates a supervised fine-tuning job. + * + * @param params - The parameters for the tuning job. + * @return - A TuningJob operation. + * + * @experimental - The SDK's tuning implementation is experimental, and may + * change in future versions. + */ + tune: (params: types.CreateTuningJobParameters) => Promise; + private getInternal; + private listInternal; + private tuneInternal; + private tuneMldevInternal; +} + +export declare interface TuningValidationDataset { + /** GCS URI of the file containing validation dataset in JSONL format. */ + gcsUri?: string; + /** The resource name of the Vertex Multimodal Dataset that is used as training dataset. Example: 'projects/my-project-id-or-number/locations/my-location/datasets/my-dataset-id'. */ + vertexDatasetResource?: string; +} + +/** Options about which input is included in the user's turn. */ +export declare enum TurnCoverage { + /** + * If unspecified, the default behavior is `TURN_INCLUDES_ONLY_ACTIVITY`. + */ + TURN_COVERAGE_UNSPECIFIED = "TURN_COVERAGE_UNSPECIFIED", + /** + * The users turn only includes activity since the last turn, excluding inactivity (e.g. silence on the audio stream). This is the default behavior. + */ + TURN_INCLUDES_ONLY_ACTIVITY = "TURN_INCLUDES_ONLY_ACTIVITY", + /** + * The users turn includes all realtime input since the last turn, including inactivity (e.g. silence on the audio stream). + */ + TURN_INCLUDES_ALL_INPUT = "TURN_INCLUDES_ALL_INPUT", +} + +/** Optional. The type of the data. */ +export declare enum Type { + /** + * Not specified, should not be used. + */ + TYPE_UNSPECIFIED = "TYPE_UNSPECIFIED", + /** + * OpenAPI string type + */ + STRING = "STRING", + /** + * OpenAPI number type + */ + NUMBER = "NUMBER", + /** + * OpenAPI integer type + */ + INTEGER = "INTEGER", + /** + * OpenAPI boolean type + */ + BOOLEAN = "BOOLEAN", + /** + * OpenAPI array type + */ + ARRAY = "ARRAY", + /** + * OpenAPI object type + */ + OBJECT = "OBJECT", + /** + * Null type + */ + NULL = "NULL", +} + +declare namespace types { + export { + createPartFromUri, + createPartFromText, + createPartFromFunctionCall, + createPartFromFunctionResponse, + createPartFromBase64, + createPartFromCodeExecutionResult, + createPartFromExecutableCode, + createUserContent, + createModelContent, + Outcome, + Language, + Type, + HarmCategory, + HarmBlockMethod, + HarmBlockThreshold, + Mode, + AuthType, + Environment, + ApiSpec, + UrlRetrievalStatus, + FinishReason, + HarmProbability, + HarmSeverity, + BlockedReason, + TrafficType, + Modality, + MediaResolution, + JobState, + AdapterSize, + FeatureSelectionPreference, + Behavior, + DynamicRetrievalConfigMode, + FunctionCallingConfigMode, + SafetyFilterLevel, + PersonGeneration, + ImagePromptLanguage, + MaskReferenceMode, + ControlReferenceType, + SubjectReferenceType, + EditMode, + VideoCompressionQuality, + FileState, + FileSource, + MediaModality, + StartSensitivity, + EndSensitivity, + ActivityHandling, + TurnCoverage, + FunctionResponseScheduling, + Scale, + LiveMusicPlaybackControl, + VideoMetadata, + Blob_2 as Blob, + FileData, + CodeExecutionResult, + ExecutableCode, + FunctionCall, + FunctionResponse, + Part, + Content, + HttpOptions, + Schema, + ModelSelectionConfig, + SafetySetting, + FunctionDeclaration, + Interval, + GoogleSearch, + DynamicRetrievalConfig, + GoogleSearchRetrieval, + EnterpriseWebSearch, + ApiKeyConfig, + AuthConfigGoogleServiceAccountConfig, + AuthConfigHttpBasicAuthConfig, + AuthConfigOauthConfig, + AuthConfigOidcConfig, + AuthConfig, + GoogleMaps, + UrlContext, + ToolComputerUse, + ApiAuthApiKeyConfig, + ApiAuth, + ExternalApiElasticSearchParams, + ExternalApiSimpleSearchParams, + ExternalApi, + VertexAISearchDataStoreSpec, + VertexAISearch, + VertexRagStoreRagResource, + RagRetrievalConfigFilter, + RagRetrievalConfigHybridSearch, + RagRetrievalConfigRankingLlmRanker, + RagRetrievalConfigRankingRankService, + RagRetrievalConfigRanking, + RagRetrievalConfig, + VertexRagStore, + Retrieval, + ToolCodeExecution, + Tool, + FunctionCallingConfig, + LatLng, + RetrievalConfig, + ToolConfig, + PrebuiltVoiceConfig, + VoiceConfig, + SpeakerVoiceConfig, + MultiSpeakerVoiceConfig, + SpeechConfig, + AutomaticFunctionCallingConfig, + ThinkingConfig, + GenerationConfigRoutingConfigAutoRoutingMode, + GenerationConfigRoutingConfigManualRoutingMode, + GenerationConfigRoutingConfig, + GenerateContentConfig, + GenerateContentParameters, + HttpResponse, + LiveCallbacks, + GoogleTypeDate, + Citation, + CitationMetadata, + UrlMetadata, + UrlContextMetadata, + RagChunkPageSpan, + RagChunk, + GroundingChunkRetrievedContext, + GroundingChunkWeb, + GroundingChunk, + Segment, + GroundingSupport, + RetrievalMetadata, + SearchEntryPoint, + GroundingMetadata, + LogprobsResultCandidate, + LogprobsResultTopCandidates, + LogprobsResult, + SafetyRating, + Candidate, + GenerateContentResponsePromptFeedback, + ModalityTokenCount, + GenerateContentResponseUsageMetadata, + GenerateContentResponse, + ReferenceImage, + EditImageParameters, + EmbedContentConfig, + EmbedContentParameters, + ContentEmbeddingStatistics, + ContentEmbedding, + EmbedContentMetadata, + EmbedContentResponse, + GenerateImagesConfig, + GenerateImagesParameters, + Image_2 as Image, + SafetyAttributes, + GeneratedImage, + GenerateImagesResponse, + MaskReferenceConfig, + ControlReferenceConfig, + StyleReferenceConfig, + SubjectReferenceConfig, + EditImageConfig, + EditImageResponse, + UpscaleImageResponse, + GetModelConfig, + GetModelParameters, + Endpoint, + TunedModelInfo, + Checkpoint, + Model, + ListModelsConfig, + ListModelsParameters, + ListModelsResponse, + UpdateModelConfig, + UpdateModelParameters, + DeleteModelConfig, + DeleteModelParameters, + DeleteModelResponse, + GenerationConfigThinkingConfig, + GenerationConfig, + CountTokensConfig, + CountTokensParameters, + CountTokensResponse, + ComputeTokensConfig, + ComputeTokensParameters, + TokensInfo, + ComputeTokensResponse, + Video, + GenerateVideosConfig, + GenerateVideosParameters, + GeneratedVideo, + GenerateVideosResponse, + GetTuningJobConfig, + GetTuningJobParameters, + TunedModelCheckpoint, + TunedModel, + GoogleRpcStatus, + SupervisedHyperParameters, + SupervisedTuningSpec, + DatasetDistributionDistributionBucket, + DatasetDistribution, + DatasetStats, + DistillationDataStats, + SupervisedTuningDatasetDistributionDatasetBucket, + SupervisedTuningDatasetDistribution, + SupervisedTuningDataStats, + TuningDataStats, + EncryptionSpec, + PartnerModelTuningSpec, + DistillationHyperParameters, + DistillationSpec, + TuningJob, + ListTuningJobsConfig, + ListTuningJobsParameters, + ListTuningJobsResponse, + TuningExample, + TuningDataset, + TuningValidationDataset, + CreateTuningJobConfig, + CreateTuningJobParameters, + TuningOperation, + CreateCachedContentConfig, + CreateCachedContentParameters, + CachedContentUsageMetadata, + CachedContent, + GetCachedContentConfig, + GetCachedContentParameters, + DeleteCachedContentConfig, + DeleteCachedContentParameters, + DeleteCachedContentResponse, + UpdateCachedContentConfig, + UpdateCachedContentParameters, + ListCachedContentsConfig, + ListCachedContentsParameters, + ListCachedContentsResponse, + ListFilesConfig, + ListFilesParameters, + FileStatus, + File_2 as File, + ListFilesResponse, + CreateFileConfig, + CreateFileParameters, + CreateFileResponse, + GetFileConfig, + GetFileParameters, + DeleteFileConfig, + DeleteFileParameters, + DeleteFileResponse, + InlinedRequest, + BatchJobSource, + JobError, + InlinedResponse, + BatchJobDestination, + CreateBatchJobConfig, + CreateBatchJobParameters, + BatchJob, + GetBatchJobConfig, + GetBatchJobParameters, + CancelBatchJobConfig, + CancelBatchJobParameters, + ListBatchJobsConfig, + ListBatchJobsParameters, + ListBatchJobsResponse, + DeleteBatchJobConfig, + DeleteBatchJobParameters, + DeleteResourceJob, + GetOperationConfig, + GetOperationParameters, + FetchPredictOperationConfig, + FetchPredictOperationParameters, + TestTableItem, + TestTableFile, + ReplayRequest, + ReplayResponse, + ReplayInteraction, + ReplayFile, + UploadFileConfig, + DownloadFileConfig, + DownloadFileParameters, + UpscaleImageConfig, + UpscaleImageParameters, + RawReferenceImage, + MaskReferenceImage, + ControlReferenceImage, + StyleReferenceImage, + SubjectReferenceImage, + LiveServerSetupComplete, + Transcription, + LiveServerContent, + LiveServerToolCall, + LiveServerToolCallCancellation, + UsageMetadata, + LiveServerGoAway, + LiveServerSessionResumptionUpdate, + LiveServerMessage, + OperationGetParameters, + OperationFromAPIResponseParameters, + Operation, + GenerateVideosOperation, + AutomaticActivityDetection, + RealtimeInputConfig, + SessionResumptionConfig, + SlidingWindow, + ContextWindowCompressionConfig, + AudioTranscriptionConfig, + ProactivityConfig, + LiveClientSetup, + LiveClientContent, + ActivityStart, + ActivityEnd, + LiveClientRealtimeInput, + LiveSendRealtimeInputParameters, + LiveClientToolResponse, + LiveClientMessage, + LiveConnectConfig, + LiveConnectParameters, + CreateChatParameters, + SendMessageParameters, + LiveSendClientContentParameters, + LiveSendToolResponseParameters, + LiveMusicClientSetup, + WeightedPrompt, + LiveMusicClientContent, + LiveMusicGenerationConfig, + LiveMusicClientMessage, + LiveMusicServerSetupComplete, + LiveMusicSourceMetadata, + AudioChunk, + LiveMusicServerContent, + LiveMusicFilteredPrompt, + LiveMusicServerMessage, + LiveMusicCallbacks, + UploadFileParameters, + CallableTool, + CallableToolConfig, + LiveMusicConnectParameters, + LiveMusicSetConfigParameters, + LiveMusicSetWeightedPromptsParameters, + AuthToken, + LiveConnectConstraints, + CreateAuthTokenConfig, + CreateAuthTokenParameters, + BlobImageUnion, + PartUnion, + PartListUnion, + ContentUnion, + ContentListUnion, + SchemaUnion, + SpeechConfigUnion, + ToolUnion, + ToolListUnion, + DownloadableFileUnion, + BatchJobSourceUnion, + BatchJobDestinationUnion, + }; +} + +/** Optional parameters for caches.update method. */ +export declare interface UpdateCachedContentConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The TTL for this resource. The expiration time is computed: now + TTL. It is a duration string, with up to nine fractional digits, terminated by 's'. Example: "3.5s". */ + ttl?: string; + /** Timestamp of when this resource is considered expired. Uses RFC 3339 format, Example: 2014-10-02T15:01:23Z. */ + expireTime?: string; +} + +export declare interface UpdateCachedContentParameters { + /** The server-generated resource name of the cached content. + */ + name: string; + /** Configuration that contains optional parameters. + */ + config?: UpdateCachedContentConfig; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + displayName?: string; + description?: string; + defaultCheckpointId?: string; +} + +/** Configuration for updating a tuned model. */ +export declare interface UpdateModelParameters { + model: string; + config?: UpdateModelConfig; +} + +declare interface Uploader { + /** + * Uploads a file to the given upload url. + * + * @param file The file to upload. file is in string type or a Blob. + * @param uploadUrl The upload URL as a string is where the file will be + * uploaded to. The uploadUrl must be a url that was returned by the + * https://generativelanguage.googleapis.com/upload/v1beta/files endpoint + * @param apiClient The ApiClient to use for uploading. + * @return A Promise that resolves to types.File. + */ + upload( + file: string | Blob, + uploadUrl: string, + apiClient: ApiClient, + ): Promise; + /** + * Returns the file's mimeType and the size of a given file. If the file is a + * string path, the file type is determined by the file extension. If the + * file's type cannot be determined, the type will be set to undefined. + * + * @param file The file to get the stat for. Can be a string path or a Blob. + * @return A Promise that resolves to the file stat of the given file. + */ + stat(file: string | Blob): Promise; +} + +/** Used to override the default configuration. */ +export declare interface UploadFileConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The name of the file in the destination (e.g., 'files/sample-image'. If not provided one will be generated. */ + name?: string; + /** mime_type: The MIME type of the file. If not provided, it will be inferred from the file extension. */ + mimeType?: string; + /** Optional display name of the file. */ + displayName?: string; +} + +/** Parameters for the upload file method. */ +export declare interface UploadFileParameters { + /** The string path to the file to be uploaded or a Blob object. */ + file: string | globalThis.Blob; + /** Configuration that contains optional parameters. */ + config?: UploadFileConfig; +} + +/** Configuration for upscaling an image. + + For more information on this configuration, refer to + the `Imagen API reference documentation + `_. + */ +export declare interface UpscaleImageConfig { + /** Used to override HTTP request options. */ + httpOptions?: HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Whether to include a reason for filtered-out images in the + response. */ + includeRaiReason?: boolean; + /** The image format that the output should be saved as. */ + outputMimeType?: string; + /** The level of compression if the ``output_mime_type`` is + ``image/jpeg``. */ + outputCompressionQuality?: number; + /** Whether to add an image enhancing step before upscaling. + It is expected to suppress the noise and JPEG compression artifacts + from the input image. */ + enhanceInputImage?: boolean; + /** With a higher image preservation factor, the original image + pixels are more respected. With a lower image preservation factor, the + output image will have be more different from the input image, but + with finer details and less noise. */ + imagePreservationFactor?: number; +} + +/** User-facing config UpscaleImageParameters. */ +export declare interface UpscaleImageParameters { + /** The model to use. */ + model: string; + /** The input image to upscale. */ + image: Image_2; + /** The factor to upscale the image (x2 or x4). */ + upscaleFactor: string; + /** Configuration for upscaling. */ + config?: UpscaleImageConfig; +} + +export declare class UpscaleImageResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: HttpResponse; + /** Generated images. */ + generatedImages?: GeneratedImage[]; +} + +/** Tool to support URL context retrieval. */ +export declare interface UrlContext {} + +/** Metadata related to url context retrieval tool. */ +export declare interface UrlContextMetadata { + /** List of url context. */ + urlMetadata?: UrlMetadata[]; +} + +/** Context for a single url retrieval. */ +export declare interface UrlMetadata { + /** The URL retrieved by the tool. */ + retrievedUrl?: string; + /** Status of the url retrieval. */ + urlRetrievalStatus?: UrlRetrievalStatus; +} + +/** Status of the url retrieval. */ +export declare enum UrlRetrievalStatus { + /** + * Default value. This value is unused + */ + URL_RETRIEVAL_STATUS_UNSPECIFIED = "URL_RETRIEVAL_STATUS_UNSPECIFIED", + /** + * Url retrieval is successful. + */ + URL_RETRIEVAL_STATUS_SUCCESS = "URL_RETRIEVAL_STATUS_SUCCESS", + /** + * Url retrieval is failed due to error. + */ + URL_RETRIEVAL_STATUS_ERROR = "URL_RETRIEVAL_STATUS_ERROR", +} + +/** Usage metadata about response(s). */ +export declare interface UsageMetadata { + /** Number of tokens in the prompt. When `cached_content` is set, this is still the total effective prompt size meaning this includes the number of tokens in the cached content. */ + promptTokenCount?: number; + /** Number of tokens in the cached part of the prompt (the cached content). */ + cachedContentTokenCount?: number; + /** Total number of tokens across all the generated response candidates. */ + responseTokenCount?: number; + /** Number of tokens present in tool-use prompt(s). */ + toolUsePromptTokenCount?: number; + /** Number of tokens of thoughts for thinking models. */ + thoughtsTokenCount?: number; + /** Total token count for prompt, response candidates, and tool-use prompts(if present). */ + totalTokenCount?: number; + /** List of modalities that were processed in the request input. */ + promptTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the cache input. */ + cacheTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were returned in the response. */ + responseTokensDetails?: ModalityTokenCount[]; + /** List of modalities that were processed in the tool-use prompt. */ + toolUsePromptTokensDetails?: ModalityTokenCount[]; + /** Traffic type. This shows whether a request consumes Pay-As-You-Go + or Provisioned Throughput quota. */ + trafficType?: TrafficType; +} + +/** Retrieve from Vertex AI Search datastore or engine for grounding. datastore and engine are mutually exclusive. See https://cloud.google.com/products/agent-builder */ +export declare interface VertexAISearch { + /** Specifications that define the specific DataStores to be searched, along with configurations for those data stores. This is only considered for Engines with multiple data stores. It should only be set if engine is used. */ + dataStoreSpecs?: VertexAISearchDataStoreSpec[]; + /** Optional. Fully-qualified Vertex AI Search data store resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + datastore?: string; + /** Optional. Fully-qualified Vertex AI Search engine resource ID. Format: `projects/{project}/locations/{location}/collections/{collection}/engines/{engine}` */ + engine?: string; + /** Optional. Filter strings to be passed to the search API. */ + filter?: string; + /** Optional. Number of search results to return per query. The default value is 10. The maximumm allowed value is 10. */ + maxResults?: number; +} + +/** Define data stores within engine to filter on in a search call and configurations for those data stores. For more information, see https://cloud.google.com/generative-ai-app-builder/docs/reference/rpc/google.cloud.discoveryengine.v1#datastorespec */ +export declare interface VertexAISearchDataStoreSpec { + /** Full resource name of DataStore, such as Format: `projects/{project}/locations/{location}/collections/{collection}/dataStores/{dataStore}` */ + dataStore?: string; + /** Optional. Filter specification to filter documents in the data store specified by data_store field. For more information on filtering, see [Filtering](https://cloud.google.com/generative-ai-app-builder/docs/filter-search-metadata) */ + filter?: string; +} + +/** Retrieve from Vertex RAG Store for grounding. */ +export declare interface VertexRagStore { + /** Optional. Deprecated. Please use rag_resources instead. */ + ragCorpora?: string[]; + /** Optional. The representation of the rag source. It can be used to specify corpus only or ragfiles. Currently only support one corpus or multiple files from one corpus. In the future we may open up multiple corpora support. */ + ragResources?: VertexRagStoreRagResource[]; + /** Optional. The retrieval config for the Rag query. */ + ragRetrievalConfig?: RagRetrievalConfig; + /** Optional. Number of top k results to return from the selected corpora. */ + similarityTopK?: number; + /** Optional. Currently only supported for Gemini Multimodal Live API. In Gemini Multimodal Live API, if `store_context` bool is specified, Gemini will leverage it to automatically memorize the interactions between the client and Gemini, and retrieve context when needed to augment the response generation for users' ongoing and future interactions. */ + storeContext?: boolean; + /** Optional. Only return results with vector distance smaller than the threshold. */ + vectorDistanceThreshold?: number; +} + +/** The definition of the Rag resource. */ +export declare interface VertexRagStoreRagResource { + /** Optional. RagCorpora resource name. Format: `projects/{project}/locations/{location}/ragCorpora/{rag_corpus}` */ + ragCorpus?: string; + /** Optional. rag_file_id. The files should be in the same rag_corpus set in rag_corpus field. */ + ragFileIds?: string[]; +} + +/** A generated video. */ +export declare interface Video { + /** Path to another storage. */ + uri?: string; + /** Video bytes. + * @remarks Encoded as base64 string. */ + videoBytes?: string; + /** Video encoding, for example "video/mp4". */ + mimeType?: string; +} + +/** Enum that controls the compression quality of the generated videos. */ +export declare enum VideoCompressionQuality { + /** + * Optimized video compression quality. This will produce videos + with a compressed, smaller file size. + */ + OPTIMIZED = "OPTIMIZED", + /** + * Lossless video compression quality. This will produce videos + with a larger file size. + */ + LOSSLESS = "LOSSLESS", +} + +/** Describes how the video in the Part should be used by the model. */ +export declare interface VideoMetadata { + /** The frame rate of the video sent to the model. If not specified, the + default value will be 1.0. The fps range is (0.0, 24.0]. */ + fps?: number; + /** Optional. The end offset of the video. */ + endOffset?: string; + /** Optional. The start offset of the video. */ + startOffset?: string; +} + +/** The configuration for the voice to use. */ +export declare interface VoiceConfig { + /** The configuration for the speaker to use. + */ + prebuiltVoiceConfig?: PrebuiltVoiceConfig; +} + +declare interface WebSocket_2 { + /** + * Connects the socket to the server. + */ + connect(): void; + /** + * Sends a message to the server. + */ + send(message: string): void; + /** + * Closes the socket connection. + */ + close(): void; +} + +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ +declare interface WebSocketCallbacks { + onopen: () => void; + onerror: (e: any) => void; + onmessage: (e: any) => void; + onclose: (e: any) => void; +} + +declare interface WebSocketFactory { + /** + * Returns a new WebSocket instance. + */ + create( + url: string, + headers: Record, + callbacks: WebSocketCallbacks, + ): WebSocket_2; +} + +/** Maps a prompt to a relative weight to steer music generation. */ +export declare interface WeightedPrompt { + /** Text prompt. */ + text?: string; + /** Weight of the prompt. The weight is used to control the relative + importance of the prompt. Higher weights are more important than lower + weights. + + Weight must not be 0. Weights of all weighted_prompts in this + LiveMusicClientContent message will be normalized. */ + weight?: number; +} + +export {}; diff --git a/sdk/stagehand-ts/google-ts-sdk/package/node/package.json b/sdk/stagehand-ts/google-ts-sdk/package/node/package.json new file mode 100644 index 0000000..7666aff --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/node/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/node", + "main": "../dist/node/index.js" +} diff --git a/sdk/stagehand-ts/google-ts-sdk/package/package.json b/sdk/stagehand-ts/google-ts-sdk/package/package.json new file mode 100644 index 0000000..f94edf9 --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/package.json @@ -0,0 +1,120 @@ +{ + "name": "@google/genai", + "version": "1.11.0", + "description": "", + "type": "module", + "main": "dist/node/index.mjs", + "module": "dist/web/index.mjs", + "browser": "dist/web/index.mjs", + "typings": "dist/genai.d.ts", + "exports": { + ".": { + "browser": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "require": "./dist/node/index.cjs", + "default": "./dist/node/index.mjs" + }, + "types": "./dist/genai.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.cjs", + "default": "./dist/index.mjs" + }, + "./web": { + "types": "./dist/web/web.d.ts", + "import": "./dist/web/index.mjs", + "default": "./dist/web/index.mjs" + }, + "./node": { + "types": "./dist/node/node.d.ts", + "import": "./dist/node/index.mjs", + "default": "./dist/node/index.mjs" + } + }, + "scripts": { + "prepare": "npm run build-prod", + "build": "rollup -c && api-extractor run --local --verbose && api-extractor run -c api-extractor.node.json --local --verbose&& api-extractor run -c api-extractor.web.json --local --verbose && node scripts/ignore_missing_mcp_dep.js", + "build-prod": "rollup -c && api-extractor run --verbose && api-extractor run -c api-extractor.node.json --verbose && api-extractor run -c api-extractor.web.json --verbose && node scripts/ignore_missing_mcp_dep.js", + "unit-test": "tsc && jasmine dist/test/unit/**/*_test.js dist/test/unit/*_test.js", + "system-test": "tsc && jasmine dist/test/system/**/*_test.js", + "test-server-tests": "tsc && GOOGLE_CLOUD_PROJECT=googcloudproj GOOGLE_CLOUD_LOCATION=googcloudloc jasmine dist/test/system/node/*_test.js !dist/test/system/node/live_test.js -- --test-server", + "test-server-tests:record": "tsc && jasmine --fail-fast dist/test/system/node/*_test.js !dist/test/system/node/live_test.js -- --test-server --record", + "docs": "typedoc && node --loader ts-node/esm scripts/add_docsite_license_headers.ts", + "pages-main": "node --loader ts-node/esm scripts/generate_pages.ts main", + "pages-release": "node --loader ts-node/esm scripts/generate_pages.ts release", + "format": "prettier '**/*.ts' '**/*.mjs' '**/*.json' --write", + "lint": "eslint '**/*.ts'", + "lint-fix": "eslint --fix '**/*.ts'" + }, + "engines": { + "node": ">=20.0.0" + }, + "files": [ + "dist/genai.d.ts", + "dist/index.mjs", + "dist/index.cjs", + "dist/index.mjs.map", + "dist/node/index.mjs", + "dist/node/index.cjs", + "dist/node/index.mjs.map", + "dist/node/node.d.ts", + "dist/web/index.mjs", + "dist/web/index.mjs.map", + "dist/web/web.d.ts", + "node/package.json", + "web/package.json" + ], + "devDependencies": { + "@eslint/js": "9.20.0", + "@microsoft/api-extractor": "^7.50.1", + "@rollup/plugin-json": "^6.1.0", + "@types/jasmine": "^5.1.2", + "@types/node": "^20.9.0", + "@types/unist": "^3.0.3", + "@types/ws": "^8.5.14", + "eslint": "8.57.0", + "gts": "^5.2.0", + "jasmine": "^5.5.0", + "jasmine-reporters": "^2.4.0", + "nyc": "^17.1.0", + "prettier": "3.3.3", + "prettier-plugin-organize-imports": "^4.1.0", + "rollup-plugin-typescript2": "^0.36.0", + "test-server-sdk": "^0.2.5", + "ts-node": "^10.9.2", + "tslib": "^2.8.1", + "tsx": "^4.19.4", + "typedoc": "^0.27.0", + "typescript": "~5.2.0", + "typescript-eslint": "8.24.1", + "zod": "^3.22.4", + "zod-to-json-schema": "^3.22.4" + }, + "dependencies": { + "google-auth-library": "^9.14.2", + "ws": "^8.18.0" + }, + "peerDependencies": { + "@modelcontextprotocol/sdk": "^1.11.0" + }, + "peerDependenciesMeta": { + "@modelcontextprotocol/sdk": { + "optional": true + } + }, + "repository": { + "type": "git", + "url": "https://github.com/googleapis/js-genai.git" + }, + "bugs": { + "url": "https://github.com/googleapis/js-genai/issues" + }, + "homepage": "https://github.com/googleapis/js-genai#readme", + "author": "", + "license": "Apache-2.0" +} diff --git a/sdk/stagehand-ts/google-ts-sdk/package/web/package.json b/sdk/stagehand-ts/google-ts-sdk/package/web/package.json new file mode 100644 index 0000000..606dd1f --- /dev/null +++ b/sdk/stagehand-ts/google-ts-sdk/package/web/package.json @@ -0,0 +1,4 @@ +{ + "name": "@google/genai/web", + "module": "../dist/web/index.mjs" +} diff --git a/sdk/stagehand-ts/lib/CHANGELOG.md b/sdk/stagehand-ts/lib/CHANGELOG.md new file mode 100644 index 0000000..89283b0 --- /dev/null +++ b/sdk/stagehand-ts/lib/CHANGELOG.md @@ -0,0 +1,57 @@ +# @browserbasehq/stagehand-lib + +## 2.4.0 + +### Minor Changes + +- [#778](https://github.com/browserbase/stagehand/pull/778) [`df570b6`](https://github.com/browserbase/stagehand/commit/df570b67e46febcaf7282ffb65dd5707e2808152) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - iframe support + +### Patch Changes + +- [#809](https://github.com/browserbase/stagehand/pull/809) [`03ebebc`](https://github.com/browserbase/stagehand/commit/03ebebc0317f92d8de77285cc2e66dc0131fe9fe) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - log NoObjectGenerated error details + +- [#801](https://github.com/browserbase/stagehand/pull/801) [`1d4f0ab`](https://github.com/browserbase/stagehand/commit/1d4f0abca47bf47ae8b7aeb53f3cd1155a7e5448) Thanks [@miguelg719](https://github.com/miguelg719)! - Default use API to true + +- [#798](https://github.com/browserbase/stagehand/pull/798) [`d86200b`](https://github.com/browserbase/stagehand/commit/d86200bd5bde4c5ba113ca89e28ab86c14a8304e) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix pino logging memory leak by reusing worker + +## 2.3.0 + +### Minor Changes + +- [#731](https://github.com/browserbase/stagehand/pull/731) [`393c8e0`](https://github.com/browserbase/stagehand/commit/393c8e05d016086e481c0043ee6b084c61886cad) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - make extract() with no arguments return the hybrid tree instead of text-rendered webpage + +- [#737](https://github.com/browserbase/stagehand/pull/737) [`6ef6073`](https://github.com/browserbase/stagehand/commit/6ef60730cab0ad9025f44b6eeb2c83751d1dcd35) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - deprecate useTextExtract and remove functionality + +### Patch Changes + +- [#741](https://github.com/browserbase/stagehand/pull/741) [`5680d25`](https://github.com/browserbase/stagehand/commit/5680d2509352c383ad502c9f4fabde01fa638833) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - use safeparse for zod validation + +- [#740](https://github.com/browserbase/stagehand/pull/740) [`28840a7`](https://github.com/browserbase/stagehand/commit/28840a7d3fec89a490984582fb37fa3d007c0349) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - dont log deprecation warning when onlyVisible is undefined + +- [#755](https://github.com/browserbase/stagehand/pull/755) [`ba687ab`](https://github.com/browserbase/stagehand/commit/ba687abdfb598f839ddfec0442d3d7b6b696b0a3) Thanks [@miguelg719](https://github.com/miguelg719)! - Fix context init error on undefined context + +- [#789](https://github.com/browserbase/stagehand/pull/789) [`c5ff8ce`](https://github.com/browserbase/stagehand/commit/c5ff8ce2d7467b70a450ca52bc3e03b15280ce1b) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix noisy useTextExtract deprecation log + +- [#757](https://github.com/browserbase/stagehand/pull/757) [`628e534`](https://github.com/browserbase/stagehand/commit/628e534ea6d7ca081bad6c32167c7d53d4772eed) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - optimize CDP calls when building hybrid tree + +- [#772](https://github.com/browserbase/stagehand/pull/772) [`64d331d`](https://github.com/browserbase/stagehand/commit/64d331dc2eba86675a8b148d361897f55f170703) Thanks [@miguelg719](https://github.com/miguelg719)! - Fixes an issue with the new tab intercepts for invalid urls + +- [#770](https://github.com/browserbase/stagehand/pull/770) [`d312a43`](https://github.com/browserbase/stagehand/commit/d312a43672fe2865abcf184a712a759a12f5b9d1) Thanks [@miguelg719](https://github.com/miguelg719)! - Removed default chromium flags that delay browser launching + +- [#753](https://github.com/browserbase/stagehand/pull/753) [`fbca400`](https://github.com/browserbase/stagehand/commit/fbca4003a547dc5eee0c0be5edc5e98c1f4d8c22) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix `stagehand.history` + +- [#745](https://github.com/browserbase/stagehand/pull/745) [`c54afab`](https://github.com/browserbase/stagehand/commit/c54afab0e43a2144eecbc56df7f33c5e444ceed5) Thanks [@miguelg719](https://github.com/miguelg719)! - Add an identifier for client language/runtime + +- [#768](https://github.com/browserbase/stagehand/pull/768) [`58b06eb`](https://github.com/browserbase/stagehand/commit/58b06eb2fdfb1a9cd84c03f46655ab0ea00ee07f) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix: page.evaluate: Execution context was destroyed, most likely because of a navigation + +- [#758](https://github.com/browserbase/stagehand/pull/758) [`98e1356`](https://github.com/browserbase/stagehand/commit/98e13566846a547003e4c9aebbe4f95eff653bba) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - rm unused functions + +- [#781](https://github.com/browserbase/stagehand/pull/781) [`8d239ce`](https://github.com/browserbase/stagehand/commit/8d239cec7a835d35243b2b00c3c00c1b66c05b5e) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix variable parsing issue with gpt-4.1 + +- [#761](https://github.com/browserbase/stagehand/pull/761) [`e1f7074`](https://github.com/browserbase/stagehand/commit/e1f7074be23c82ae897386d5e5e132ff8cb4120a) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - build xpaths on node side instead of using injected JS + +## 2.2.1 + +### Patch Changes + +- [#729](https://github.com/browserbase/stagehand/pull/729) [`fc24f84`](https://github.com/browserbase/stagehand/commit/fc24f848ee0f300182e88993dfe8d68025d69fcb) Thanks [@seanmcguire12](https://github.com/seanmcguire12)! - fix "failed to inject helper scripts" log on stagehand.close() diff --git a/sdk/stagehand-ts/lib/StagehandContext.ts b/sdk/stagehand-ts/lib/StagehandContext.ts new file mode 100644 index 0000000..e74b77e --- /dev/null +++ b/sdk/stagehand-ts/lib/StagehandContext.ts @@ -0,0 +1,208 @@ +import type { + BrowserContext as PlaywrightContext, + CDPSession, + Page as PlaywrightPage, +} from "playwright"; +import { Stagehand } from "./index"; +import { StagehandPage } from "./StagehandPage"; +import { Page } from "../types/page"; +import { EnhancedContext } from "../types/context"; +import { Protocol } from "devtools-protocol"; + +export class StagehandContext { + private readonly stagehand: Stagehand; + private readonly intContext: EnhancedContext; + private pageMap: WeakMap; + private activeStagehandPage: StagehandPage | null = null; + private readonly frameIdMap: Map = new Map(); + + private constructor(context: PlaywrightContext, stagehand: Stagehand) { + this.stagehand = stagehand; + this.pageMap = new WeakMap(); + + // Create proxy around the context + this.intContext = new Proxy(context, { + get: (target, prop) => { + if (prop === "newPage") { + return async (): Promise => { + const pwPage = await target.newPage(); + const stagehandPage = await this.createStagehandPage(pwPage); + await this.attachFrameNavigatedListener(pwPage); + // Set as active page when created + this.setActivePage(stagehandPage); + return stagehandPage.page; + }; + } + if (prop === "pages") { + return (): Page[] => { + const pwPages = target.pages(); + // Convert all pages to StagehandPages synchronously + return pwPages.map((pwPage: PlaywrightPage) => { + let stagehandPage = this.pageMap.get(pwPage); + if (!stagehandPage) { + // Create a new StagehandPage and store it in the map + stagehandPage = new StagehandPage( + pwPage, + this.stagehand, + this, + this.stagehand.llmClient, + this.stagehand.userProvidedInstructions, + this.stagehand.apiClient, + this.stagehand.waitForCaptchaSolves, + ); + this.pageMap.set(pwPage, stagehandPage); + } + return stagehandPage.page; + }); + }; + } + return target[prop as keyof PlaywrightContext]; + }, + }) as unknown as EnhancedContext; + } + + private async createStagehandPage( + page: PlaywrightPage, + ): Promise { + const stagehandPage = await new StagehandPage( + page, + this.stagehand, + this, + this.stagehand.llmClient, + this.stagehand.userProvidedInstructions, + this.stagehand.apiClient, + this.stagehand.waitForCaptchaSolves, + ).init(); + this.pageMap.set(page, stagehandPage); + return stagehandPage; + } + + static async init( + context: PlaywrightContext, + stagehand: Stagehand, + ): Promise { + const instance = new StagehandContext(context, stagehand); + context.on("page", async (pwPage) => { + await instance.handleNewPlaywrightPage(pwPage); + instance + .attachFrameNavigatedListener(pwPage) + .catch((err) => + stagehand.logger({ + category: "cdp", + message: `Failed to attach frameNavigated listener: ${err}`, + level: 0, + }), + ) + .finally(() => + instance.handleNewPlaywrightPage(pwPage).catch((err) => + stagehand.logger({ + category: "context", + message: `Failed to initialise new page: ${err}`, + level: 0, + }), + ), + ); + }); + + // Initialize existing pages + const existingPages = context.pages(); + for (const page of existingPages) { + const stagehandPage = await instance.createStagehandPage(page); + await instance.attachFrameNavigatedListener(page); + // Set the first page as active + if (!instance.activeStagehandPage) { + instance.setActivePage(stagehandPage); + } + } + + return instance; + } + public get frameIdLookup(): ReadonlyMap { + return this.frameIdMap; + } + + public registerFrameId(frameId: string, page: StagehandPage): void { + this.frameIdMap.set(frameId, page); + } + + public unregisterFrameId(frameId: string): void { + this.frameIdMap.delete(frameId); + } + + public getStagehandPageByFrameId(frameId: string): StagehandPage | undefined { + return this.frameIdMap.get(frameId); + } + + public get context(): EnhancedContext { + return this.intContext; + } + + public async getStagehandPage(page: PlaywrightPage): Promise { + let stagehandPage = this.pageMap.get(page); + if (!stagehandPage) { + stagehandPage = await this.createStagehandPage(page); + } + // Update active page when getting a page + this.setActivePage(stagehandPage); + return stagehandPage; + } + + public async getStagehandPages(): Promise { + const pwPages = this.intContext.pages(); + return Promise.all( + pwPages.map((page: PlaywrightPage) => this.getStagehandPage(page)), + ); + } + + public setActivePage(page: StagehandPage): void { + this.activeStagehandPage = page; + // Update the stagehand's active page reference + this.stagehand["setActivePage"](page); + } + + public getActivePage(): StagehandPage | null { + return this.activeStagehandPage; + } + + private async handleNewPlaywrightPage(pwPage: PlaywrightPage): Promise { + let stagehandPage = this.pageMap.get(pwPage); + if (!stagehandPage) { + stagehandPage = await this.createStagehandPage(pwPage); + } + this.setActivePage(stagehandPage); + } + + private async attachFrameNavigatedListener( + pwPage: PlaywrightPage, + ): Promise { + const shPage = this.pageMap.get(pwPage); + if (!shPage) return; + try { + const session: CDPSession = await this.intContext.newCDPSession(pwPage); + await session.send("Page.enable"); + + pwPage.once("close", () => { + if (shPage.frameId) this.unregisterFrameId(shPage.frameId); + }); + + session.on( + "Page.frameNavigated", + (evt: Protocol.Page.FrameNavigatedEvent): void => { + if (evt.frame.parentId) return; + if (evt.frame.id === shPage.frameId) return; + + const oldId = shPage.frameId; + if (oldId) this.unregisterFrameId(oldId); + this.registerFrameId(evt.frame.id, shPage); + shPage.updateRootFrameId(evt.frame.id); + }, + ); + } catch (error) { + this.stagehand.logger({ + category: "context", + message: `Failed to attach frameNavigated listener: ${error}`, + level: 0, + }); + } + } +} diff --git a/sdk/stagehand-ts/lib/StagehandPage.ts b/sdk/stagehand-ts/lib/StagehandPage.ts new file mode 100644 index 0000000..ff1661d --- /dev/null +++ b/sdk/stagehand-ts/lib/StagehandPage.ts @@ -0,0 +1,1184 @@ +import type { CDPSession, Page as PlaywrightPage, Frame } from "playwright"; +// import { selectors } from "playwright"; +import { z } from "zod/v3"; +import { Page, defaultExtractSchema } from "../types/page"; +import { + ExtractOptions, + ExtractResult, + ObserveOptions, + ObserveResult, +} from "../types/stagehand"; +import { StagehandAPI } from "./api"; +import { StagehandActHandler } from "./handlers/actHandler"; +import { StagehandExtractHandler } from "./handlers/extractHandler"; +import { StagehandObserveHandler } from "./handlers/observeHandler"; +import { ActOptions, ActResult, GotoOptions, Stagehand } from "./index"; +import { LLMClient } from "./llm/LLMClient"; +import { StagehandContext } from "./StagehandContext"; +import { EncodedId, EnhancedContext } from "../types/context"; +import { clearOverlays } from "./utils"; +import { + StagehandError, + StagehandNotInitializedError, + StagehandEnvironmentError, + CaptchaTimeoutError, + MissingLLMConfigurationError, + HandlerNotInitializedError, + StagehandDefaultError, + ExperimentalApiConflictError, +} from "../types/stagehandErrors"; +import { StagehandAPIError } from "@/types/stagehandApiErrors"; +import { scriptContent } from "@/lib/dom/build/scriptContent"; +import type { Protocol } from "devtools-protocol"; + +async function getCurrentRootFrameId(session: CDPSession): Promise { + const { frameTree } = (await session.send( + "Page.getFrameTree", + )) as Protocol.Page.GetFrameTreeResponse; + return frameTree.frame.id; +} + +/** ensure we register the custom selector only once per process */ +// let stagehandSelectorRegistered = false; + +export class StagehandPage { + public stagehand: Stagehand; + private rawPage: PlaywrightPage; + private intPage: Page; + private intContext: StagehandContext; + private actHandler: StagehandActHandler; + private extractHandler: StagehandExtractHandler; + private observeHandler: StagehandObserveHandler; + private llmClient: LLMClient; + private cdpClient: CDPSession | null = null; + private api: StagehandAPI; + private userProvidedInstructions?: string; + private waitForCaptchaSolves: boolean; + private initialized: boolean = false; + private isClosed: boolean = false; + private readonly cdpClients = new WeakMap< + PlaywrightPage | Frame, + CDPSession + >(); + private fidOrdinals: Map = new Map([ + [undefined, 0], + ]); + + private rootFrameId!: string; + + public get frameId(): string { + return this.rootFrameId; + } + + public updateRootFrameId(newId: string): void { + this.rootFrameId = newId; + } + + constructor( + page: PlaywrightPage, + stagehand: Stagehand, + context: StagehandContext, + llmClient: LLMClient, + userProvidedInstructions?: string, + api?: StagehandAPI, + waitForCaptchaSolves?: boolean, + ) { + if (stagehand.experimental && api) { + throw new ExperimentalApiConflictError(); + } + this.rawPage = page; + // Create a proxy to intercept all method calls and property access + this.intPage = new Proxy(page, { + get: (target: PlaywrightPage, prop: keyof PlaywrightPage) => { + // Special handling for our enhanced methods before initialization + if ( + !this.initialized && + (prop === ("act" as keyof Page) || + prop === ("extract" as keyof Page) || + prop === ("observe" as keyof Page) || + prop === ("on" as keyof Page)) + ) { + return () => { + throw new StagehandNotInitializedError(String(prop)); + }; + } + + const value = target[prop]; + // If the property is a function, wrap it to update active page before execution + if (typeof value === "function" && prop !== "on") { + return (...args: unknown[]) => value.apply(target, args); + } + return value; + }, + }) as Page; + + this.stagehand = stagehand; + this.intContext = context; + this.llmClient = llmClient; + this.api = api; + this.userProvidedInstructions = userProvidedInstructions; + this.waitForCaptchaSolves = waitForCaptchaSolves ?? false; + + if (this.llmClient) { + this.actHandler = new StagehandActHandler({ + logger: this.stagehand.logger, + stagehandPage: this, + selfHeal: this.stagehand.selfHeal, + experimental: this.stagehand.experimental, + }); + this.extractHandler = new StagehandExtractHandler({ + stagehand: this.stagehand, + logger: this.stagehand.logger, + stagehandPage: this, + userProvidedInstructions, + experimental: this.stagehand.experimental, + }); + this.observeHandler = new StagehandObserveHandler({ + stagehand: this.stagehand, + logger: this.stagehand.logger, + stagehandPage: this, + userProvidedInstructions, + experimental: this.stagehand.experimental, + }); + } + } + + public ordinalForFrameId(fid: string | undefined): number { + if (fid === undefined) return 0; + + const cached = this.fidOrdinals.get(fid); + if (cached !== undefined) return cached; + + const next: number = this.fidOrdinals.size; + this.fidOrdinals.set(fid, next); + return next; + } + + public encodeWithFrameId( + fid: string | undefined, + backendId: number, + ): EncodedId { + return `${this.ordinalForFrameId(fid)}-${backendId}` as EncodedId; + } + + public resetFrameOrdinals(): void { + this.fidOrdinals = new Map([[undefined, 0]]); + } + + private async ensureStagehandScript(): Promise { + try { + const injected = await this.rawPage.evaluate( + () => !!window.__stagehandInjected, + ); + + if (injected) return; + + const guardedScript = `if (!window.__stagehandInjected) { \ +window.__stagehandInjected = true; \ +${scriptContent} \ +}`; + + await this.rawPage.addInitScript({ content: guardedScript }); + await this.rawPage.evaluate(guardedScript); + } catch (err) { + if (!this.stagehand.isClosed) { + this.stagehand.log({ + category: "dom", + message: "Failed to inject Stagehand helper script", + level: 1, + auxiliary: { + error: { value: (err as Error).message, type: "string" }, + trace: { value: (err as Error).stack, type: "string" }, + }, + }); + throw err; + } + } + } + + /** Register the custom selector engine that pierces open/closed shadow roots. */ + // private async ensureStagehandSelectorEngine(): Promise { + // if (stagehandSelectorRegistered) return; + // stagehandSelectorRegistered = true; + + // await selectors.register("stagehand", () => { + // type Backdoor = { + // getClosedRoot?: (host: Element) => ShadowRoot | undefined; + // }; + + // function parseSelector(input: string): { name: string; value: string } { + // // Accept either: "abc123" → uses DEFAULT_ATTR + // // or explicitly: "data-__stagehand-id=abc123" + // const raw = input.trim(); + // const eq = raw.indexOf("="); + // if (eq === -1) { + // return { + // name: "data-__stagehand-id", + // value: raw.replace(/^["']|["']$/g, ""), + // }; + // } + // const name = raw.slice(0, eq).trim(); + // const value = raw + // .slice(eq + 1) + // .trim() + // .replace(/^["']|["']$/g, ""); + // return { name, value }; + // } + + // function pushChildren(node: Node, stack: Node[]): void { + // if (node.nodeType === Node.DOCUMENT_NODE) { + // const de = (node as Document).documentElement; + // if (de) stack.push(de); + // return; + // } + + // if (node.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { + // const frag = node as DocumentFragment; + // const hc = frag.children as HTMLCollection | undefined; + // if (hc && hc.length) { + // for (let i = hc.length - 1; i >= 0; i--) + // stack.push(hc[i] as Element); + // } else { + // const cn = frag.childNodes; + // for (let i = cn.length - 1; i >= 0; i--) stack.push(cn[i]); + // } + // return; + // } + + // if (node.nodeType === Node.ELEMENT_NODE) { + // const el = node as Element; + // for (let i = el.children.length - 1; i >= 0; i--) + // stack.push(el.children[i]); + // } + // } + + // function* traverseAllTrees( + // start: Node, + // ): Generator { + // const backdoor = window.__stagehand__ as Backdoor | undefined; + // const stack: Node[] = []; + + // if (start.nodeType === Node.DOCUMENT_NODE) { + // const de = (start as Document).documentElement; + // if (de) stack.push(de); + // } else { + // stack.push(start); + // } + + // while (stack.length) { + // const node = stack.pop()!; + // if (node.nodeType === Node.ELEMENT_NODE) { + // const el = node as Element; + // yield el; + + // // open shadow + // const open = el.shadowRoot as ShadowRoot | null; + // if (open) stack.push(open); + + // // closed shadow via backdoor + // const closed = backdoor?.getClosedRoot?.(el); + // if (closed) stack.push(closed); + // } + // pushChildren(node, stack); + // } + // } + + // return { + // query(root: Node, selector: string): Element | null { + // const { name, value } = parseSelector(selector); + // for (const el of traverseAllTrees(root)) { + // if (el.getAttribute(name) === value) return el; + // } + // return null; + // }, + // queryAll(root: Node, selector: string): Element[] { + // const { name, value } = parseSelector(selector); + // const out: Element[] = []; + // for (const el of traverseAllTrees(root)) { + // if (el.getAttribute(name) === value) out.push(el); + // } + // return out; + // }, + // }; + // }); + // } + + /** + * Waits for a captcha to be solved when using Browserbase environment. + * + * @param timeoutMs - Optional timeout in milliseconds. If provided, the promise will reject if the captcha solving hasn't started within the given time. + * @throws StagehandEnvironmentError if called in a LOCAL environment + * @throws CaptchaTimeoutError if the timeout is reached before captcha solving starts + * @returns Promise that resolves when the captcha is solved + */ + public async waitForCaptchaSolve(timeoutMs?: number) { + if (this.stagehand.env === "LOCAL") { + throw new StagehandEnvironmentError( + this.stagehand.env, + "BROWSERBASE", + "waitForCaptcha method", + ); + } + + this.stagehand.log({ + category: "captcha", + message: "Waiting for captcha", + level: 1, + }); + + return new Promise((resolve, reject) => { + let started = false; + let timeoutId: NodeJS.Timeout; + + if (timeoutMs) { + timeoutId = setTimeout(() => { + if (!started) { + reject(new CaptchaTimeoutError()); + } + }, timeoutMs); + } + + this.intPage.on("console", (msg) => { + if (msg.text() === "browserbase-solving-finished") { + this.stagehand.log({ + category: "captcha", + message: "Captcha solving finished", + level: 1, + }); + if (timeoutId) clearTimeout(timeoutId); + resolve(); + } else if (msg.text() === "browserbase-solving-started") { + started = true; + this.stagehand.log({ + category: "captcha", + message: "Captcha solving started", + level: 1, + }); + } + }); + }); + } + + async init(): Promise { + try { + const page = this.rawPage; + const stagehand = this.stagehand; + + // Create a proxy that updates active page on method calls + const handler = { + get: (target: PlaywrightPage, prop: string | symbol) => { + const value = target[prop as keyof PlaywrightPage]; + + // Inject-on-demand for evaluate + if ( + prop === "evaluate" || + prop === "evaluateHandle" || + prop === "$eval" || + prop === "$$eval" + ) { + return async (...args: unknown[]) => { + // Make sure helpers exist + await this.ensureStagehandScript(); + return (value as (...a: unknown[]) => unknown).apply( + target, + args, + ); + }; + } + + // Handle enhanced methods + if (prop === "act" || prop === "extract" || prop === "observe") { + if (!this.llmClient) { + return () => { + throw new MissingLLMConfigurationError(); + }; + } + + // Use type assertion to safely call the method with proper typing + type EnhancedMethod = ( + options: + | ActOptions + | ExtractOptions + | ObserveOptions, + ) => Promise< + ActResult | ExtractResult | ObserveResult[] + >; + + const method = this[prop as keyof StagehandPage] as EnhancedMethod; + return (options: unknown) => method.call(this, options); + } + + // Handle screenshots with CDP + if (prop === "screenshot" && this.stagehand.env === "BROWSERBASE") { + return async ( + options: { + type?: "png" | "jpeg"; + quality?: number; + fullPage?: boolean; + clip?: { x: number; y: number; width: number; height: number }; + omitBackground?: boolean; + } = {}, + ) => { + const cdpOptions: Record = { + format: options.type === "jpeg" ? "jpeg" : "png", + quality: options.quality, + clip: options.clip, + omitBackground: options.omitBackground, + fromSurface: true, + }; + + if (options.fullPage) { + cdpOptions.captureBeyondViewport = true; + } + + const data = await this.sendCDP<{ data: string }>( + "Page.captureScreenshot", + cdpOptions, + ); + + // Convert base64 to buffer + const buffer = Buffer.from(data.data, "base64"); + + return buffer; + }; + } + + // Handle goto specially + if (prop === "goto") { + const rawGoto: typeof target.goto = + Object.getPrototypeOf(target).goto.bind(target); + return async (url: string, options: GotoOptions) => { + try { + const result = this.api + ? await this.api.goto(url, { + ...options, + frameId: this.rootFrameId, + }) + : await rawGoto(url, options); + + this.stagehand.addToHistory( + "navigate", + { url, options }, + result, + ); + + if (this.waitForCaptchaSolves) { + try { + await this.waitForCaptchaSolve(1000); + } catch { + // ignore + } + } + + if (this.stagehand.debugDom) { + this.stagehand.log({ + category: "deprecation", + message: + "Warning: debugDom is not supported in this version of Stagehand", + level: 1, + }); + } + await target.waitForLoadState("domcontentloaded"); + await this._waitForSettledDom(); + + return result; + } catch (error) { + this.stagehand.log({ + category: "navigation", + message: `Failed to navigate to ${url}`, + level: 0, + auxiliary: { + error: { + value: (error as Error).message, + type: "string", + }, + url: { + value: url, + type: "string", + }, + }, + }); + throw error; + } + }; + } + + // Handle event listeners + if (prop === "on") { + return ( + event: keyof PlaywrightPage["on"], + listener: Parameters[1], + ) => { + if (event === "popup") { + return this.context.on("page", async (page: PlaywrightPage) => { + const newContext = await StagehandContext.init( + page.context(), + stagehand, + ); + const newStagehandPage = new StagehandPage( + page, + stagehand, + newContext, + this.llmClient, + ); + + await newStagehandPage.init(); + listener(newStagehandPage.page); + }); + } + this.intContext.setActivePage(this); + return target.on(event, listener); + }; + } + + // For all other method calls, update active page + if (typeof value === "function") { + return (...args: unknown[]) => value.apply(target, args); + } + + return value; + }, + }; + + const session = await this.getCDPClient(this.rawPage); + await session.send("Page.enable"); + + const rootId = await getCurrentRootFrameId(session); + this.updateRootFrameId(rootId); + this.intContext.registerFrameId(rootId, this); + + this.intPage = new Proxy(page, handler) as unknown as Page; + + // Ensure backdoor and selector engine are ready up front + // await this.ensureStagehandSelectorEngine(); + + this.initialized = true; + return this; + } catch (err: unknown) { + // if (err instanceof StagehandError || err instanceof StagehandAPIError) { + // throw err; + // } + // throw new StagehandDefaultError(err); + this.stagehand.log({ + category: "init", + message: `Error initializing stagehand page: ${err}`, + level: 0, + }); + throw err; + } + } + + public get page(): Page { + return this.intPage; + } + + public get context(): EnhancedContext { + return this.intContext.context; + } + + /** + * `_waitForSettledDom` waits until the DOM is settled, and therefore is + * ready for actions to be taken. + * + * **Definition of "settled"** + * • No in-flight network requests (except WebSocket / Server-Sent-Events). + * • That idle state lasts for at least **500 ms** (the "quiet-window"). + * + * **How it works** + * 1. Subscribes to CDP Network and Page events for the main target and all + * out-of-process iframes (via `Target.setAutoAttach { flatten:true }`). + * 2. Every time `Network.requestWillBeSent` fires, the request ID is added + * to an **`inflight`** `Set`. + * 3. When the request finishes—`loadingFinished`, `loadingFailed`, + * `requestServedFromCache`, or a *data:* response—the request ID is + * removed. + * 4. *Document* requests are also mapped **frameId → requestId**; when + * `Page.frameStoppedLoading` fires the corresponding Document request is + * removed immediately (covers iframes whose network events never close). + * 5. A **stalled-request sweep timer** runs every 500 ms. If a *Document* + * request has been open for ≥ 2 s it is forcibly removed; this prevents + * ad/analytics iframes from blocking the wait forever. + * 6. When `inflight` becomes empty the helper starts a 500 ms timer. + * If no new request appears before the timer fires, the promise + * resolves → **DOM is considered settled**. + * 7. A global guard (`timeoutMs` or `stagehand.domSettleTimeoutMs`, + * default ≈ 30 s) ensures we always resolve; if it fires we log how many + * requests were still outstanding. + * + * @param timeoutMs – Optional hard cap (ms). Defaults to + * `this.stagehand.domSettleTimeoutMs`. + */ + public async _waitForSettledDom(timeoutMs?: number): Promise { + const timeout = timeoutMs ?? this.stagehand.domSettleTimeoutMs; + const client = await this.getCDPClient(); + + const hasDoc = !!(await this.page.title().catch(() => false)); + if (!hasDoc) await this.page.waitForLoadState("domcontentloaded"); + + await client.send("Network.enable"); + await client.send("Page.enable"); + await client.send("Target.setAutoAttach", { + autoAttach: true, + waitForDebuggerOnStart: false, + flatten: true, + filter: [ + { type: "worker", exclude: true }, + { type: "shared_worker", exclude: true }, + ], + }); + + return new Promise((resolve) => { + const inflight = new Set(); + const meta = new Map(); + const docByFrame = new Map(); + + let quietTimer: NodeJS.Timeout | null = null; + let stalledRequestSweepTimer: NodeJS.Timeout | null = null; + + const clearQuiet = () => { + if (quietTimer) { + clearTimeout(quietTimer); + quietTimer = null; + } + }; + + const maybeQuiet = () => { + if (inflight.size === 0 && !quietTimer) + quietTimer = setTimeout(() => resolveDone(), 500); + }; + + const finishReq = (id: string) => { + if (!inflight.delete(id)) return; + meta.delete(id); + for (const [fid, rid] of docByFrame) + if (rid === id) docByFrame.delete(fid); + clearQuiet(); + maybeQuiet(); + }; + + const onRequest = (p: Protocol.Network.RequestWillBeSentEvent) => { + if (p.type === "WebSocket" || p.type === "EventSource") return; + + inflight.add(p.requestId); + meta.set(p.requestId, { url: p.request.url, start: Date.now() }); + + if (p.type === "Document" && p.frameId) + docByFrame.set(p.frameId, p.requestId); + + clearQuiet(); + }; + + const onFinish = (p: { requestId: string }) => finishReq(p.requestId); + const onCached = (p: { requestId: string }) => finishReq(p.requestId); + const onDataUrl = (p: Protocol.Network.ResponseReceivedEvent) => + p.response.url.startsWith("data:") && finishReq(p.requestId); + + const onFrameStop = (f: Protocol.Page.FrameStoppedLoadingEvent) => { + const id = docByFrame.get(f.frameId); + if (id) finishReq(id); + }; + + client.on("Network.requestWillBeSent", onRequest); + client.on("Network.loadingFinished", onFinish); + client.on("Network.loadingFailed", onFinish); + client.on("Network.requestServedFromCache", onCached); + client.on("Network.responseReceived", onDataUrl); + client.on("Page.frameStoppedLoading", onFrameStop); + + stalledRequestSweepTimer = setInterval(() => { + const now = Date.now(); + for (const [id, m] of meta) { + if (now - m.start > 2_000) { + inflight.delete(id); + meta.delete(id); + this.stagehand.log({ + category: "dom", + message: "⏳ forcing completion of stalled iframe document", + level: 2, + auxiliary: { + url: { + value: m.url.slice(0, 120), + type: "string", + }, + }, + }); + } + } + maybeQuiet(); + }, 500); + + maybeQuiet(); + + const guard = setTimeout(() => { + if (inflight.size) + this.stagehand.log({ + category: "dom", + message: + "⚠️ DOM-settle timeout reached – network requests still pending", + level: 2, + auxiliary: { + count: { + value: inflight.size.toString(), + type: "integer", + }, + }, + }); + resolveDone(); + }, timeout); + + const resolveDone = () => { + client.off("Network.requestWillBeSent", onRequest); + client.off("Network.loadingFinished", onFinish); + client.off("Network.loadingFailed", onFinish); + client.off("Network.requestServedFromCache", onCached); + client.off("Network.responseReceived", onDataUrl); + client.off("Page.frameStoppedLoading", onFrameStop); + if (quietTimer) clearTimeout(quietTimer); + if (stalledRequestSweepTimer) clearInterval(stalledRequestSweepTimer); + clearTimeout(guard); + resolve(); + }; + }); + } + + async act( + actionOrOptions: string | ActOptions | ObserveResult, + ): Promise { + try { + if (!this.actHandler) { + throw new HandlerNotInitializedError("Act"); + } + + await clearOverlays(this.page); + + // If actionOrOptions is an ObserveResult, we call actFromObserveResult. + // We need to ensure there is both a selector and a method in the ObserveResult. + if (typeof actionOrOptions === "object" && actionOrOptions !== null) { + // If it has selector AND method => treat as ObserveResult + if ("selector" in actionOrOptions && "method" in actionOrOptions) { + const observeResult = actionOrOptions as ObserveResult; + + if (this.api) { + const result = await this.api.act({ + ...observeResult, + frameId: this.rootFrameId, + }); + this.stagehand.addToHistory("act", observeResult, result); + return result; + } + + // validate observeResult.method, etc. + return this.actHandler.actFromObserveResult(observeResult); + } else { + // If it's an object but no selector/method, + // check that it's truly ActOptions (i.e., has an `action` field). + if (!("action" in actionOrOptions)) { + throw new StagehandError( + "Invalid argument. Valid arguments are: a string, an ActOptions object, " + + "or an ObserveResult WITH 'selector' and 'method' fields.", + ); + } + } + } else if (typeof actionOrOptions === "string") { + // Convert string to ActOptions + actionOrOptions = { action: actionOrOptions }; + } else { + throw new StagehandError( + "Invalid argument: you may have called act with an empty ObserveResult.\n" + + "Valid arguments are: a string, an ActOptions object, or an ObserveResult " + + "WITH 'selector' and 'method' fields.", + ); + } + + const { action, modelName, modelClientOptions } = actionOrOptions; + + if (this.api) { + const opts = { ...actionOrOptions, frameId: this.rootFrameId }; + const result = await this.api.act(opts); + this.stagehand.addToHistory("act", actionOrOptions, result); + return result; + } + + const requestId = Math.random().toString(36).substring(2); + const llmClient: LLMClient = modelName + ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) + : this.llmClient; + + this.stagehand.log({ + category: "act", + message: "running act", + level: 1, + auxiliary: { + action: { + value: action, + type: "string", + }, + requestId: { + value: requestId, + type: "string", + }, + modelName: { + value: llmClient.modelName, + type: "string", + }, + }, + }); + + const result = await this.actHandler.observeAct( + actionOrOptions, + this.observeHandler, + llmClient, + requestId, + ); + this.stagehand.addToHistory("act", actionOrOptions, result); + return result; + } catch (err: unknown) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + } + + async extract( + instructionOrOptions?: string | ExtractOptions, + ): Promise> { + try { + if (!this.extractHandler) { + throw new HandlerNotInitializedError("Extract"); + } + + await clearOverlays(this.page); + + // check if user called extract() with no arguments + if (!instructionOrOptions) { + let result: ExtractResult; + if (this.api) { + result = await this.api.extract({ frameId: this.rootFrameId }); + } else { + result = await this.extractHandler.extract(); + } + this.stagehand.addToHistory("extract", instructionOrOptions, result); + return result; + } + + const options: ExtractOptions = + typeof instructionOrOptions === "string" + ? { + instruction: instructionOrOptions, + schema: defaultExtractSchema as T, + } + : instructionOrOptions.schema + ? instructionOrOptions + : { + ...instructionOrOptions, + schema: defaultExtractSchema as T, + }; + + const { + instruction, + schema, + modelName, + modelClientOptions, + domSettleTimeoutMs, + useTextExtract, + selector, + iframes, + } = options; + + if (this.api) { + const opts = { ...options, frameId: this.rootFrameId }; + const result = await this.api.extract(opts); + this.stagehand.addToHistory("extract", instructionOrOptions, result); + return result; + } + + const requestId = Math.random().toString(36).substring(2); + const llmClient = modelName + ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) + : this.llmClient; + + this.stagehand.log({ + category: "extract", + message: "running extract", + level: 1, + auxiliary: { + instruction: { + value: instruction, + type: "string", + }, + requestId: { + value: requestId, + type: "string", + }, + modelName: { + value: llmClient.modelName, + type: "string", + }, + }, + }); + + const result = await this.extractHandler + .extract({ + instruction, + schema, + llmClient, + requestId, + domSettleTimeoutMs, + useTextExtract, + selector, + iframes, + }) + .catch((e) => { + this.stagehand.log({ + category: "extract", + message: "error extracting", + level: 1, + auxiliary: { + error: { + value: e.message, + type: "string", + }, + trace: { + value: e.stack, + type: "string", + }, + }, + }); + + if (this.stagehand.enableCaching) { + this.stagehand.llmProvider.cleanRequestCache(requestId); + } + + throw e; + }); + + this.stagehand.addToHistory("extract", instructionOrOptions, result); + + return result; + } catch (err: unknown) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + } + + async observe( + instructionOrOptions?: string | ObserveOptions, + ): Promise { + try { + if (!this.observeHandler) { + throw new HandlerNotInitializedError("Observe"); + } + + await clearOverlays(this.page); + + const options: ObserveOptions = + typeof instructionOrOptions === "string" + ? { instruction: instructionOrOptions } + : instructionOrOptions || {}; + + const { + instruction, + modelName, + modelClientOptions, + domSettleTimeoutMs, + returnAction = true, + onlyVisible, + drawOverlay, + iframes, + } = options; + + if (this.api) { + const opts = { ...options, frameId: this.rootFrameId }; + const result = await this.api.observe(opts); + this.stagehand.addToHistory("observe", instructionOrOptions, result); + return result; + } + + const requestId = Math.random().toString(36).substring(2); + const llmClient = modelName + ? this.stagehand.llmProvider.getClient(modelName, modelClientOptions) + : this.llmClient; + + this.stagehand.log({ + category: "observe", + message: "running observe", + level: 1, + auxiliary: { + instruction: { + value: instruction, + type: "string", + }, + requestId: { + value: requestId, + type: "string", + }, + modelName: { + value: llmClient.modelName, + type: "string", + }, + ...(onlyVisible !== undefined && { + onlyVisible: { + value: onlyVisible ? "true" : "false", + type: "boolean", + }, + }), + }, + }); + + const result = await this.observeHandler + .observe({ + instruction, + llmClient, + requestId, + domSettleTimeoutMs, + returnAction, + onlyVisible, + drawOverlay, + iframes, + }) + .catch((e) => { + this.stagehand.log({ + category: "observe", + message: "error observing", + level: 1, + auxiliary: { + error: { + value: e.message, + type: "string", + }, + trace: { + value: e.stack, + type: "string", + }, + requestId: { + value: requestId, + type: "string", + }, + instruction: { + value: instruction, + type: "string", + }, + }, + }); + + if (this.stagehand.enableCaching) { + this.stagehand.llmProvider.cleanRequestCache(requestId); + } + + throw e; + }); + + this.stagehand.addToHistory("observe", instructionOrOptions, result); + + return result; + } catch (err: unknown) { + if (err instanceof StagehandError || err instanceof StagehandAPIError) { + throw err; + } + throw new StagehandDefaultError(err); + } + } + + /** + * Get or create a CDP session for the given target. + * @param target The Page or (OOPIF) Frame you want to talk to. + */ + async getCDPClient( + target: PlaywrightPage | Frame = this.page, + ): Promise { + // Check if the page is closed + if (this.isClosed) { + throw new Error("Cannot create CDP session: page is closed"); + } + + const cached = this.cdpClients.get(target); + if (cached) return cached; + + try { + // Check if the target is still valid + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (!target || (target as any)._closed) { + throw new Error("Target page or frame is closed"); + } + + const session = await this.context.newCDPSession(target); + this.cdpClients.set(target, session); + return session; + } catch (err) { + const msg = (err as Error).message ?? ""; + + // Check for closed target errors + if ( + msg.includes("No target with given id found") || + msg.includes("Target page, context or browser has been closed") || + msg.includes("Protocol error") + ) { + this.isClosed = true; + throw new Error(`CDP session creation failed: ${msg}`); + } + + // Fallback for same-process iframes + if (msg.includes("does not have a separate CDP session")) { + // Re-use / create the top-level session instead + const rootSession = await this.getCDPClient(this.page); + // cache the alias so we don't try again for this frame + this.cdpClients.set(target, rootSession); + return rootSession; + } + throw err; + } + } + + /** + * Send a CDP command to the chosen DevTools target. + * + * @param method Any valid CDP method, e.g. `"DOM.getDocument"`. + * @param params Command parameters (optional). + * @param target A `Page` or OOPIF `Frame`. Defaults to the main page. + * + * @typeParam T Expected result shape (defaults to `unknown`). + */ + async sendCDP( + method: string, + params: Record = {}, + target?: PlaywrightPage | Frame, + ): Promise { + try { + const client = await this.getCDPClient(target ?? this.page); + + return client.send( + method as Parameters[0], + params as Parameters[1], + ) as Promise; + } catch (err) { + const msg = (err as Error).message ?? ""; + if ( + msg.includes("CDP session creation failed") || + msg.includes("page is closed") + ) { + // Return a default value or throw a more specific error + throw new Error(`CDP command failed: ${method} - ${msg}`); + } + throw err; + } + } + + /** Enable a CDP domain (e.g. `"Network"` or `"DOM"`) on the chosen target. */ + async enableCDP( + domain: string, + target?: PlaywrightPage | Frame, + ): Promise { + await this.sendCDP(`${domain}.enable`, {}, target); + } + + /** Disable a CDP domain on the chosen target. */ + async disableCDP( + domain: string, + target?: PlaywrightPage | Frame, + ): Promise { + await this.sendCDP(`${domain}.disable`, {}, target); + } +} diff --git a/sdk/stagehand-ts/lib/a11y/utils.ts b/sdk/stagehand-ts/lib/a11y/utils.ts new file mode 100644 index 0000000..6be8c3f --- /dev/null +++ b/sdk/stagehand-ts/lib/a11y/utils.ts @@ -0,0 +1,1346 @@ +import { + AccessibilityNode, + TreeResult, + AXNode, + DOMNode, + BackendIdMaps, + CdpFrameTree, + FrameOwnerResult, + FrameSnapshot, + CombinedA11yResult, + EncodedId, + RichNode, + ID_PATTERN, + CdpFrame, +} from "../../types/context"; +import { StagehandPage } from "../StagehandPage"; +import { LogLine } from "../../types/log"; +import { + ContentFrameNotFoundError, + StagehandDomProcessError, + StagehandElementNotFoundError, + StagehandIframeError, + XPathResolutionError, +} from "@/types/stagehandErrors"; +import { CDPSession, Frame } from "playwright"; + +const IFRAME_STEP_RE = /iframe\[\d+]$/i; +const PUA_START = 0xe000; +const PUA_END = 0xf8ff; + +const NBSP_CHARS = new Set([0x00a0, 0x202f, 0x2007, 0xfeff]); + +const WORLD_NAME = "stagehand-world"; + +/** + * Clean a string by removing private-use unicode characters, normalizing whitespace, + * and trimming the result. + * + * @param input - The text to clean, potentially containing PUA and NBSP characters. + * @returns A cleaned string with PUA characters removed, NBSP variants collapsed, + * consecutive spaces merged, and leading/trailing whitespace trimmed. + */ +export function cleanText(input: string): string { + let out = ""; + let prevWasSpace = false; + + for (let i = 0; i < input.length; i++) { + const code = input.charCodeAt(i); + + // Skip private-use area glyphs + if (code >= PUA_START && code <= PUA_END) { + continue; + } + + // Convert NBSP-family characters to a single space, collapsing repeats + if (NBSP_CHARS.has(code)) { + if (!prevWasSpace) { + out += " "; + prevWasSpace = true; + } + continue; + } + + // Append the character and update space tracker + out += input[i]; + prevWasSpace = input[i] === " "; + } + + // Trim leading/trailing spaces before returning + return out.trim(); +} + +/** + * Generate a human-readable, indented outline of an accessibility node tree. + * + * @param node - The accessibility node to format, optionally with an encodedId. + * @param level - The current depth level for indentation (used internally). + * @returns A string representation of the node and its descendants, with one node per line. + */ +export function formatSimplifiedTree( + node: AccessibilityNode & { encodedId?: EncodedId }, + level = 0, +): string { + // Compute indentation based on depth level + const indent = " ".repeat(level); + + // Use encodedId if available, otherwise fallback to nodeId + const idLabel = node.encodedId ?? node.nodeId; + + // Prepare the formatted name segment if present + const namePart = node.name ? `: ${cleanText(node.name)}` : ""; + + // Build current line and recurse into child nodes + const currentLine = `${indent}[${idLabel}] ${node.role}${namePart}\n`; + const childrenLines = + node.children + ?.map((c) => formatSimplifiedTree(c as typeof node, level + 1)) + .join("") ?? ""; + + return currentLine + childrenLines; +} + +const lowerCache = new Map(); + +/** + * Memoized lowercase conversion for strings to avoid repeated .toLowerCase() calls. + * + * @param raw - The original string to convert. + * @returns The lowercase version of the input string, cached for future reuse. + */ +const lc = (raw: string): string => { + let v = lowerCache.get(raw); + if (!v) { + v = raw.toLowerCase(); + lowerCache.set(raw, v); + } + return v; +}; + +/** + * Build mappings from CDP backendNodeIds to HTML tag names and relative XPaths. + * + * @param experimental - Whether to use experimental behaviour. + * @param sp - The StagehandPage wrapper for Playwright and CDP calls. + * @param targetFrame - Optional Playwright.Frame whose DOM subtree to map; defaults to main frame. + * @returns A Promise resolving to BackendIdMaps containing tagNameMap and xpathMap. + */ +export async function buildBackendIdMaps( + experimental: boolean, + sp: StagehandPage, + targetFrame?: Frame, +): Promise { + // 0. choose CDP session + let session: CDPSession; + if (!targetFrame || targetFrame === sp.page.mainFrame()) { + session = await sp.getCDPClient(); + } else { + try { + session = await sp.context.newCDPSession(targetFrame); // OOPIF + } catch { + session = await sp.getCDPClient(); // same-proc iframe + } + } + + await sp.enableCDP( + "DOM", + session === (await sp.getCDPClient()) ? undefined : targetFrame, + ); + + try { + // 1. full DOM tree + const { root } = (await session.send("DOM.getDocument", { + depth: -1, + pierce: true, + })) as { root: DOMNode }; + + // 2. pick start node + root frame-id + let startNode: DOMNode = root; + let rootFid: string | undefined = + targetFrame && (await getCDPFrameId(sp, targetFrame)); + + if ( + targetFrame && + targetFrame !== sp.page.mainFrame() && + session === (await sp.getCDPClient()) + ) { + // same-proc iframe: walk down to its contentDocument + const frameId = rootFid!; + const { backendNodeId } = await sp.sendCDP<{ backendNodeId: number }>( + "DOM.getFrameOwner", + { frameId }, + ); + + let iframeNode: DOMNode | undefined; + const locate = (n: DOMNode): boolean => { + if (experimental) { + if (n.backendNodeId === backendNodeId) { + iframeNode = n; + return true; + } + if (n.shadowRoots?.some(locate)) return true; + if (n.children?.some(locate)) return true; + if (n.contentDocument && locate(n.contentDocument)) return true; + return false; + } else { + if (n.backendNodeId === backendNodeId) return (iframeNode = n), true; + return ( + (n.children?.some(locate) ?? false) || + (n.contentDocument ? locate(n.contentDocument) : false) + ); + } + }; + + if (!locate(root) || !iframeNode?.contentDocument) { + throw new Error("iframe element or its contentDocument not found"); + } + startNode = iframeNode.contentDocument; + rootFid = iframeNode.contentDocument.frameId ?? frameId; + } + + // 3. DFS walk: fill maps + const tagNameMap: Record = {}; + const xpathMap: Record = {}; + + interface StackEntry { + node: DOMNode; + path: string; + fid: string | undefined; // CDP frame-id of this node’s doc + } + const stack: StackEntry[] = [{ node: startNode, path: "", fid: rootFid }]; + const seen = new Set(); + + const joinStep = (base: string, step: string): string => + base.endsWith("//") ? `${base}${step}` : `${base}/${step}`; + + while (stack.length) { + const { node, path, fid } = stack.pop()!; + + if (!node.backendNodeId) continue; + const enc = sp.encodeWithFrameId(fid, node.backendNodeId); + if (seen.has(enc)) continue; + seen.add(enc); + + tagNameMap[enc] = lc(String(node.nodeName)); + xpathMap[enc] = path; + + // recurse into sub-document if