@langchain/google 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/CHANGELOG.md +11 -0
- package/LICENSE +21 -0
- package/README.md +97 -0
- package/dist/_virtual/rolldown_runtime.cjs +25 -0
- package/dist/chat_models/api-types.d.cts +1506 -0
- package/dist/chat_models/api-types.d.ts +1506 -0
- package/dist/chat_models/base.cjs +445 -0
- package/dist/chat_models/base.cjs.map +1 -0
- package/dist/chat_models/base.d.cts +319 -0
- package/dist/chat_models/base.d.ts +319 -0
- package/dist/chat_models/base.js +442 -0
- package/dist/chat_models/base.js.map +1 -0
- package/dist/chat_models/index.cjs +23 -0
- package/dist/chat_models/index.cjs.map +1 -0
- package/dist/chat_models/index.d.cts +39 -0
- package/dist/chat_models/index.d.ts +39 -0
- package/dist/chat_models/index.js +22 -0
- package/dist/chat_models/index.js.map +1 -0
- package/dist/chat_models/node.cjs +35 -0
- package/dist/chat_models/node.cjs.map +1 -0
- package/dist/chat_models/node.d.cts +13 -0
- package/dist/chat_models/node.d.ts +13 -0
- package/dist/chat_models/node.js +34 -0
- package/dist/chat_models/node.js.map +1 -0
- package/dist/chat_models/profiles.cjs +373 -0
- package/dist/chat_models/profiles.cjs.map +1 -0
- package/dist/chat_models/profiles.js +372 -0
- package/dist/chat_models/profiles.js.map +1 -0
- package/dist/chat_models/types.d.cts +250 -0
- package/dist/chat_models/types.d.ts +250 -0
- package/dist/clients/index.cjs +219 -0
- package/dist/clients/index.cjs.map +1 -0
- package/dist/clients/index.d.cts +49 -0
- package/dist/clients/index.d.ts +49 -0
- package/dist/clients/index.js +217 -0
- package/dist/clients/index.js.map +1 -0
- package/dist/clients/node.cjs +327 -0
- package/dist/clients/node.cjs.map +1 -0
- package/dist/clients/node.d.cts +59 -0
- package/dist/clients/node.d.ts +59 -0
- package/dist/clients/node.js +325 -0
- package/dist/clients/node.js.map +1 -0
- package/dist/const.cjs +13 -0
- package/dist/const.cjs.map +1 -0
- package/dist/const.js +9 -0
- package/dist/const.js.map +1 -0
- package/dist/converters/messages.cjs +697 -0
- package/dist/converters/messages.cjs.map +1 -0
- package/dist/converters/messages.js +691 -0
- package/dist/converters/messages.js.map +1 -0
- package/dist/converters/params.cjs +205 -0
- package/dist/converters/params.cjs.map +1 -0
- package/dist/converters/params.js +202 -0
- package/dist/converters/params.js.map +1 -0
- package/dist/converters/tools.cjs +356 -0
- package/dist/converters/tools.cjs.map +1 -0
- package/dist/converters/tools.js +353 -0
- package/dist/converters/tools.js.map +1 -0
- package/dist/index.cjs +7 -0
- package/dist/index.d.cts +3 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +4 -0
- package/dist/node.cjs +7 -0
- package/dist/node.d.cts +3 -0
- package/dist/node.d.ts +3 -0
- package/dist/node.js +4 -0
- package/dist/utils/errors.cjs +543 -0
- package/dist/utils/errors.cjs.map +1 -0
- package/dist/utils/errors.js +535 -0
- package/dist/utils/errors.js.map +1 -0
- package/dist/utils/gcp-auth.cjs +188 -0
- package/dist/utils/gcp-auth.cjs.map +1 -0
- package/dist/utils/gcp-auth.d.cts +43 -0
- package/dist/utils/gcp-auth.d.ts +43 -0
- package/dist/utils/gcp-auth.js +186 -0
- package/dist/utils/gcp-auth.js.map +1 -0
- package/dist/utils/handler.cjs +67 -0
- package/dist/utils/handler.cjs.map +1 -0
- package/dist/utils/handler.d.cts +34 -0
- package/dist/utils/handler.d.ts +34 -0
- package/dist/utils/handler.js +64 -0
- package/dist/utils/handler.js.map +1 -0
- package/dist/utils/misc.cjs +10 -0
- package/dist/utils/misc.cjs.map +1 -0
- package/dist/utils/misc.d.cts +14 -0
- package/dist/utils/misc.d.ts +14 -0
- package/dist/utils/misc.js +9 -0
- package/dist/utils/misc.js.map +1 -0
- package/dist/utils/stream.cjs +26 -0
- package/dist/utils/stream.cjs.map +1 -0
- package/dist/utils/stream.js +25 -0
- package/dist/utils/stream.js.map +1 -0
- package/package.json +96 -0
|
@@ -0,0 +1,250 @@
|
|
|
1
|
+
import { Prettify } from "../utils/misc.js";
|
|
2
|
+
import { Gemini } from "./api-types.js";
|
|
3
|
+
import { BindToolsInput } from "@langchain/core/language_models/chat_models";
|
|
4
|
+
import { InteropZodType } from "@langchain/core/utils/types";
|
|
5
|
+
|
|
6
|
+
//#region src/chat_models/types.d.ts
|
|
7
|
+
interface ChatGoogleFields {
|
|
8
|
+
/**
|
|
9
|
+
* The temperature is used for sampling during response generation, which
|
|
10
|
+
* occurs when topP and topK are applied. Temperature controls the degree of
|
|
11
|
+
* randomness in token selection. Lower temperatures are good for prompts that
|
|
12
|
+
* require a less open-ended or creative response, while higher temperatures
|
|
13
|
+
* can lead to more diverse or creative results.
|
|
14
|
+
*
|
|
15
|
+
* Specify a lower value for less random responses and a higher value for more
|
|
16
|
+
* random responses.
|
|
17
|
+
*/
|
|
18
|
+
temperature?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Top-P changes how the model selects tokens for output. Tokens are selected
|
|
21
|
+
* from the most probable to least probable until the sum of their
|
|
22
|
+
* probabilities equals the top-P value.
|
|
23
|
+
*
|
|
24
|
+
* Specify a lower value for less random responses and a higher value for more
|
|
25
|
+
* random responses.
|
|
26
|
+
*/
|
|
27
|
+
topP?: number;
|
|
28
|
+
/**
|
|
29
|
+
* Top-K changes how the model selects tokens for output. A top-K of 1 means
|
|
30
|
+
* the selected token is the most probable among all tokens in the model's
|
|
31
|
+
* vocabulary (also called greedy decoding), while a top-K of 3 means that the
|
|
32
|
+
* next token is selected from among the 3 most probable tokens (using
|
|
33
|
+
* temperature).
|
|
34
|
+
*/
|
|
35
|
+
topK?: number;
|
|
36
|
+
/**
|
|
37
|
+
* Maximum number of tokens that can be generated in the response. A token is
|
|
38
|
+
* approximately four characters. 100 tokens correspond to roughly 60-80 words.
|
|
39
|
+
* Specify a lower value for shorter responses and a higher value for
|
|
40
|
+
* potentially longer responses.
|
|
41
|
+
*/
|
|
42
|
+
maxOutputTokens?: number;
|
|
43
|
+
/**
|
|
44
|
+
* Positive values penalize tokens that already appear in the generated text,
|
|
45
|
+
* increasing the probability of generating more diverse content.
|
|
46
|
+
*/
|
|
47
|
+
presencePenalty?: number;
|
|
48
|
+
/**
|
|
49
|
+
* Positive values penalize tokens that repeatedly appear in the generated
|
|
50
|
+
* text, decreasing the probability of repeating content.
|
|
51
|
+
*/
|
|
52
|
+
frequencyPenalty?: number;
|
|
53
|
+
/**
|
|
54
|
+
* Specifies a list of strings that tells the model to stop generating text if
|
|
55
|
+
* one of the strings is encountered in the response. If a string appears
|
|
56
|
+
* multiple times in the response, then the response truncates where it's
|
|
57
|
+
* first encountered. The strings are case-sensitive.
|
|
58
|
+
*/
|
|
59
|
+
stopSequences?: string[];
|
|
60
|
+
/**
|
|
61
|
+
* When seed is fixed to a specific value, the model makes a best effort to
|
|
62
|
+
* provide the same response for repeated requests. Deterministic output isn't
|
|
63
|
+
* guaranteed. Also, changing the model or parameter settings, such as the
|
|
64
|
+
* temperature, can cause variations in the response even when you use the
|
|
65
|
+
* same seed value. By default, a random seed value is used.
|
|
66
|
+
*/
|
|
67
|
+
seed?: number;
|
|
68
|
+
/**
|
|
69
|
+
* If true, returns the log probabilities of the tokens that were chosen by
|
|
70
|
+
* the model at each step. By default, this parameter is set to false.
|
|
71
|
+
*/
|
|
72
|
+
responseLogprobs?: boolean;
|
|
73
|
+
/**
|
|
74
|
+
* Returns the log probabilities of the top candidate tokens at each generation
|
|
75
|
+
* step. The model's chosen token might not be the same as the top candidate
|
|
76
|
+
* token at each step. Specify the number of candidates to return by using an
|
|
77
|
+
* integer value in the range of 1-20.
|
|
78
|
+
*/
|
|
79
|
+
logprobs?: number;
|
|
80
|
+
/**
|
|
81
|
+
* Per request settings for blocking unsafe content
|
|
82
|
+
*/
|
|
83
|
+
safetySettings?: Prettify<Gemini.SafetySetting>[];
|
|
84
|
+
/**
|
|
85
|
+
* Configuration for the model's thinking process
|
|
86
|
+
*/
|
|
87
|
+
thinkingConfig?: Prettify<Gemini.ThinkingConfig>;
|
|
88
|
+
/**
|
|
89
|
+
* The schema that the generated response should match.
|
|
90
|
+
* Can be a Zod schema or a JSON Schema object.
|
|
91
|
+
* When set, the response will be structured according to this schema
|
|
92
|
+
* and `responseMimeType` will automatically be set to "application/json".
|
|
93
|
+
*/
|
|
94
|
+
responseSchema?: InteropZodType | Record<string, unknown>;
|
|
95
|
+
/**
|
|
96
|
+
* A list of tools the model may use to generate the next response.
|
|
97
|
+
* Can be LangChain tools, OpenAI tools, or Gemini function declarations.
|
|
98
|
+
*/
|
|
99
|
+
tools?: BindToolsInput[];
|
|
100
|
+
/**
|
|
101
|
+
* The requested modalities of the response.
|
|
102
|
+
* Represents the set of modalities that the model can return.
|
|
103
|
+
* An empty list is equivalent to requesting only text.
|
|
104
|
+
*/
|
|
105
|
+
responseModalities?: Prettify<Gemini.GenerativeLanguageModality>[];
|
|
106
|
+
/**
|
|
107
|
+
* If true, enables enhanced civic answers feature.
|
|
108
|
+
*/
|
|
109
|
+
enableEnhancedCivicAnswers?: boolean;
|
|
110
|
+
/**
|
|
111
|
+
* Speech generation configuration.
|
|
112
|
+
* You can use either Google's definition of the speech configuration,
|
|
113
|
+
* or a simplified version we've defined (which can be as simple
|
|
114
|
+
* as the name of a pre-defined voice).
|
|
115
|
+
*/
|
|
116
|
+
speechConfig?: Prettify<Gemini.SpeechConfig> | SimplifiedSpeechConfig;
|
|
117
|
+
/**
|
|
118
|
+
* Configuration for image generation.
|
|
119
|
+
*/
|
|
120
|
+
imageConfig?: Prettify<Gemini.ImageConfig>;
|
|
121
|
+
/**
|
|
122
|
+
* Media resolution for input media processing.
|
|
123
|
+
*/
|
|
124
|
+
mediaResolution?: Prettify<Gemini.MediaResolution>;
|
|
125
|
+
/**
|
|
126
|
+
* The number of reasoning tokens that the model should generate.
|
|
127
|
+
* If explicitly set, then the reasoning blocks will be returned.
|
|
128
|
+
*/
|
|
129
|
+
maxReasoningTokens?: number;
|
|
130
|
+
/**
|
|
131
|
+
* An alias for `maxReasoningTokens` for compatibility.
|
|
132
|
+
*/
|
|
133
|
+
thinkingBudget?: number;
|
|
134
|
+
/**
|
|
135
|
+
* An alias for `maxReasoningTokens` under Gemini 2.5 or
|
|
136
|
+
* the primary thinking/reasoning setting for Gemini 3.
|
|
137
|
+
* If explicitly set, then the reasoning blocks will be returned.
|
|
138
|
+
*/
|
|
139
|
+
reasoningEffort?: Gemini.ThinkingLevel;
|
|
140
|
+
/**
|
|
141
|
+
* An alias for `reasoningEffort` for compatibility.
|
|
142
|
+
*/
|
|
143
|
+
thinkingLevel?: Gemini.ThinkingLevel;
|
|
144
|
+
}
|
|
145
|
+
declare module "./api-types.js" {
|
|
146
|
+
namespace Gemini {
|
|
147
|
+
namespace Part {
|
|
148
|
+
type CodeExecutionResult = Pick<Gemini.Part, "codeExecutionResult">;
|
|
149
|
+
type ExecutableCode = Pick<Gemini.Part, "executableCode">;
|
|
150
|
+
type FileData = Pick<Gemini.Part, "fileData" | "videoMetadata">;
|
|
151
|
+
type FunctionCall = Required<Pick<Gemini.Part, "functionCall">> & Pick<Gemini.Part, "thoughtSignature">;
|
|
152
|
+
type FunctionResponse = Pick<Gemini.Part, "functionResponse">;
|
|
153
|
+
type InlineData = Pick<Gemini.Part, "inlineData" | "videoMetadata">;
|
|
154
|
+
type MediaResolution = Pick<Gemini.Part, "mediaResolution">;
|
|
155
|
+
type PartMetadata = Pick<Gemini.Part, "partMetadata">;
|
|
156
|
+
type Text = Pick<Gemini.Part, "text">;
|
|
157
|
+
type Thought = Pick<Gemini.Part, "thought">;
|
|
158
|
+
type ThoughtSignature = Pick<Gemini.Part, "thoughtSignature">;
|
|
159
|
+
}
|
|
160
|
+
namespace PrebuiltVoiceConfig {
|
|
161
|
+
/**
|
|
162
|
+
* The name of a prebuilt voice that can be used for speech synthesis.
|
|
163
|
+
*
|
|
164
|
+
* Extracted as a non-nullable type from the GeminiBase.PrebuiltVoiceConfig["voiceName"] property.
|
|
165
|
+
*/
|
|
166
|
+
type VoiceName = NonNullable<Gemini.PrebuiltVoiceConfig["voiceName"]>;
|
|
167
|
+
}
|
|
168
|
+
namespace SpeakerVoiceConfig {
|
|
169
|
+
/**
|
|
170
|
+
* The speaker identifier for a custom or multi-speaker TTS configuration.
|
|
171
|
+
*
|
|
172
|
+
* Extracted as a non-nullable type from the GeminiBase.SpeakerVoiceConfig["speaker"] property.
|
|
173
|
+
*/
|
|
174
|
+
type Speaker = NonNullable<Gemini.SpeakerVoiceConfig["speaker"]>;
|
|
175
|
+
}
|
|
176
|
+
namespace SpeechConfig {
|
|
177
|
+
/**
|
|
178
|
+
* The BCP-47 language code for speech synthesis (e.g., "en-US").
|
|
179
|
+
*
|
|
180
|
+
* Extracted as a non-nullable type from the GeminiBase.SpeechConfig["languageCode"] property.
|
|
181
|
+
*/
|
|
182
|
+
type LanguageCode = NonNullable<Gemini.SpeechConfig["languageCode"]>;
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* The level of "thinking" or reasoning configured for the model.
|
|
186
|
+
*
|
|
187
|
+
* Corresponds to GeminiBase.ThinkingConfig["thinkingLevel"].
|
|
188
|
+
*/
|
|
189
|
+
type ThinkingLevel = Gemini.ThinkingConfig["thinkingLevel"];
|
|
190
|
+
/**
|
|
191
|
+
* The role of a content message. The spec types this as `string`, but
|
|
192
|
+
* the API only accepts these specific values.
|
|
193
|
+
*/
|
|
194
|
+
type Role = "user" | "model" | "function";
|
|
195
|
+
/**
|
|
196
|
+
* Alias for the unwieldy generated grounding support type name.
|
|
197
|
+
*/
|
|
198
|
+
type GroundingSupport = Gemini.GoogleAiGenerativelanguageV1betaGroundingSupport;
|
|
199
|
+
/**
|
|
200
|
+
* Alias for the unwieldy generated segment type name.
|
|
201
|
+
*/
|
|
202
|
+
type Segment = Gemini.GoogleAiGenerativelanguageV1betaSegment;
|
|
203
|
+
namespace Tools {
|
|
204
|
+
/**
|
|
205
|
+
* The mode for function calling configuration, extracted from the
|
|
206
|
+
* FunctionCallingConfig interface.
|
|
207
|
+
*/
|
|
208
|
+
type FunctionCallingConfigMode = Gemini.Tools.FunctionCallingConfig["mode"];
|
|
209
|
+
}
|
|
210
|
+
/**
|
|
211
|
+
* Legacy URL retrieval metadata (predecessor of UrlContextMetadata).
|
|
212
|
+
* Not in the current OpenAPI spec but still returned by the API.
|
|
213
|
+
*/
|
|
214
|
+
interface UrlRetrievalMetadata {
|
|
215
|
+
urlRetrievalContexts?: Array<Gemini.UrlMetadata>;
|
|
216
|
+
}
|
|
217
|
+
interface Candidate {
|
|
218
|
+
/** @deprecated Use urlContextMetadata instead. */
|
|
219
|
+
readonly urlRetrievalMetadata?: UrlRetrievalMetadata;
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
/**
|
|
224
|
+
* Simplified speaker/name pair for multi-speaker config.
|
|
225
|
+
* - `speaker` derived from SpeakerVoiceConfig["speaker"]
|
|
226
|
+
* - `name` is the prebuilt voice name
|
|
227
|
+
*/
|
|
228
|
+
interface SpeechSpeakerName {
|
|
229
|
+
speaker: Gemini.SpeakerVoiceConfig.Speaker;
|
|
230
|
+
name: Gemini.PrebuiltVoiceConfig.VoiceName;
|
|
231
|
+
}
|
|
232
|
+
/** A voice can be a prebuilt voice name, a speaker/name pair, or an array of pairs */
|
|
233
|
+
type SpeechVoice = Gemini.PrebuiltVoiceConfig.VoiceName | SpeechSpeakerName | SpeechSpeakerName[];
|
|
234
|
+
/** Voice with language code (derived from SpeechConfig's languageCode) */
|
|
235
|
+
interface SpeechVoiceLanguage {
|
|
236
|
+
voice: SpeechVoice;
|
|
237
|
+
languageCode: Gemini.SpeechConfig.LanguageCode;
|
|
238
|
+
}
|
|
239
|
+
/** Voices with language code */
|
|
240
|
+
interface SpeechVoicesLanguage {
|
|
241
|
+
voices: SpeechVoice;
|
|
242
|
+
languageCode: Gemini.SpeechConfig.LanguageCode;
|
|
243
|
+
}
|
|
244
|
+
/** Simplified language config (with voice or voices) */
|
|
245
|
+
type SimplifiedSpeechLanguageConfig = SpeechVoiceLanguage | SpeechVoicesLanguage;
|
|
246
|
+
/** Top-level simplified config: just a voice, or voice+language */
|
|
247
|
+
type SimplifiedSpeechConfig = SpeechVoice | SimplifiedSpeechLanguageConfig;
|
|
248
|
+
//#endregion
|
|
249
|
+
export { ChatGoogleFields };
|
|
250
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
|
|
2
|
+
const require_const = require('../const.cjs');
|
|
3
|
+
const require_misc = require('../utils/misc.cjs');
|
|
4
|
+
const require_errors = require('../utils/errors.cjs');
|
|
5
|
+
const require_gcp_auth = require('../utils/gcp-auth.cjs');
|
|
6
|
+
const __langchain_core_utils_env = require_rolldown_runtime.__toESM(require("@langchain/core/utils/env"));
|
|
7
|
+
|
|
8
|
+
//#region src/clients/index.ts
|
|
9
|
+
/**
|
|
10
|
+
* Abstract base class for API clients that interact with Google services.
|
|
11
|
+
*
|
|
12
|
+
* This class defines the contract for API clients, requiring implementations
|
|
13
|
+
* to provide a fetch method that handles HTTP requests with appropriate
|
|
14
|
+
* authentication headers. Concrete implementations should handle different
|
|
15
|
+
* authentication strategies (API keys, service account credentials, etc.)
|
|
16
|
+
* based on the runtime environment.
|
|
17
|
+
*
|
|
18
|
+
* @abstract
|
|
19
|
+
*
|
|
20
|
+
* @example
|
|
21
|
+
* ```typescript
|
|
22
|
+
* class MyApiClient extends ApiClient {
|
|
23
|
+
* async fetch(request: Request): Promise<Response> {
|
|
24
|
+
* // Add authentication headers
|
|
25
|
+
* request.headers.set('Authorization', 'Bearer token');
|
|
26
|
+
* return fetch(request);
|
|
27
|
+
* }
|
|
28
|
+
* }
|
|
29
|
+
* ```
|
|
30
|
+
*/
|
|
31
|
+
var ApiClient = class {
|
|
32
|
+
/**
|
|
33
|
+
* For some credential methods, we know what the project ID is.
|
|
34
|
+
* This is necessary for OAuth-based access to Vertex
|
|
35
|
+
*/
|
|
36
|
+
async getProjectId() {
|
|
37
|
+
return "unknown-project-id";
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
/**
|
|
41
|
+
* Web-compatible API client for Google services.
|
|
42
|
+
*
|
|
43
|
+
* This client provides authentication for Google API requests in web environments
|
|
44
|
+
* (browsers, edge functions, etc.) where the google-auth-library is not available.
|
|
45
|
+
* It supports two authentication methods:
|
|
46
|
+
*
|
|
47
|
+
* 1. **API Key Authentication**: Simple key-based authentication suitable for
|
|
48
|
+
* public APIs and client-side applications.
|
|
49
|
+
*
|
|
50
|
+
* 2. **Service Account Credentials**: OAuth2-based authentication using GCP
|
|
51
|
+
* service account keys. The client automatically handles token generation
|
|
52
|
+
* and caching.
|
|
53
|
+
*
|
|
54
|
+
* The client follows this authentication priority:
|
|
55
|
+
* 1. Explicit `apiKey` parameter
|
|
56
|
+
* 2. `GOOGLE_API_KEY` environment variable
|
|
57
|
+
* 3. Explicit `credentials` parameter
|
|
58
|
+
* 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable
|
|
59
|
+
*
|
|
60
|
+
* @extends ApiClient
|
|
61
|
+
*
|
|
62
|
+
* @example
|
|
63
|
+
* ```typescript
|
|
64
|
+
* // Using API key
|
|
65
|
+
* const client = new WebApiClient({
|
|
66
|
+
* apiKey: 'your-api-key'
|
|
67
|
+
* });
|
|
68
|
+
*
|
|
69
|
+
* // Using service account credentials
|
|
70
|
+
* const client = new WebApiClient({
|
|
71
|
+
* credentials: {
|
|
72
|
+
* type: "service_account",
|
|
73
|
+
* project_id: "my-project",
|
|
74
|
+
* private_key_id: "key-id",
|
|
75
|
+
* private_key: "-----BEGIN PRIVATE KEY-----\n...",
|
|
76
|
+
* client_email: "service-account@project.iam.gserviceaccount.com",
|
|
77
|
+
* // ... other required fields
|
|
78
|
+
* }
|
|
79
|
+
* });
|
|
80
|
+
*
|
|
81
|
+
* // Using environment variables
|
|
82
|
+
* // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS
|
|
83
|
+
* const client = new WebApiClient({});
|
|
84
|
+
*
|
|
85
|
+
* // Make authenticated requests
|
|
86
|
+
* const request = new Request('https://api.google.com/...');
|
|
87
|
+
* const response = await client.fetch(request);
|
|
88
|
+
* ```
|
|
89
|
+
*
|
|
90
|
+
* @remarks
|
|
91
|
+
* - API keys are added via the `X-Goog-Api-Key` header
|
|
92
|
+
* - Service account tokens are added via the `Authorization` header with Bearer scheme
|
|
93
|
+
* - Tokens are automatically cached and refreshed as needed
|
|
94
|
+
* - For Node.js environments with advanced auth requirements, use NodeApiClient instead
|
|
95
|
+
*
|
|
96
|
+
* @see {@link NodeApiClient} for Node.js-specific authentication options
|
|
97
|
+
* @see {@link GCPCredentials} for service account credential structure
|
|
98
|
+
*/
|
|
99
|
+
var WebApiClient = class extends ApiClient {
|
|
100
|
+
hasApiKey() {
|
|
101
|
+
return typeof this.apiKey === "string" && this.apiKey !== "";
|
|
102
|
+
}
|
|
103
|
+
async getProjectId() {
|
|
104
|
+
if (typeof this.credentials !== "undefined") return this.credentials.project_id;
|
|
105
|
+
else return super.getProjectId();
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* The Google API key used for authentication, if provided.
|
|
109
|
+
*
|
|
110
|
+
* This value is resolved from either the constructor parameter or the
|
|
111
|
+
* `GOOGLE_API_KEY` environment variable.
|
|
112
|
+
*
|
|
113
|
+
* @protected
|
|
114
|
+
*/
|
|
115
|
+
apiKey;
|
|
116
|
+
/**
|
|
117
|
+
* The normalized GCP service account credentials, if provided.
|
|
118
|
+
*
|
|
119
|
+
* This value is resolved from either the constructor parameter or the
|
|
120
|
+
* `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized
|
|
121
|
+
* to ensure immutability.
|
|
122
|
+
*
|
|
123
|
+
* @protected
|
|
124
|
+
*/
|
|
125
|
+
credentials;
|
|
126
|
+
/**
|
|
127
|
+
* Creates a new WebApiClient instance.
|
|
128
|
+
*
|
|
129
|
+
* The constructor initializes authentication credentials by checking:
|
|
130
|
+
* 1. Explicit parameters passed to the constructor
|
|
131
|
+
* 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)
|
|
132
|
+
*
|
|
133
|
+
* Credentials are normalized and frozen to prevent accidental modification.
|
|
134
|
+
*
|
|
135
|
+
* @param params - Configuration parameters for the client
|
|
136
|
+
*
|
|
137
|
+
* @example
|
|
138
|
+
* ```typescript
|
|
139
|
+
* // Minimal configuration (uses environment variables)
|
|
140
|
+
* const client = new WebApiClient({});
|
|
141
|
+
*
|
|
142
|
+
* // With explicit API key
|
|
143
|
+
* const client = new WebApiClient({
|
|
144
|
+
* apiKey: 'your-api-key'
|
|
145
|
+
* });
|
|
146
|
+
*
|
|
147
|
+
* // With service account credentials as JSON string
|
|
148
|
+
* const client = new WebApiClient({
|
|
149
|
+
* credentials: '{"type":"service_account",...}'
|
|
150
|
+
* });
|
|
151
|
+
*
|
|
152
|
+
* // With service account credentials as object
|
|
153
|
+
* const client = new WebApiClient({
|
|
154
|
+
* credentials: {
|
|
155
|
+
* type: "service_account",
|
|
156
|
+
* // ... other fields
|
|
157
|
+
* }
|
|
158
|
+
* });
|
|
159
|
+
* ```
|
|
160
|
+
*/
|
|
161
|
+
constructor(params) {
|
|
162
|
+
super();
|
|
163
|
+
this.params = params;
|
|
164
|
+
this.apiKey = params.apiKey ?? (0, __langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_API_KEY");
|
|
165
|
+
this.credentials = require_misc.iife(() => {
|
|
166
|
+
if (params.credentials) return require_gcp_auth.normalizeGCPCredentials(params.credentials);
|
|
167
|
+
const credentialsVar = (0, __langchain_core_utils_env.getEnvironmentVariable)("GOOGLE_CLOUD_CREDENTIALS");
|
|
168
|
+
if (credentialsVar) return require_gcp_auth.normalizeGCPCredentials(credentialsVar);
|
|
169
|
+
return void 0;
|
|
170
|
+
});
|
|
171
|
+
}
|
|
172
|
+
/**
|
|
173
|
+
* Executes an HTTP request with appropriate Google API authentication.
|
|
174
|
+
*
|
|
175
|
+
* This method adds authentication headers to the request based on the
|
|
176
|
+
* configured authentication method:
|
|
177
|
+
*
|
|
178
|
+
* - If an API key is configured, adds the `X-Goog-Api-Key` header
|
|
179
|
+
* - If service account credentials are configured, generates an access token
|
|
180
|
+
* and adds it via the `Authorization` header with Bearer scheme
|
|
181
|
+
*
|
|
182
|
+
* The authentication priority is:
|
|
183
|
+
* 1. API key (if provided)
|
|
184
|
+
* 2. Service account credentials (if provided)
|
|
185
|
+
*
|
|
186
|
+
* @param request - The HTTP request to execute. Headers will be modified
|
|
187
|
+
* in-place to include authentication information.
|
|
188
|
+
* @returns A Promise that resolves to the HTTP response
|
|
189
|
+
*
|
|
190
|
+
* @throws {AuthError} If no authentication method is available (neither apiKey
|
|
191
|
+
* nor credentials), or if service account authentication
|
|
192
|
+
* fails (e.g., invalid credentials, network error, or
|
|
193
|
+
* token generation failure)
|
|
194
|
+
*
|
|
195
|
+
* @example
|
|
196
|
+
* ```typescript
|
|
197
|
+
* const client = new WebApiClient({ apiKey: 'your-key' });
|
|
198
|
+
* const request = new Request('https://generativelanguage.googleapis.com/v1/models');
|
|
199
|
+
* const response = await client.fetch(request);
|
|
200
|
+
* const data = await response.json();
|
|
201
|
+
* ```
|
|
202
|
+
*
|
|
203
|
+
* @remarks
|
|
204
|
+
* - The request object is modified in-place by adding headers
|
|
205
|
+
* - Service account tokens are automatically cached and refreshed
|
|
206
|
+
* - If both API key and credentials are provided, API key takes precedence
|
|
207
|
+
*/
|
|
208
|
+
async fetch(request) {
|
|
209
|
+
if (!this.apiKey && !this.credentials) throw new require_errors.AuthError({ message: "No authentication method available. Please provide either an apiKey or credentials." });
|
|
210
|
+
if (this.apiKey) request.headers.set(require_const.GOOGLE_API_KEY_HEADER, this.apiKey);
|
|
211
|
+
if (this.credentials) request.headers.set(require_const.GCP_API_KEY_HEADER, `Bearer ${await require_gcp_auth.getGCPCredentialsAccessToken(this.credentials)}`);
|
|
212
|
+
return fetch(request);
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
|
|
216
|
+
//#endregion
|
|
217
|
+
exports.ApiClient = ApiClient;
|
|
218
|
+
exports.WebApiClient = WebApiClient;
|
|
219
|
+
//# sourceMappingURL=index.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.cjs","names":["params: WebApiClientParams","iife","normalizeGCPCredentials","request: Request","AuthError","GOOGLE_API_KEY_HEADER","GCP_API_KEY_HEADER","getGCPCredentialsAccessToken"],"sources":["../../src/clients/index.ts"],"sourcesContent":["import { getEnvironmentVariable } from \"@langchain/core/utils/env\";\nimport { GCP_API_KEY_HEADER, GOOGLE_API_KEY_HEADER } from \"../const.js\";\nimport {\n GCPCredentials,\n getGCPCredentialsAccessToken,\n normalizeGCPCredentials,\n} from \"../utils/gcp-auth.js\";\nimport { AuthError } from \"../utils/errors.js\";\nimport { iife } from \"../utils/misc.js\";\n\n/**\n * Abstract base class for API clients that interact with Google services.\n *\n * This class defines the contract for API clients, requiring implementations\n * to provide a fetch method that handles HTTP requests with appropriate\n * authentication headers. Concrete implementations should handle different\n * authentication strategies (API keys, service account credentials, etc.)\n * based on the runtime environment.\n *\n * @abstract\n *\n * @example\n * ```typescript\n * class MyApiClient extends ApiClient {\n * async fetch(request: Request): Promise<Response> {\n * // Add authentication headers\n * request.headers.set('Authorization', 'Bearer token');\n * return fetch(request);\n * }\n * }\n * ```\n */\nexport abstract class ApiClient {\n /**\n * Has an API Key been set for this client?\n */\n abstract hasApiKey(): boolean;\n\n /**\n * For some credential methods, we know what the project ID is.\n * This is necessary for OAuth-based access to Vertex\n */\n async getProjectId(): Promise<string> {\n return \"unknown-project-id\";\n }\n\n /**\n * Executes an HTTP request with appropriate authentication.\n *\n * Implementations should add necessary authentication headers to the request\n * before forwarding it to the underlying fetch implementation.\n *\n * @param request - The HTTP request to execute\n * @returns A Promise that resolves to the HTTP response\n *\n * @abstract\n */\n abstract fetch(request: Request): Promise<Response>;\n}\n\n/**\n * Configuration parameters for the WebApiClient.\n *\n * This interface defines the authentication options available for web-based\n * API clients. Authentication can be provided via an API key or GCP service\n * account credentials. The client will automatically check environment variables\n * if explicit values are not provided.\n *\n * @interface\n */\nexport interface WebApiClientParams {\n /**\n * Google API key for authentication.\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @see https://cloud.google.com/docs/authentication/api-keys\n */\n apiKey?: string;\n\n /**\n * GCP service account credentials for authentication.\n *\n * Can be provided as either:\n * - A JSON string containing the service account key\n * - A GCPCredentials object\n *\n * If not provided, the client will attempt to read from the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable.\n *\n * @see https://cloud.google.com/iam/docs/creating-managing-service-account-keys\n */\n credentials?: string | GCPCredentials;\n\n /**\n * Google Auth options configuration.\n *\n * @deprecated This option is not supported in web environments.\n * Import from `@langchain/google/node` to configure google auth options\n * using the NodeApiClient instead.\n */\n googleAuthOptions?: never;\n}\n\n/**\n * Web-compatible API client for Google services.\n *\n * This client provides authentication for Google API requests in web environments\n * (browsers, edge functions, etc.) where the google-auth-library is not available.\n * It supports two authentication methods:\n *\n * 1. **API Key Authentication**: Simple key-based authentication suitable for\n * public APIs and client-side applications.\n *\n * 2. **Service Account Credentials**: OAuth2-based authentication using GCP\n * service account keys. The client automatically handles token generation\n * and caching.\n *\n * The client follows this authentication priority:\n * 1. Explicit `apiKey` parameter\n * 2. `GOOGLE_API_KEY` environment variable\n * 3. Explicit `credentials` parameter\n * 4. `GOOGLE_CLOUD_CREDENTIALS` environment variable\n *\n * @extends ApiClient\n *\n * @example\n * ```typescript\n * // Using API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // Using service account credentials\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * project_id: \"my-project\",\n * private_key_id: \"key-id\",\n * private_key: \"-----BEGIN PRIVATE KEY-----\\n...\",\n * client_email: \"service-account@project.iam.gserviceaccount.com\",\n * // ... other required fields\n * }\n * });\n *\n * // Using environment variables\n * // Set GOOGLE_API_KEY or GOOGLE_CLOUD_CREDENTIALS\n * const client = new WebApiClient({});\n *\n * // Make authenticated requests\n * const request = new Request('https://api.google.com/...');\n * const response = await client.fetch(request);\n * ```\n *\n * @remarks\n * - API keys are added via the `X-Goog-Api-Key` header\n * - Service account tokens are added via the `Authorization` header with Bearer scheme\n * - Tokens are automatically cached and refreshed as needed\n * - For Node.js environments with advanced auth requirements, use NodeApiClient instead\n *\n * @see {@link NodeApiClient} for Node.js-specific authentication options\n * @see {@link GCPCredentials} for service account credential structure\n */\nexport class WebApiClient extends ApiClient {\n hasApiKey(): boolean {\n return typeof this.apiKey === \"string\" && this.apiKey !== \"\";\n }\n\n async getProjectId(): Promise<string> {\n if (typeof this.credentials !== \"undefined\") {\n return this.credentials.project_id;\n } else {\n return super.getProjectId();\n }\n }\n\n /**\n * The Google API key used for authentication, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_API_KEY` environment variable.\n *\n * @protected\n */\n protected apiKey?: string;\n\n /**\n * The normalized GCP service account credentials, if provided.\n *\n * This value is resolved from either the constructor parameter or the\n * `GOOGLE_CLOUD_CREDENTIALS` environment variable, and is normalized\n * to ensure immutability.\n *\n * @protected\n */\n protected credentials?: GCPCredentials;\n\n /**\n * Creates a new WebApiClient instance.\n *\n * The constructor initializes authentication credentials by checking:\n * 1. Explicit parameters passed to the constructor\n * 2. Environment variables (`GOOGLE_API_KEY`, `GOOGLE_CLOUD_CREDENTIALS`)\n *\n * Credentials are normalized and frozen to prevent accidental modification.\n *\n * @param params - Configuration parameters for the client\n *\n * @example\n * ```typescript\n * // Minimal configuration (uses environment variables)\n * const client = new WebApiClient({});\n *\n * // With explicit API key\n * const client = new WebApiClient({\n * apiKey: 'your-api-key'\n * });\n *\n * // With service account credentials as JSON string\n * const client = new WebApiClient({\n * credentials: '{\"type\":\"service_account\",...}'\n * });\n *\n * // With service account credentials as object\n * const client = new WebApiClient({\n * credentials: {\n * type: \"service_account\",\n * // ... other fields\n * }\n * });\n * ```\n */\n constructor(protected params: WebApiClientParams) {\n super();\n this.apiKey = params.apiKey ?? getEnvironmentVariable(\"GOOGLE_API_KEY\");\n this.credentials = iife(() => {\n if (params.credentials) {\n return normalizeGCPCredentials(params.credentials);\n }\n const credentialsVar = getEnvironmentVariable(\"GOOGLE_CLOUD_CREDENTIALS\");\n if (credentialsVar) {\n return normalizeGCPCredentials(credentialsVar);\n }\n return undefined;\n });\n }\n\n /**\n * Executes an HTTP request with appropriate Google API authentication.\n *\n * This method adds authentication headers to the request based on the\n * configured authentication method:\n *\n * - If an API key is configured, adds the `X-Goog-Api-Key` header\n * - If service account credentials are configured, generates an access token\n * and adds it via the `Authorization` header with Bearer scheme\n *\n * The authentication priority is:\n * 1. API key (if provided)\n * 2. Service account credentials (if provided)\n *\n * @param request - The HTTP request to execute. Headers will be modified\n * in-place to include authentication information.\n * @returns A Promise that resolves to the HTTP response\n *\n * @throws {AuthError} If no authentication method is available (neither apiKey\n * nor credentials), or if service account authentication\n * fails (e.g., invalid credentials, network error, or\n * token generation failure)\n *\n * @example\n * ```typescript\n * const client = new WebApiClient({ apiKey: 'your-key' });\n * const request = new Request('https://generativelanguage.googleapis.com/v1/models');\n * const response = await client.fetch(request);\n * const data = await response.json();\n * ```\n *\n * @remarks\n * - The request object is modified in-place by adding headers\n * - Service account tokens are automatically cached and refreshed\n * - If both API key and credentials are provided, API key takes precedence\n */\n async fetch(request: Request): Promise<Response> {\n if (!this.apiKey && !this.credentials) {\n throw new AuthError({\n message:\n \"No authentication method available. Please provide either an apiKey or credentials.\",\n });\n }\n if (this.apiKey) {\n request.headers.set(GOOGLE_API_KEY_HEADER, this.apiKey);\n }\n if (this.credentials) {\n request.headers.set(\n GCP_API_KEY_HEADER,\n `Bearer ${await getGCPCredentialsAccessToken(this.credentials)}`\n );\n }\n return fetch(request);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,IAAsB,YAAtB,MAAgC;;;;;CAU9B,MAAM,eAAgC;AACpC,SAAO;CACR;AAcF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GD,IAAa,eAAb,cAAkC,UAAU;CAC1C,YAAqB;AACnB,SAAO,OAAO,KAAK,WAAW,YAAY,KAAK,WAAW;CAC3D;CAED,MAAM,eAAgC;AACpC,MAAI,OAAO,KAAK,gBAAgB,YAC9B,QAAO,KAAK,YAAY;MAExB,QAAO,MAAM,cAAc;CAE9B;;;;;;;;;CAUD,AAAU;;;;;;;;;;CAWV,AAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAqCV,YAAsBA,QAA4B;EAChD,OAAO;EADa;EAEpB,KAAK,SAAS,OAAO,iEAAiC,iBAAiB;EACvE,KAAK,cAAcC,kBAAK,MAAM;AAC5B,OAAI,OAAO,YACT,QAAOC,yCAAwB,OAAO,YAAY;GAEpD,MAAM,wEAAwC,2BAA2B;AACzE,OAAI,eACF,QAAOA,yCAAwB,eAAe;AAEhD,UAAO;EACR,EAAC;CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAsCD,MAAM,MAAMC,SAAqC;AAC/C,MAAI,CAAC,KAAK,UAAU,CAAC,KAAK,YACxB,OAAM,IAAIC,yBAAU,EAClB,SACE,sFACH;AAEH,MAAI,KAAK,QACP,QAAQ,QAAQ,IAAIC,qCAAuB,KAAK,OAAO;AAEzD,MAAI,KAAK,aACP,QAAQ,QAAQ,IACdC,kCACA,CAAC,OAAO,EAAE,MAAMC,8CAA6B,KAAK,YAAY,EAAE,CACjE;AAEH,SAAO,MAAM,QAAQ;CACtB;AACF"}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/clients/index.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Abstract base class for API clients that interact with Google services.
|
|
4
|
+
*
|
|
5
|
+
* This class defines the contract for API clients, requiring implementations
|
|
6
|
+
* to provide a fetch method that handles HTTP requests with appropriate
|
|
7
|
+
* authentication headers. Concrete implementations should handle different
|
|
8
|
+
* authentication strategies (API keys, service account credentials, etc.)
|
|
9
|
+
* based on the runtime environment.
|
|
10
|
+
*
|
|
11
|
+
* @abstract
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* class MyApiClient extends ApiClient {
|
|
16
|
+
* async fetch(request: Request): Promise<Response> {
|
|
17
|
+
* // Add authentication headers
|
|
18
|
+
* request.headers.set('Authorization', 'Bearer token');
|
|
19
|
+
* return fetch(request);
|
|
20
|
+
* }
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
declare abstract class ApiClient {
|
|
25
|
+
/**
|
|
26
|
+
* Has an API Key been set for this client?
|
|
27
|
+
*/
|
|
28
|
+
abstract hasApiKey(): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* For some credential methods, we know what the project ID is.
|
|
31
|
+
* This is necessary for OAuth-based access to Vertex
|
|
32
|
+
*/
|
|
33
|
+
getProjectId(): Promise<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Executes an HTTP request with appropriate authentication.
|
|
36
|
+
*
|
|
37
|
+
* Implementations should add necessary authentication headers to the request
|
|
38
|
+
* before forwarding it to the underlying fetch implementation.
|
|
39
|
+
*
|
|
40
|
+
* @param request - The HTTP request to execute
|
|
41
|
+
* @returns A Promise that resolves to the HTTP response
|
|
42
|
+
*
|
|
43
|
+
* @abstract
|
|
44
|
+
*/
|
|
45
|
+
abstract fetch(request: Request): Promise<Response>;
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { ApiClient };
|
|
49
|
+
//# sourceMappingURL=index.d.cts.map
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
//#region src/clients/index.d.ts
|
|
2
|
+
/**
|
|
3
|
+
* Abstract base class for API clients that interact with Google services.
|
|
4
|
+
*
|
|
5
|
+
* This class defines the contract for API clients, requiring implementations
|
|
6
|
+
* to provide a fetch method that handles HTTP requests with appropriate
|
|
7
|
+
* authentication headers. Concrete implementations should handle different
|
|
8
|
+
* authentication strategies (API keys, service account credentials, etc.)
|
|
9
|
+
* based on the runtime environment.
|
|
10
|
+
*
|
|
11
|
+
* @abstract
|
|
12
|
+
*
|
|
13
|
+
* @example
|
|
14
|
+
* ```typescript
|
|
15
|
+
* class MyApiClient extends ApiClient {
|
|
16
|
+
* async fetch(request: Request): Promise<Response> {
|
|
17
|
+
* // Add authentication headers
|
|
18
|
+
* request.headers.set('Authorization', 'Bearer token');
|
|
19
|
+
* return fetch(request);
|
|
20
|
+
* }
|
|
21
|
+
* }
|
|
22
|
+
* ```
|
|
23
|
+
*/
|
|
24
|
+
declare abstract class ApiClient {
|
|
25
|
+
/**
|
|
26
|
+
* Has an API Key been set for this client?
|
|
27
|
+
*/
|
|
28
|
+
abstract hasApiKey(): boolean;
|
|
29
|
+
/**
|
|
30
|
+
* For some credential methods, we know what the project ID is.
|
|
31
|
+
* This is necessary for OAuth-based access to Vertex
|
|
32
|
+
*/
|
|
33
|
+
getProjectId(): Promise<string>;
|
|
34
|
+
/**
|
|
35
|
+
* Executes an HTTP request with appropriate authentication.
|
|
36
|
+
*
|
|
37
|
+
* Implementations should add necessary authentication headers to the request
|
|
38
|
+
* before forwarding it to the underlying fetch implementation.
|
|
39
|
+
*
|
|
40
|
+
* @param request - The HTTP request to execute
|
|
41
|
+
* @returns A Promise that resolves to the HTTP response
|
|
42
|
+
*
|
|
43
|
+
* @abstract
|
|
44
|
+
*/
|
|
45
|
+
abstract fetch(request: Request): Promise<Response>;
|
|
46
|
+
}
|
|
47
|
+
//#endregion
|
|
48
|
+
export { ApiClient };
|
|
49
|
+
//# sourceMappingURL=index.d.ts.map
|