@langchain/google-common 0.0.27 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/auth.cjs CHANGED
@@ -3,6 +3,16 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ensureAuthOptionScopes = exports.aiPlatformScope = exports.ApiKeyGoogleAuth = exports.GoogleAbstractedFetchClient = void 0;
4
4
  const stream_js_1 = require("./utils/stream.cjs");
5
5
  class GoogleAbstractedFetchClient {
6
+ async _buildData(res, opts) {
7
+ switch (opts.responseType) {
8
+ case "json":
9
+ return res.json();
10
+ case "stream":
11
+ return new stream_js_1.ReadableJsonStream(res.body);
12
+ default:
13
+ return res.blob();
14
+ }
15
+ }
6
16
  async _request(url, opts, additionalHeaders) {
7
17
  if (url == null)
8
18
  throw new Error("Missing URL");
@@ -15,20 +25,31 @@ class GoogleAbstractedFetchClient {
15
25
  },
16
26
  };
17
27
  if (opts.data !== undefined) {
18
- fetchOptions.body = JSON.stringify(opts.data);
28
+ if (typeof opts.data === "string") {
29
+ fetchOptions.body = opts.data;
30
+ }
31
+ else {
32
+ fetchOptions.body = JSON.stringify(opts.data);
33
+ }
19
34
  }
20
35
  const res = await fetch(url, fetchOptions);
21
36
  if (!res.ok) {
22
37
  const resText = await res.text();
23
38
  const error = new Error(`Google request failed with status code ${res.status}: ${resText}`);
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
39
+ /* eslint-disable @typescript-eslint/no-explicit-any */
25
40
  error.response = res;
41
+ error.details = {
42
+ url,
43
+ opts,
44
+ fetchOptions,
45
+ result: res,
46
+ };
47
+ /* eslint-enable @typescript-eslint/no-explicit-any */
26
48
  throw error;
27
49
  }
50
+ const data = await this._buildData(res, opts);
28
51
  return {
29
- data: opts.responseType === "json"
30
- ? await res.json()
31
- : new stream_js_1.ReadableJsonStream(res.body),
52
+ data,
32
53
  config: {},
33
54
  status: res.status,
34
55
  statusText: res.statusText,
package/dist/auth.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { GooglePlatformType } from "./types.js";
2
- export type GoogleAbstractedClientOpsMethod = "GET" | "POST";
3
- export type GoogleAbstractedClientOpsResponseType = "json" | "stream";
2
+ export type GoogleAbstractedClientOpsMethod = "GET" | "POST" | "DELETE";
3
+ export type GoogleAbstractedClientOpsResponseType = "json" | "stream" | "blob";
4
4
  export type GoogleAbstractedClientOps = {
5
5
  url?: string;
6
6
  method?: GoogleAbstractedClientOpsMethod;
@@ -17,6 +17,7 @@ export declare abstract class GoogleAbstractedFetchClient implements GoogleAbstr
17
17
  abstract get clientType(): string;
18
18
  abstract getProjectId(): Promise<string>;
19
19
  abstract request(opts: GoogleAbstractedClientOps): unknown;
20
+ _buildData(res: Response, opts: GoogleAbstractedClientOps): Promise<any>;
20
21
  _request(url: string | undefined, opts: GoogleAbstractedClientOps, additionalHeaders: Record<string, string>): Promise<{
21
22
  data: any;
22
23
  config: {};
package/dist/auth.js CHANGED
@@ -1,5 +1,15 @@
1
1
  import { ReadableJsonStream } from "./utils/stream.js";
2
2
  export class GoogleAbstractedFetchClient {
3
+ async _buildData(res, opts) {
4
+ switch (opts.responseType) {
5
+ case "json":
6
+ return res.json();
7
+ case "stream":
8
+ return new ReadableJsonStream(res.body);
9
+ default:
10
+ return res.blob();
11
+ }
12
+ }
3
13
  async _request(url, opts, additionalHeaders) {
4
14
  if (url == null)
5
15
  throw new Error("Missing URL");
@@ -12,20 +22,31 @@ export class GoogleAbstractedFetchClient {
12
22
  },
13
23
  };
14
24
  if (opts.data !== undefined) {
15
- fetchOptions.body = JSON.stringify(opts.data);
25
+ if (typeof opts.data === "string") {
26
+ fetchOptions.body = opts.data;
27
+ }
28
+ else {
29
+ fetchOptions.body = JSON.stringify(opts.data);
30
+ }
16
31
  }
17
32
  const res = await fetch(url, fetchOptions);
18
33
  if (!res.ok) {
19
34
  const resText = await res.text();
20
35
  const error = new Error(`Google request failed with status code ${res.status}: ${resText}`);
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
36
+ /* eslint-disable @typescript-eslint/no-explicit-any */
22
37
  error.response = res;
38
+ error.details = {
39
+ url,
40
+ opts,
41
+ fetchOptions,
42
+ result: res,
43
+ };
44
+ /* eslint-enable @typescript-eslint/no-explicit-any */
23
45
  throw error;
24
46
  }
47
+ const data = await this._buildData(res, opts);
25
48
  return {
26
- data: opts.responseType === "json"
27
- ? await res.json()
28
- : new ReadableJsonStream(res.body),
49
+ data,
29
50
  config: {},
30
51
  status: res.status,
31
52
  statusText: res.statusText,
@@ -53,10 +53,10 @@ class ChatConnection extends connection_js_1.AbstractGoogleLLMConnection {
53
53
  }
54
54
  return true;
55
55
  }
56
- formatContents(input, _parameters) {
57
- return input
58
- .map((msg, i) => (0, gemini_js_1.baseMessageToContent)(msg, input[i - 1], this.useSystemInstruction))
59
- .reduce((acc, cur) => {
56
+ async formatContents(input, _parameters) {
57
+ const inputPromises = input.map((msg, i) => this.api.baseMessageToContent(msg, input[i - 1], this.useSystemInstruction));
58
+ const inputs = await Promise.all(inputPromises);
59
+ return inputs.reduce((acc, cur) => {
60
60
  // Filter out the system content
61
61
  if (cur.every((content) => content.role === "system")) {
62
62
  return acc;
@@ -76,24 +76,25 @@ class ChatConnection extends connection_js_1.AbstractGoogleLLMConnection {
76
76
  return acc;
77
77
  }, []);
78
78
  }
79
- formatSystemInstruction(input, _parameters) {
79
+ async formatSystemInstruction(input, _parameters) {
80
80
  if (!this.useSystemInstruction) {
81
81
  return {};
82
82
  }
83
83
  let ret = {};
84
- input.forEach((message, index) => {
84
+ for (let index = 0; index < input.length; index += 1) {
85
+ const message = input[index];
85
86
  if (message._getType() === "system") {
86
87
  // For system types, we only want it if it is the first message,
87
88
  // if it appears anywhere else, it should be an error.
88
89
  if (index === 0) {
89
90
  // eslint-disable-next-line prefer-destructuring
90
- ret = (0, gemini_js_1.baseMessageToContent)(message, undefined, true)[0];
91
+ ret = (await this.api.baseMessageToContent(message, undefined, true))[0];
91
92
  }
92
93
  else {
93
94
  throw new Error("System messages are only permitted as the first passed message.");
94
95
  }
95
96
  }
96
- });
97
+ }
97
98
  return ret;
98
99
  }
99
100
  }
@@ -273,7 +274,7 @@ class ChatGoogleBase extends chat_models_1.BaseChatModel {
273
274
  };
274
275
  }
275
276
  const response = await this.connection.request(messages, parameters, options);
276
- const ret = (0, gemini_js_1.safeResponseToChatResult)(response, this.safetyHandler);
277
+ const ret = this.connection.api.safeResponseToChatResult(response, this.safetyHandler);
277
278
  await runManager?.handleLLMNewToken(ret.generations[0].text);
278
279
  return ret;
279
280
  }
@@ -300,7 +301,7 @@ class ChatGoogleBase extends chat_models_1.BaseChatModel {
300
301
  };
301
302
  }
302
303
  const chunk = output !== null
303
- ? (0, gemini_js_1.safeResponseToChatGeneration)({ data: output }, this.safetyHandler)
304
+ ? this.connection.api.safeResponseToChatGeneration({ data: output }, this.safetyHandler)
304
305
  : new outputs_1.ChatGenerationChunk({
305
306
  text: "",
306
307
  generationInfo: { finishReason: "stop" },
@@ -10,19 +10,19 @@ import { AsyncCaller } from "@langchain/core/utils/async_caller";
10
10
  import { GoogleAIBaseLLMInput, GoogleAIModelParams, GoogleAISafetySetting, GoogleConnectionParams, GooglePlatformType, GeminiContent, GoogleAIBaseLanguageModelCallOptions } from "./types.js";
11
11
  import { AbstractGoogleLLMConnection } from "./connection.js";
12
12
  import { GoogleAbstractedClient } from "./auth.js";
13
- import type { GoogleBaseLLMInput, GoogleAISafetyHandler, GoogleAISafetyParams, GoogleAIToolType } from "./types.js";
13
+ import type { GoogleBaseLLMInput, GoogleAISafetyHandler, GoogleAISafetyParams, GoogleAIToolType, GeminiAPIConfig } from "./types.js";
14
14
  declare class ChatConnection<AuthOptions> extends AbstractGoogleLLMConnection<BaseMessage[], AuthOptions> {
15
15
  convertSystemMessageToHumanContent: boolean | undefined;
16
16
  constructor(fields: GoogleAIBaseLLMInput<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient, streaming: boolean);
17
17
  get useSystemInstruction(): boolean;
18
18
  get computeUseSystemInstruction(): boolean;
19
- formatContents(input: BaseMessage[], _parameters: GoogleAIModelParams): GeminiContent[];
20
- formatSystemInstruction(input: BaseMessage[], _parameters: GoogleAIModelParams): GeminiContent;
19
+ formatContents(input: BaseMessage[], _parameters: GoogleAIModelParams): Promise<GeminiContent[]>;
20
+ formatSystemInstruction(input: BaseMessage[], _parameters: GoogleAIModelParams): Promise<GeminiContent>;
21
21
  }
22
22
  /**
23
23
  * Input to chat model class.
24
24
  */
25
- export interface ChatGoogleBaseInput<AuthOptions> extends BaseChatModelParams, GoogleConnectionParams<AuthOptions>, GoogleAIModelParams, GoogleAISafetyParams, Pick<GoogleAIBaseLanguageModelCallOptions, "streamUsage"> {
25
+ export interface ChatGoogleBaseInput<AuthOptions> extends BaseChatModelParams, GoogleConnectionParams<AuthOptions>, GoogleAIModelParams, GoogleAISafetyParams, GeminiAPIConfig, Pick<GoogleAIBaseLanguageModelCallOptions, "streamUsage"> {
26
26
  }
27
27
  /**
28
28
  * Integration with a Google chat model.
@@ -7,7 +7,7 @@ import { JsonOutputKeyToolsParser } from "@langchain/core/output_parsers/openai_
7
7
  import { concat } from "@langchain/core/utils/stream";
8
8
  import { convertToGeminiTools, copyAIModelParams, copyAndValidateModelParamsInto, } from "./utils/common.js";
9
9
  import { AbstractGoogleLLMConnection } from "./connection.js";
10
- import { baseMessageToContent, safeResponseToChatGeneration, safeResponseToChatResult, DefaultGeminiSafetyHandler, } from "./utils/gemini.js";
10
+ import { DefaultGeminiSafetyHandler } from "./utils/gemini.js";
11
11
  import { ApiKeyGoogleAuth } from "./auth.js";
12
12
  import { ensureParams } from "./utils/failed_handler.js";
13
13
  import { zodToGeminiParameters } from "./utils/zod_to_gemini_parameters.js";
@@ -50,10 +50,10 @@ class ChatConnection extends AbstractGoogleLLMConnection {
50
50
  }
51
51
  return true;
52
52
  }
53
- formatContents(input, _parameters) {
54
- return input
55
- .map((msg, i) => baseMessageToContent(msg, input[i - 1], this.useSystemInstruction))
56
- .reduce((acc, cur) => {
53
+ async formatContents(input, _parameters) {
54
+ const inputPromises = input.map((msg, i) => this.api.baseMessageToContent(msg, input[i - 1], this.useSystemInstruction));
55
+ const inputs = await Promise.all(inputPromises);
56
+ return inputs.reduce((acc, cur) => {
57
57
  // Filter out the system content
58
58
  if (cur.every((content) => content.role === "system")) {
59
59
  return acc;
@@ -73,24 +73,25 @@ class ChatConnection extends AbstractGoogleLLMConnection {
73
73
  return acc;
74
74
  }, []);
75
75
  }
76
- formatSystemInstruction(input, _parameters) {
76
+ async formatSystemInstruction(input, _parameters) {
77
77
  if (!this.useSystemInstruction) {
78
78
  return {};
79
79
  }
80
80
  let ret = {};
81
- input.forEach((message, index) => {
81
+ for (let index = 0; index < input.length; index += 1) {
82
+ const message = input[index];
82
83
  if (message._getType() === "system") {
83
84
  // For system types, we only want it if it is the first message,
84
85
  // if it appears anywhere else, it should be an error.
85
86
  if (index === 0) {
86
87
  // eslint-disable-next-line prefer-destructuring
87
- ret = baseMessageToContent(message, undefined, true)[0];
88
+ ret = (await this.api.baseMessageToContent(message, undefined, true))[0];
88
89
  }
89
90
  else {
90
91
  throw new Error("System messages are only permitted as the first passed message.");
91
92
  }
92
93
  }
93
- });
94
+ }
94
95
  return ret;
95
96
  }
96
97
  }
@@ -270,7 +271,7 @@ export class ChatGoogleBase extends BaseChatModel {
270
271
  };
271
272
  }
272
273
  const response = await this.connection.request(messages, parameters, options);
273
- const ret = safeResponseToChatResult(response, this.safetyHandler);
274
+ const ret = this.connection.api.safeResponseToChatResult(response, this.safetyHandler);
274
275
  await runManager?.handleLLMNewToken(ret.generations[0].text);
275
276
  return ret;
276
277
  }
@@ -297,7 +298,7 @@ export class ChatGoogleBase extends BaseChatModel {
297
298
  };
298
299
  }
299
300
  const chunk = output !== null
300
- ? safeResponseToChatGeneration({ data: output }, this.safetyHandler)
301
+ ? this.connection.api.safeResponseToChatGeneration({ data: output }, this.safetyHandler)
301
302
  : new ChatGenerationChunk({
302
303
  text: "",
303
304
  generationInfo: { finishReason: "stop" },
@@ -1,9 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.AbstractGoogleLLMConnection = exports.GoogleAIConnection = exports.GoogleHostConnection = exports.GoogleConnection = void 0;
3
+ exports.AbstractGoogleLLMConnection = exports.GoogleAIConnection = exports.GoogleRawConnection = exports.GoogleHostConnection = exports.GoogleConnection = void 0;
4
4
  const env_1 = require("@langchain/core/utils/env");
5
5
  const function_calling_1 = require("@langchain/core/utils/function_calling");
6
6
  const zod_to_gemini_parameters_js_1 = require("./utils/zod_to_gemini_parameters.cjs");
7
+ const index_js_1 = require("./utils/index.cjs");
7
8
  class GoogleConnection {
8
9
  constructor(caller, client, streaming) {
9
10
  Object.defineProperty(this, "caller", {
@@ -53,12 +54,18 @@ class GoogleConnection {
53
54
  async _moduleName() {
54
55
  return this.constructor.name;
55
56
  }
56
- async _request(data, options) {
57
+ async additionalHeaders() {
58
+ return {};
59
+ }
60
+ async _buildOpts(data, _options, requestHeaders = {}) {
57
61
  const url = await this.buildUrl();
58
62
  const method = this.buildMethod();
59
63
  const infoHeaders = (await this._clientInfoHeaders()) ?? {};
64
+ const additionalHeaders = (await this.additionalHeaders()) ?? {};
60
65
  const headers = {
61
66
  ...infoHeaders,
67
+ ...additionalHeaders,
68
+ ...requestHeaders,
62
69
  };
63
70
  const opts = {
64
71
  url,
@@ -74,6 +81,10 @@ class GoogleConnection {
74
81
  else {
75
82
  opts.responseType = "json";
76
83
  }
84
+ return opts;
85
+ }
86
+ async _request(data, options, requestHeaders = {}) {
87
+ const opts = await this._buildOpts(data, options, requestHeaders);
77
88
  const callResponse = await this.caller.callWithOptions({ signal: options?.signal }, async () => this.client.request(opts));
78
89
  const response = callResponse; // Done for typecast safety, I guess
79
90
  return response;
@@ -127,6 +138,14 @@ class GoogleHostConnection extends GoogleConnection {
127
138
  }
128
139
  }
129
140
  exports.GoogleHostConnection = GoogleHostConnection;
141
+ class GoogleRawConnection extends GoogleHostConnection {
142
+ async _buildOpts(data, _options, requestHeaders = {}) {
143
+ const opts = await super._buildOpts(data, _options, requestHeaders);
144
+ opts.responseType = "blob";
145
+ return opts;
146
+ }
147
+ }
148
+ exports.GoogleRawConnection = GoogleRawConnection;
130
149
  class GoogleAIConnection extends GoogleHostConnection {
131
150
  constructor(fields, caller, client, streaming) {
132
151
  super(fields, caller, client, streaming);
@@ -148,9 +167,17 @@ class GoogleAIConnection extends GoogleHostConnection {
148
167
  writable: true,
149
168
  value: void 0
150
169
  });
170
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
171
+ Object.defineProperty(this, "api", {
172
+ enumerable: true,
173
+ configurable: true,
174
+ writable: true,
175
+ value: void 0
176
+ }); // FIXME: Make this a real type
151
177
  this.client = client;
152
178
  this.modelName = fields?.model ?? fields?.modelName ?? this.model;
153
179
  this.model = this.modelName;
180
+ this.api = (0, index_js_1.getGeminiAPI)(fields);
154
181
  }
155
182
  get modelFamily() {
156
183
  if (this.model.startsWith("gemini")) {
@@ -188,7 +215,7 @@ class GoogleAIConnection extends GoogleHostConnection {
188
215
  }
189
216
  }
190
217
  async request(input, parameters, options) {
191
- const data = this.formatData(input, parameters);
218
+ const data = await this.formatData(input, parameters);
192
219
  const response = await this._request(data, options);
193
220
  return response;
194
221
  }
@@ -219,7 +246,7 @@ class AbstractGoogleLLMConnection extends GoogleAIConnection {
219
246
  formatSafetySettings(_input, parameters) {
220
247
  return parameters.safetySettings ?? [];
221
248
  }
222
- formatSystemInstruction(_input, _parameters) {
249
+ async formatSystemInstruction(_input, _parameters) {
223
250
  return {};
224
251
  }
225
252
  structuredToolToFunctionDeclaration(tool) {
@@ -265,13 +292,13 @@ class AbstractGoogleLLMConnection extends GoogleAIConnection {
265
292
  },
266
293
  };
267
294
  }
268
- formatData(input, parameters) {
269
- const contents = this.formatContents(input, parameters);
295
+ async formatData(input, parameters) {
296
+ const contents = await this.formatContents(input, parameters);
270
297
  const generationConfig = this.formatGenerationConfig(input, parameters);
271
298
  const tools = this.formatTools(input, parameters);
272
299
  const toolConfig = this.formatToolConfig(parameters);
273
300
  const safetySettings = this.formatSafetySettings(input, parameters);
274
- const systemInstruction = this.formatSystemInstruction(input, parameters);
301
+ const systemInstruction = await this.formatSystemInstruction(input, parameters);
275
302
  const ret = {
276
303
  contents,
277
304
  generationConfig,
@@ -1,8 +1,8 @@
1
1
  import { BaseLanguageModelCallOptions } from "@langchain/core/language_models/base";
2
2
  import { AsyncCaller, AsyncCallerCallOptions } from "@langchain/core/utils/async_caller";
3
3
  import { StructuredToolParams } from "@langchain/core/tools";
4
- import type { GoogleAIBaseLLMInput, GoogleConnectionParams, GoogleLLMModelFamily, GooglePlatformType, GoogleResponse, GoogleLLMResponse, GeminiContent, GeminiGenerationConfig, GeminiRequest, GeminiSafetySetting, GeminiTool, GeminiFunctionDeclaration, GoogleAIModelRequestParams } from "./types.js";
5
- import { GoogleAbstractedClient, GoogleAbstractedClientOpsMethod } from "./auth.js";
4
+ import type { GoogleAIBaseLLMInput, GoogleConnectionParams, GoogleLLMModelFamily, GooglePlatformType, GoogleResponse, GoogleLLMResponse, GeminiContent, GeminiGenerationConfig, GeminiRequest, GeminiSafetySetting, GeminiTool, GeminiFunctionDeclaration, GoogleAIModelRequestParams, GoogleRawResponse } from "./types.js";
5
+ import { GoogleAbstractedClient, GoogleAbstractedClientOps, GoogleAbstractedClientOpsMethod } from "./auth.js";
6
6
  export declare abstract class GoogleConnection<CallOptions extends AsyncCallerCallOptions, ResponseType extends GoogleResponse> {
7
7
  caller: AsyncCaller;
8
8
  client: GoogleAbstractedClient;
@@ -16,7 +16,9 @@ export declare abstract class GoogleConnection<CallOptions extends AsyncCallerCa
16
16
  clientLibraryVersion: string;
17
17
  }>;
18
18
  _moduleName(): Promise<string>;
19
- _request(data: unknown | undefined, options: CallOptions): Promise<ResponseType>;
19
+ additionalHeaders(): Promise<Record<string, string>>;
20
+ _buildOpts(data: unknown | undefined, _options: CallOptions, requestHeaders?: Record<string, string>): Promise<GoogleAbstractedClientOps>;
21
+ _request(data: unknown | undefined, options: CallOptions, requestHeaders?: Record<string, string>): Promise<ResponseType>;
20
22
  }
21
23
  export declare abstract class GoogleHostConnection<CallOptions extends AsyncCallerCallOptions, ResponseType extends GoogleResponse, AuthOptions> extends GoogleConnection<CallOptions, ResponseType> implements GoogleConnectionParams<AuthOptions> {
22
24
  platformType: GooglePlatformType | undefined;
@@ -28,10 +30,14 @@ export declare abstract class GoogleHostConnection<CallOptions extends AsyncCall
28
30
  get computedPlatformType(): GooglePlatformType;
29
31
  buildMethod(): GoogleAbstractedClientOpsMethod;
30
32
  }
33
+ export declare abstract class GoogleRawConnection<CallOptions extends AsyncCallerCallOptions, AuthOptions> extends GoogleHostConnection<CallOptions, GoogleRawResponse, AuthOptions> {
34
+ _buildOpts(data: unknown | undefined, _options: CallOptions, requestHeaders?: Record<string, string>): Promise<GoogleAbstractedClientOps>;
35
+ }
31
36
  export declare abstract class GoogleAIConnection<CallOptions extends AsyncCallerCallOptions, InputType, AuthOptions, ResponseType extends GoogleResponse> extends GoogleHostConnection<CallOptions, ResponseType, AuthOptions> implements GoogleAIBaseLLMInput<AuthOptions> {
32
37
  model: string;
33
38
  modelName: string;
34
39
  client: GoogleAbstractedClient;
40
+ api: any;
35
41
  constructor(fields: GoogleAIBaseLLMInput<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient, streaming?: boolean);
36
42
  get modelFamily(): GoogleLLMModelFamily;
37
43
  get computedPlatformType(): GooglePlatformType;
@@ -39,19 +45,19 @@ export declare abstract class GoogleAIConnection<CallOptions extends AsyncCaller
39
45
  buildUrlGenerativeLanguage(): Promise<string>;
40
46
  buildUrlVertex(): Promise<string>;
41
47
  buildUrl(): Promise<string>;
42
- abstract formatData(input: InputType, parameters: GoogleAIModelRequestParams): unknown;
43
- request(input: InputType, parameters: GoogleAIModelRequestParams, options: CallOptions): Promise<ResponseType>;
48
+ abstract formatData(input: InputType, parameters: GoogleAIModelRequestParams): Promise<unknown>;
49
+ request(input: InputType, parameters: GoogleAIModelRequestParams, options: CallOptions): Promise<GoogleResponse>;
44
50
  }
45
51
  export declare abstract class AbstractGoogleLLMConnection<MessageType, AuthOptions> extends GoogleAIConnection<BaseLanguageModelCallOptions, MessageType, AuthOptions, GoogleLLMResponse> {
46
52
  buildUrlMethodGemini(): Promise<string>;
47
53
  buildUrlMethod(): Promise<string>;
48
- abstract formatContents(input: MessageType, parameters: GoogleAIModelRequestParams): GeminiContent[];
54
+ abstract formatContents(input: MessageType, parameters: GoogleAIModelRequestParams): Promise<GeminiContent[]>;
49
55
  formatGenerationConfig(_input: MessageType, parameters: GoogleAIModelRequestParams): GeminiGenerationConfig;
50
56
  formatSafetySettings(_input: MessageType, parameters: GoogleAIModelRequestParams): GeminiSafetySetting[];
51
- formatSystemInstruction(_input: MessageType, _parameters: GoogleAIModelRequestParams): GeminiContent;
57
+ formatSystemInstruction(_input: MessageType, _parameters: GoogleAIModelRequestParams): Promise<GeminiContent>;
52
58
  structuredToolToFunctionDeclaration(tool: StructuredToolParams): GeminiFunctionDeclaration;
53
59
  structuredToolsToGeminiTools(tools: StructuredToolParams[]): GeminiTool[];
54
60
  formatTools(_input: MessageType, parameters: GoogleAIModelRequestParams): GeminiTool[];
55
61
  formatToolConfig(parameters: GoogleAIModelRequestParams): GeminiRequest["toolConfig"] | undefined;
56
- formatData(input: MessageType, parameters: GoogleAIModelRequestParams): GeminiRequest;
62
+ formatData(input: MessageType, parameters: GoogleAIModelRequestParams): Promise<GeminiRequest>;
57
63
  }
@@ -1,6 +1,7 @@
1
1
  import { getRuntimeEnvironment } from "@langchain/core/utils/env";
2
2
  import { isLangChainTool } from "@langchain/core/utils/function_calling";
3
3
  import { zodToGeminiParameters } from "./utils/zod_to_gemini_parameters.js";
4
+ import { getGeminiAPI } from "./utils/index.js";
4
5
  export class GoogleConnection {
5
6
  constructor(caller, client, streaming) {
6
7
  Object.defineProperty(this, "caller", {
@@ -50,12 +51,18 @@ export class GoogleConnection {
50
51
  async _moduleName() {
51
52
  return this.constructor.name;
52
53
  }
53
- async _request(data, options) {
54
+ async additionalHeaders() {
55
+ return {};
56
+ }
57
+ async _buildOpts(data, _options, requestHeaders = {}) {
54
58
  const url = await this.buildUrl();
55
59
  const method = this.buildMethod();
56
60
  const infoHeaders = (await this._clientInfoHeaders()) ?? {};
61
+ const additionalHeaders = (await this.additionalHeaders()) ?? {};
57
62
  const headers = {
58
63
  ...infoHeaders,
64
+ ...additionalHeaders,
65
+ ...requestHeaders,
59
66
  };
60
67
  const opts = {
61
68
  url,
@@ -71,6 +78,10 @@ export class GoogleConnection {
71
78
  else {
72
79
  opts.responseType = "json";
73
80
  }
81
+ return opts;
82
+ }
83
+ async _request(data, options, requestHeaders = {}) {
84
+ const opts = await this._buildOpts(data, options, requestHeaders);
74
85
  const callResponse = await this.caller.callWithOptions({ signal: options?.signal }, async () => this.client.request(opts));
75
86
  const response = callResponse; // Done for typecast safety, I guess
76
87
  return response;
@@ -122,6 +133,13 @@ export class GoogleHostConnection extends GoogleConnection {
122
133
  return "POST";
123
134
  }
124
135
  }
136
+ export class GoogleRawConnection extends GoogleHostConnection {
137
+ async _buildOpts(data, _options, requestHeaders = {}) {
138
+ const opts = await super._buildOpts(data, _options, requestHeaders);
139
+ opts.responseType = "blob";
140
+ return opts;
141
+ }
142
+ }
125
143
  export class GoogleAIConnection extends GoogleHostConnection {
126
144
  constructor(fields, caller, client, streaming) {
127
145
  super(fields, caller, client, streaming);
@@ -143,9 +161,17 @@ export class GoogleAIConnection extends GoogleHostConnection {
143
161
  writable: true,
144
162
  value: void 0
145
163
  });
164
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
165
+ Object.defineProperty(this, "api", {
166
+ enumerable: true,
167
+ configurable: true,
168
+ writable: true,
169
+ value: void 0
170
+ }); // FIXME: Make this a real type
146
171
  this.client = client;
147
172
  this.modelName = fields?.model ?? fields?.modelName ?? this.model;
148
173
  this.model = this.modelName;
174
+ this.api = getGeminiAPI(fields);
149
175
  }
150
176
  get modelFamily() {
151
177
  if (this.model.startsWith("gemini")) {
@@ -183,7 +209,7 @@ export class GoogleAIConnection extends GoogleHostConnection {
183
209
  }
184
210
  }
185
211
  async request(input, parameters, options) {
186
- const data = this.formatData(input, parameters);
212
+ const data = await this.formatData(input, parameters);
187
213
  const response = await this._request(data, options);
188
214
  return response;
189
215
  }
@@ -213,7 +239,7 @@ export class AbstractGoogleLLMConnection extends GoogleAIConnection {
213
239
  formatSafetySettings(_input, parameters) {
214
240
  return parameters.safetySettings ?? [];
215
241
  }
216
- formatSystemInstruction(_input, _parameters) {
242
+ async formatSystemInstruction(_input, _parameters) {
217
243
  return {};
218
244
  }
219
245
  structuredToolToFunctionDeclaration(tool) {
@@ -259,13 +285,13 @@ export class AbstractGoogleLLMConnection extends GoogleAIConnection {
259
285
  },
260
286
  };
261
287
  }
262
- formatData(input, parameters) {
263
- const contents = this.formatContents(input, parameters);
288
+ async formatData(input, parameters) {
289
+ const contents = await this.formatContents(input, parameters);
264
290
  const generationConfig = this.formatGenerationConfig(input, parameters);
265
291
  const tools = this.formatTools(input, parameters);
266
292
  const toolConfig = this.formatToolConfig(parameters);
267
293
  const safetySettings = this.formatSafetySettings(input, parameters);
268
- const systemInstruction = this.formatSystemInstruction(input, parameters);
294
+ const systemInstruction = await this.formatSystemInstruction(input, parameters);
269
295
  const ret = {
270
296
  contents,
271
297
  generationConfig,
@@ -19,7 +19,7 @@ class EmbeddingsConnection extends connection_js_1.GoogleAIConnection {
19
19
  async buildUrlMethod() {
20
20
  return "predict";
21
21
  }
22
- formatData(input, parameters) {
22
+ async formatData(input, parameters) {
23
23
  return {
24
24
  instances: input,
25
25
  parameters,
@@ -79,7 +79,9 @@ class BaseGoogleEmbeddings extends embeddings_1.Embeddings {
79
79
  const options = {};
80
80
  const responses = await Promise.all(instanceChunks.map((instances) => this.connection.request(instances, parameters, options)));
81
81
  const result = responses
82
- ?.map((response) => response?.data?.predictions?.map((result) => result.embeddings.values) ?? [])
82
+ ?.map((response) => response?.data?.predictions?.map(
83
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
84
+ (result) => result.embeddings?.values) ?? [])
83
85
  .flat() ?? [];
84
86
  return result;
85
87
  }
@@ -16,7 +16,7 @@ class EmbeddingsConnection extends GoogleAIConnection {
16
16
  async buildUrlMethod() {
17
17
  return "predict";
18
18
  }
19
- formatData(input, parameters) {
19
+ async formatData(input, parameters) {
20
20
  return {
21
21
  instances: input,
22
22
  parameters,
@@ -76,7 +76,9 @@ export class BaseGoogleEmbeddings extends Embeddings {
76
76
  const options = {};
77
77
  const responses = await Promise.all(instanceChunks.map((instances) => this.connection.request(instances, parameters, options)));
78
78
  const result = responses
79
- ?.map((response) => response?.data?.predictions?.map((result) => result.embeddings.values) ?? [])
79
+ ?.map((response) => response?.data?.predictions?.map(
80
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
81
+ (result) => result.embeddings?.values) ?? [])
80
82
  .flat() ?? [];
81
83
  return result;
82
84
  }