langchain 0.0.175 → 0.0.177

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.
Files changed (89) hide show
  1. package/dist/chat_models/bedrock.cjs +25 -4
  2. package/dist/chat_models/bedrock.d.ts +2 -1
  3. package/dist/chat_models/bedrock.js +25 -4
  4. package/dist/chat_models/googlevertexai/common.cjs +46 -7
  5. package/dist/chat_models/googlevertexai/common.d.ts +7 -2
  6. package/dist/chat_models/googlevertexai/common.js +47 -8
  7. package/dist/chat_models/googlevertexai/index.cjs +4 -3
  8. package/dist/chat_models/googlevertexai/index.js +4 -3
  9. package/dist/chat_models/googlevertexai/web.cjs +2 -1
  10. package/dist/chat_models/googlevertexai/web.js +2 -1
  11. package/dist/chat_models/llama_cpp.cjs +31 -79
  12. package/dist/chat_models/llama_cpp.d.ts +15 -58
  13. package/dist/chat_models/llama_cpp.js +32 -80
  14. package/dist/chat_models/openai.cjs +91 -6
  15. package/dist/chat_models/openai.d.ts +10 -0
  16. package/dist/chat_models/openai.js +91 -6
  17. package/dist/embeddings/googlevertexai.cjs +1 -1
  18. package/dist/embeddings/googlevertexai.js +1 -1
  19. package/dist/embeddings/hf.cjs +10 -1
  20. package/dist/embeddings/hf.d.ts +4 -2
  21. package/dist/embeddings/hf.js +10 -1
  22. package/dist/embeddings/llama_cpp.cjs +67 -0
  23. package/dist/embeddings/llama_cpp.d.ts +26 -0
  24. package/dist/embeddings/llama_cpp.js +63 -0
  25. package/dist/embeddings/ollama.cjs +7 -1
  26. package/dist/embeddings/ollama.js +7 -1
  27. package/dist/experimental/hubs/makersuite/googlemakersuitehub.d.ts +2 -2
  28. package/dist/experimental/multimodal_embeddings/googlevertexai.cjs +1 -1
  29. package/dist/experimental/multimodal_embeddings/googlevertexai.d.ts +2 -1
  30. package/dist/experimental/multimodal_embeddings/googlevertexai.js +2 -2
  31. package/dist/experimental/plan_and_execute/agent_executor.cjs +7 -4
  32. package/dist/experimental/plan_and_execute/agent_executor.d.ts +4 -3
  33. package/dist/experimental/plan_and_execute/agent_executor.js +8 -5
  34. package/dist/experimental/plan_and_execute/prompt.cjs +25 -9
  35. package/dist/experimental/plan_and_execute/prompt.d.ts +9 -1
  36. package/dist/experimental/plan_and_execute/prompt.js +23 -8
  37. package/dist/llms/bedrock.cjs +25 -3
  38. package/dist/llms/bedrock.d.ts +2 -1
  39. package/dist/llms/bedrock.js +25 -3
  40. package/dist/llms/googlevertexai/common.cjs +46 -13
  41. package/dist/llms/googlevertexai/common.d.ts +8 -3
  42. package/dist/llms/googlevertexai/common.js +46 -13
  43. package/dist/llms/googlevertexai/index.cjs +4 -3
  44. package/dist/llms/googlevertexai/index.js +4 -3
  45. package/dist/llms/googlevertexai/web.cjs +2 -1
  46. package/dist/llms/googlevertexai/web.js +2 -1
  47. package/dist/llms/hf.cjs +10 -1
  48. package/dist/llms/hf.d.ts +3 -0
  49. package/dist/llms/hf.js +10 -1
  50. package/dist/llms/llama_cpp.cjs +25 -65
  51. package/dist/llms/llama_cpp.d.ts +7 -43
  52. package/dist/llms/llama_cpp.js +25 -65
  53. package/dist/load/import_constants.cjs +1 -0
  54. package/dist/load/import_constants.js +1 -0
  55. package/dist/prompts/few_shot.cjs +162 -1
  56. package/dist/prompts/few_shot.d.ts +90 -2
  57. package/dist/prompts/few_shot.js +160 -0
  58. package/dist/prompts/index.cjs +2 -1
  59. package/dist/prompts/index.d.ts +1 -1
  60. package/dist/prompts/index.js +1 -1
  61. package/dist/retrievers/zep.cjs +26 -3
  62. package/dist/retrievers/zep.d.ts +11 -2
  63. package/dist/retrievers/zep.js +26 -3
  64. package/dist/types/googlevertexai-types.d.ts +12 -10
  65. package/dist/util/bedrock.d.ts +2 -0
  66. package/dist/util/googlevertexai-connection.cjs +298 -10
  67. package/dist/util/googlevertexai-connection.d.ts +76 -7
  68. package/dist/util/googlevertexai-connection.js +294 -9
  69. package/dist/util/googlevertexai-gauth.cjs +36 -0
  70. package/dist/util/googlevertexai-gauth.d.ts +8 -0
  71. package/dist/util/googlevertexai-gauth.js +32 -0
  72. package/dist/util/googlevertexai-webauth.cjs +38 -2
  73. package/dist/util/googlevertexai-webauth.d.ts +2 -6
  74. package/dist/util/googlevertexai-webauth.js +38 -2
  75. package/dist/util/llama_cpp.cjs +34 -0
  76. package/dist/util/llama_cpp.d.ts +46 -0
  77. package/dist/util/llama_cpp.js +28 -0
  78. package/dist/util/openai-format-fndef.cjs +81 -0
  79. package/dist/util/openai-format-fndef.d.ts +44 -0
  80. package/dist/util/openai-format-fndef.js +77 -0
  81. package/dist/util/openapi.d.ts +2 -2
  82. package/dist/vectorstores/googlevertexai.d.ts +4 -4
  83. package/dist/vectorstores/pinecone.cjs +5 -5
  84. package/dist/vectorstores/pinecone.d.ts +2 -2
  85. package/dist/vectorstores/pinecone.js +5 -5
  86. package/embeddings/llama_cpp.cjs +1 -0
  87. package/embeddings/llama_cpp.d.ts +1 -0
  88. package/embeddings/llama_cpp.js +1 -0
  89. package/package.json +13 -5
@@ -1,25 +1,94 @@
1
1
  import { BaseLanguageModelCallOptions } from "../base_language/index.js";
2
2
  import { AsyncCaller, AsyncCallerCallOptions } from "./async_caller.js";
3
- import type { GoogleVertexAIBaseLLMInput, GoogleVertexAIBasePrediction, GoogleVertexAIConnectionParams, GoogleVertexAILLMResponse, GoogleVertexAIModelParams, GoogleResponse, GoogleAbstractedClient } from "../types/googlevertexai-types.js";
3
+ import type { GoogleVertexAIBaseLLMInput, GoogleVertexAIBasePrediction, GoogleVertexAIConnectionParams, GoogleVertexAILLMPredictions, GoogleVertexAIModelParams, GoogleResponse, GoogleAbstractedClient, GoogleAbstractedClientOpsMethod } from "../types/googlevertexai-types.js";
4
4
  export declare abstract class GoogleConnection<CallOptions extends AsyncCallerCallOptions, ResponseType extends GoogleResponse> {
5
5
  caller: AsyncCaller;
6
6
  client: GoogleAbstractedClient;
7
- constructor(caller: AsyncCaller, client: GoogleAbstractedClient);
7
+ streaming: boolean;
8
+ constructor(caller: AsyncCaller, client: GoogleAbstractedClient, streaming?: boolean);
8
9
  abstract buildUrl(): Promise<string>;
9
- abstract buildMethod(): string;
10
+ abstract buildMethod(): GoogleAbstractedClientOpsMethod;
10
11
  _request(data: unknown | undefined, options: CallOptions): Promise<ResponseType>;
11
12
  }
12
13
  export declare abstract class GoogleVertexAIConnection<CallOptions extends AsyncCallerCallOptions, ResponseType extends GoogleResponse, AuthOptions> extends GoogleConnection<CallOptions, ResponseType> implements GoogleVertexAIConnectionParams<AuthOptions> {
13
14
  endpoint: string;
14
15
  location: string;
15
16
  apiVersion: string;
16
- constructor(fields: GoogleVertexAIConnectionParams<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient);
17
- buildMethod(): string;
17
+ constructor(fields: GoogleVertexAIConnectionParams<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient, streaming?: boolean);
18
+ buildMethod(): GoogleAbstractedClientOpsMethod;
18
19
  }
19
- export declare class GoogleVertexAILLMConnection<CallOptions extends BaseLanguageModelCallOptions, InstanceType, PredictionType extends GoogleVertexAIBasePrediction, AuthOptions> extends GoogleVertexAIConnection<CallOptions, PredictionType, AuthOptions> implements GoogleVertexAIBaseLLMInput<AuthOptions> {
20
+ export declare function complexValue(value: unknown): unknown;
21
+ export declare function simpleValue(val: unknown): unknown;
22
+ export declare class GoogleVertexAILLMConnection<CallOptions extends BaseLanguageModelCallOptions, InstanceType, PredictionType extends GoogleVertexAIBasePrediction, AuthOptions> extends GoogleVertexAIConnection<CallOptions, GoogleVertexAILLMResponse<PredictionType>, AuthOptions> implements GoogleVertexAIBaseLLMInput<AuthOptions> {
20
23
  model: string;
21
24
  client: GoogleAbstractedClient;
22
- constructor(fields: GoogleVertexAIBaseLLMInput<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient);
25
+ constructor(fields: GoogleVertexAIBaseLLMInput<AuthOptions> | undefined, caller: AsyncCaller, client: GoogleAbstractedClient, streaming?: boolean);
23
26
  buildUrl(): Promise<string>;
27
+ formatStreamingData(inputs: InstanceType[], parameters: GoogleVertexAIModelParams): unknown;
28
+ formatStandardData(instances: InstanceType[], parameters: GoogleVertexAIModelParams): unknown;
29
+ formatData(instances: InstanceType[], parameters: GoogleVertexAIModelParams): unknown;
24
30
  request(instances: InstanceType[], parameters: GoogleVertexAIModelParams, options: CallOptions): Promise<GoogleVertexAILLMResponse<PredictionType>>;
25
31
  }
32
+ export interface GoogleVertexAILLMResponse<PredictionType extends GoogleVertexAIBasePrediction> extends GoogleResponse {
33
+ data: GoogleVertexAIStream | GoogleVertexAILLMPredictions<PredictionType>;
34
+ }
35
+ export declare class GoogleVertexAIStream {
36
+ _buffer: string;
37
+ _bufferOpen: boolean;
38
+ _firstRun: boolean;
39
+ /**
40
+ * Add data to the buffer. This may cause chunks to be generated, if available.
41
+ * @param data
42
+ */
43
+ appendBuffer(data: string): void;
44
+ /**
45
+ * Indicate there is no more data that will be added to the text buffer.
46
+ * This should be called when all the data has been read and added to indicate
47
+ * that we should process everything remaining in the buffer.
48
+ */
49
+ closeBuffer(): void;
50
+ /**
51
+ * Skip characters in the buffer till we get to the start of an object.
52
+ * Then attempt to read a full object.
53
+ * If we do read a full object, turn it into a chunk and send it to the chunk handler.
54
+ * Repeat this for as much as we can.
55
+ */
56
+ _parseBuffer(): void;
57
+ /**
58
+ * If the string is present, move the start of the buffer to the first occurrence
59
+ * of that string. This is useful for skipping over elements or parts that we're not
60
+ * really interested in parsing. (ie - the opening characters, comma separators, etc.)
61
+ * @param start The string to start the buffer with
62
+ */
63
+ _skipTo(start: string): void;
64
+ /**
65
+ * Given what is in the buffer, parse a single object out of it.
66
+ * If a complete object isn't available, return null.
67
+ * Assumes that we are at the start of an object to parse.
68
+ */
69
+ _getFullObject(): object | null;
70
+ _simplifyObject(obj: unknown): object;
71
+ _chunkResolution: (chunk: any) => void;
72
+ _chunkPending: Promise<any> | null;
73
+ _chunkQueue: any[];
74
+ /**
75
+ * Register that we have another chunk available for consumption.
76
+ * If we are waiting for a chunk, resolve the promise waiting for it immediately.
77
+ * If not, then add it to the queue.
78
+ * @param chunk
79
+ */
80
+ _handleChunk(chunk: any): void;
81
+ /**
82
+ * Get the next chunk that is coming from the stream.
83
+ * This chunk may be null, usually indicating the last chunk in the stream.
84
+ */
85
+ nextChunk(): Promise<any>;
86
+ /**
87
+ * Is the stream done?
88
+ * A stream is only done if all of the following are true:
89
+ * - There is no more data to be added to the text buffer
90
+ * - There is no more data in the text buffer
91
+ * - There are no chunks that are waiting to be consumed
92
+ */
93
+ get streamDone(): boolean;
94
+ }
@@ -1,5 +1,5 @@
1
1
  export class GoogleConnection {
2
- constructor(caller, client) {
2
+ constructor(caller, client, streaming) {
3
3
  Object.defineProperty(this, "caller", {
4
4
  enumerable: true,
5
5
  configurable: true,
@@ -12,13 +12,19 @@ export class GoogleConnection {
12
12
  writable: true,
13
13
  value: void 0
14
14
  });
15
+ Object.defineProperty(this, "streaming", {
16
+ enumerable: true,
17
+ configurable: true,
18
+ writable: true,
19
+ value: void 0
20
+ });
15
21
  this.caller = caller;
16
22
  this.client = client;
23
+ this.streaming = streaming ?? false;
17
24
  }
18
25
  async _request(data, options) {
19
26
  const url = await this.buildUrl();
20
27
  const method = this.buildMethod();
21
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
22
28
  const opts = {
23
29
  url,
24
30
  method,
@@ -26,6 +32,12 @@ export class GoogleConnection {
26
32
  if (data && method === "POST") {
27
33
  opts.data = data;
28
34
  }
35
+ if (this.streaming) {
36
+ opts.responseType = "stream";
37
+ }
38
+ else {
39
+ opts.responseType = "json";
40
+ }
29
41
  try {
30
42
  const callResponse = await this.caller.callWithOptions({ signal: options?.signal }, async () => this.client.request(opts));
31
43
  const response = callResponse; // Done for typecast safety, I guess
@@ -38,8 +50,8 @@ export class GoogleConnection {
38
50
  }
39
51
  }
40
52
  export class GoogleVertexAIConnection extends GoogleConnection {
41
- constructor(fields, caller, client) {
42
- super(caller, client);
53
+ constructor(fields, caller, client, streaming) {
54
+ super(caller, client, streaming);
43
55
  Object.defineProperty(this, "endpoint", {
44
56
  enumerable: true,
45
57
  configurable: true,
@@ -68,9 +80,84 @@ export class GoogleVertexAIConnection extends GoogleConnection {
68
80
  return "POST";
69
81
  }
70
82
  }
83
+ export function complexValue(value) {
84
+ if (value === null || typeof value === "undefined") {
85
+ // I dunno what to put here. An error, probably
86
+ return undefined;
87
+ }
88
+ else if (typeof value === "object") {
89
+ if (Array.isArray(value)) {
90
+ return {
91
+ list_val: value.map((avalue) => complexValue(avalue)),
92
+ };
93
+ }
94
+ else {
95
+ const ret = {};
96
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
97
+ const v = value;
98
+ Object.keys(v).forEach((key) => {
99
+ ret[key] = complexValue(v[key]);
100
+ });
101
+ return { struct_val: ret };
102
+ }
103
+ }
104
+ else if (typeof value === "number") {
105
+ if (Number.isInteger(value)) {
106
+ return { int_val: value };
107
+ }
108
+ else {
109
+ return { float_val: value };
110
+ }
111
+ }
112
+ else {
113
+ return {
114
+ string_val: [value],
115
+ };
116
+ }
117
+ }
118
+ export function simpleValue(val) {
119
+ if (val && typeof val === "object" && !Array.isArray(val)) {
120
+ // eslint-disable-next-line no-prototype-builtins
121
+ if (val.hasOwnProperty("stringVal")) {
122
+ return val.stringVal[0];
123
+ // eslint-disable-next-line no-prototype-builtins
124
+ }
125
+ else if (val.hasOwnProperty("boolVal")) {
126
+ return val.boolVal[0];
127
+ // eslint-disable-next-line no-prototype-builtins
128
+ }
129
+ else if (val.hasOwnProperty("listVal")) {
130
+ const { listVal } = val;
131
+ return listVal.map((aval) => simpleValue(aval));
132
+ // eslint-disable-next-line no-prototype-builtins
133
+ }
134
+ else if (val.hasOwnProperty("structVal")) {
135
+ const ret = {};
136
+ const struct = val.structVal;
137
+ Object.keys(struct).forEach((key) => {
138
+ ret[key] = simpleValue(struct[key]);
139
+ });
140
+ return ret;
141
+ }
142
+ else {
143
+ const ret = {};
144
+ const struct = val;
145
+ Object.keys(struct).forEach((key) => {
146
+ ret[key] = simpleValue(struct[key]);
147
+ });
148
+ return ret;
149
+ }
150
+ }
151
+ else if (Array.isArray(val)) {
152
+ return val.map((aval) => simpleValue(aval));
153
+ }
154
+ else {
155
+ return val;
156
+ }
157
+ }
71
158
  export class GoogleVertexAILLMConnection extends GoogleVertexAIConnection {
72
- constructor(fields, caller, client) {
73
- super(fields, caller, client);
159
+ constructor(fields, caller, client, streaming) {
160
+ super(fields, caller, client, streaming);
74
161
  Object.defineProperty(this, "model", {
75
162
  enumerable: true,
76
163
  configurable: true,
@@ -88,15 +175,213 @@ export class GoogleVertexAILLMConnection extends GoogleVertexAIConnection {
88
175
  }
89
176
  async buildUrl() {
90
177
  const projectId = await this.client.getProjectId();
91
- const url = `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:predict`;
178
+ const method = this.streaming ? "serverStreamingPredict" : "predict";
179
+ const url = `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:${method}`;
92
180
  return url;
93
181
  }
94
- async request(instances, parameters, options) {
95
- const data = {
182
+ formatStreamingData(inputs, parameters) {
183
+ return {
184
+ inputs: [inputs.map((i) => complexValue(i))],
185
+ parameters: complexValue(parameters),
186
+ };
187
+ }
188
+ formatStandardData(instances, parameters) {
189
+ return {
96
190
  instances,
97
191
  parameters,
98
192
  };
193
+ }
194
+ formatData(instances, parameters) {
195
+ return this.streaming
196
+ ? this.formatStreamingData(instances, parameters)
197
+ : this.formatStandardData(instances, parameters);
198
+ }
199
+ async request(instances, parameters, options) {
200
+ const data = this.formatData(instances, parameters);
99
201
  const response = await this._request(data, options);
100
202
  return response;
101
203
  }
102
204
  }
205
+ export class GoogleVertexAIStream {
206
+ constructor() {
207
+ Object.defineProperty(this, "_buffer", {
208
+ enumerable: true,
209
+ configurable: true,
210
+ writable: true,
211
+ value: ""
212
+ });
213
+ Object.defineProperty(this, "_bufferOpen", {
214
+ enumerable: true,
215
+ configurable: true,
216
+ writable: true,
217
+ value: true
218
+ });
219
+ Object.defineProperty(this, "_firstRun", {
220
+ enumerable: true,
221
+ configurable: true,
222
+ writable: true,
223
+ value: true
224
+ });
225
+ // Set up a potential Promise that the handler can resolve.
226
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
227
+ Object.defineProperty(this, "_chunkResolution", {
228
+ enumerable: true,
229
+ configurable: true,
230
+ writable: true,
231
+ value: void 0
232
+ });
233
+ // If there is no Promise (it is null), the handler must add it to the queue
234
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
235
+ Object.defineProperty(this, "_chunkPending", {
236
+ enumerable: true,
237
+ configurable: true,
238
+ writable: true,
239
+ value: null
240
+ });
241
+ // A queue that will collect chunks while there is no Promise
242
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
+ Object.defineProperty(this, "_chunkQueue", {
244
+ enumerable: true,
245
+ configurable: true,
246
+ writable: true,
247
+ value: []
248
+ });
249
+ }
250
+ /**
251
+ * Add data to the buffer. This may cause chunks to be generated, if available.
252
+ * @param data
253
+ */
254
+ appendBuffer(data) {
255
+ this._buffer += data;
256
+ // Our first time, skip to the opening of the array
257
+ if (this._firstRun) {
258
+ this._skipTo("[");
259
+ this._firstRun = false;
260
+ }
261
+ this._parseBuffer();
262
+ }
263
+ /**
264
+ * Indicate there is no more data that will be added to the text buffer.
265
+ * This should be called when all the data has been read and added to indicate
266
+ * that we should process everything remaining in the buffer.
267
+ */
268
+ closeBuffer() {
269
+ this._bufferOpen = false;
270
+ this._parseBuffer();
271
+ }
272
+ /**
273
+ * Skip characters in the buffer till we get to the start of an object.
274
+ * Then attempt to read a full object.
275
+ * If we do read a full object, turn it into a chunk and send it to the chunk handler.
276
+ * Repeat this for as much as we can.
277
+ */
278
+ _parseBuffer() {
279
+ let obj = null;
280
+ do {
281
+ this._skipTo("{");
282
+ obj = this._getFullObject();
283
+ if (obj !== null) {
284
+ const chunk = this._simplifyObject(obj);
285
+ this._handleChunk(chunk);
286
+ }
287
+ } while (obj !== null);
288
+ if (!this._bufferOpen) {
289
+ // No more data will be added, and we have parsed everything we could,
290
+ // so everything else is garbage.
291
+ this._handleChunk(null);
292
+ this._buffer = "";
293
+ }
294
+ }
295
+ /**
296
+ * If the string is present, move the start of the buffer to the first occurrence
297
+ * of that string. This is useful for skipping over elements or parts that we're not
298
+ * really interested in parsing. (ie - the opening characters, comma separators, etc.)
299
+ * @param start The string to start the buffer with
300
+ */
301
+ _skipTo(start) {
302
+ const index = this._buffer.indexOf(start);
303
+ if (index > 0) {
304
+ this._buffer = this._buffer.slice(index);
305
+ }
306
+ }
307
+ /**
308
+ * Given what is in the buffer, parse a single object out of it.
309
+ * If a complete object isn't available, return null.
310
+ * Assumes that we are at the start of an object to parse.
311
+ */
312
+ _getFullObject() {
313
+ let ret = null;
314
+ // Loop while we don't have something to return AND we have something in the buffer
315
+ let index = 0;
316
+ while (ret === null && this._buffer.length > index) {
317
+ // Advance to the next close bracket after our current index
318
+ index = this._buffer.indexOf("}", index + 1);
319
+ // If we don't find one, exit with null
320
+ if (index === -1) {
321
+ return null;
322
+ }
323
+ // If we have one, try to turn it into an object to return
324
+ try {
325
+ const objStr = this._buffer.substring(0, index + 1);
326
+ ret = JSON.parse(objStr);
327
+ // We only get here if it parsed it ok
328
+ // If we did turn it into an object, remove it from the buffer
329
+ this._buffer = this._buffer.slice(index + 1);
330
+ }
331
+ catch (xx) {
332
+ // It didn't parse it correctly, so we swallow the exception and continue
333
+ }
334
+ }
335
+ return ret;
336
+ }
337
+ _simplifyObject(obj) {
338
+ return simpleValue(obj);
339
+ }
340
+ /**
341
+ * Register that we have another chunk available for consumption.
342
+ * If we are waiting for a chunk, resolve the promise waiting for it immediately.
343
+ * If not, then add it to the queue.
344
+ * @param chunk
345
+ */
346
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
347
+ _handleChunk(chunk) {
348
+ if (this._chunkPending) {
349
+ this._chunkResolution(chunk);
350
+ this._chunkPending = null;
351
+ }
352
+ else {
353
+ this._chunkQueue.push(chunk);
354
+ }
355
+ }
356
+ /**
357
+ * Get the next chunk that is coming from the stream.
358
+ * This chunk may be null, usually indicating the last chunk in the stream.
359
+ */
360
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
361
+ async nextChunk() {
362
+ if (this._chunkQueue.length > 0) {
363
+ // If there is data in the queue, return the next queue chunk
364
+ return this._chunkQueue.shift();
365
+ }
366
+ else {
367
+ // Otherwise, set up a promise that handleChunk will cause to be resolved
368
+ this._chunkPending = new Promise((resolve) => {
369
+ this._chunkResolution = resolve;
370
+ });
371
+ return this._chunkPending;
372
+ }
373
+ }
374
+ /**
375
+ * Is the stream done?
376
+ * A stream is only done if all of the following are true:
377
+ * - There is no more data to be added to the text buffer
378
+ * - There is no more data in the text buffer
379
+ * - There are no chunks that are waiting to be consumed
380
+ */
381
+ get streamDone() {
382
+ return (!this._bufferOpen &&
383
+ this._buffer.length === 0 &&
384
+ this._chunkQueue.length === 0 &&
385
+ this._chunkPending === null);
386
+ }
387
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.GAuthClient = void 0;
4
+ const google_auth_library_1 = require("google-auth-library");
5
+ const googlevertexai_connection_js_1 = require("./googlevertexai-connection.cjs");
6
+ class GoogleVertexAINodeStream extends googlevertexai_connection_js_1.GoogleVertexAIStream {
7
+ constructor(data) {
8
+ super();
9
+ data.on("data", (data) => this.appendBuffer(data.toString()));
10
+ data.on("end", () => this.closeBuffer());
11
+ }
12
+ }
13
+ class GAuthClient {
14
+ constructor(options) {
15
+ Object.defineProperty(this, "gauth", {
16
+ enumerable: true,
17
+ configurable: true,
18
+ writable: true,
19
+ value: void 0
20
+ });
21
+ this.gauth = new google_auth_library_1.GoogleAuth(options);
22
+ }
23
+ async getProjectId() {
24
+ return this.gauth.getProjectId();
25
+ }
26
+ async request(opts) {
27
+ const ret = await this.gauth.request(opts);
28
+ return opts.responseType !== "stream"
29
+ ? ret
30
+ : {
31
+ ...ret,
32
+ data: new GoogleVertexAINodeStream(ret.data),
33
+ };
34
+ }
35
+ }
36
+ exports.GAuthClient = GAuthClient;
@@ -0,0 +1,8 @@
1
+ import { GoogleAuth, GoogleAuthOptions } from "google-auth-library";
2
+ import { GoogleAbstractedClient, GoogleAbstractedClientOps } from "../types/googlevertexai-types.js";
3
+ export declare class GAuthClient implements GoogleAbstractedClient {
4
+ gauth: GoogleAuth;
5
+ constructor(options?: GoogleAuthOptions);
6
+ getProjectId(): Promise<string>;
7
+ request(opts: GoogleAbstractedClientOps): Promise<unknown>;
8
+ }
@@ -0,0 +1,32 @@
1
+ import { GoogleAuth } from "google-auth-library";
2
+ import { GoogleVertexAIStream } from "./googlevertexai-connection.js";
3
+ class GoogleVertexAINodeStream extends GoogleVertexAIStream {
4
+ constructor(data) {
5
+ super();
6
+ data.on("data", (data) => this.appendBuffer(data.toString()));
7
+ data.on("end", () => this.closeBuffer());
8
+ }
9
+ }
10
+ export class GAuthClient {
11
+ constructor(options) {
12
+ Object.defineProperty(this, "gauth", {
13
+ enumerable: true,
14
+ configurable: true,
15
+ writable: true,
16
+ value: void 0
17
+ });
18
+ this.gauth = new GoogleAuth(options);
19
+ }
20
+ async getProjectId() {
21
+ return this.gauth.getProjectId();
22
+ }
23
+ async request(opts) {
24
+ const ret = await this.gauth.request(opts);
25
+ return opts.responseType !== "stream"
26
+ ? ret
27
+ : {
28
+ ...ret,
29
+ data: new GoogleVertexAINodeStream(ret.data),
30
+ };
31
+ }
32
+ }
@@ -3,6 +3,40 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.WebGoogleAuth = void 0;
4
4
  const google_1 = require("web-auth-library/google");
5
5
  const env_js_1 = require("./env.cjs");
6
+ const googlevertexai_connection_js_1 = require("./googlevertexai-connection.cjs");
7
+ class GoogleVertexAIResponseStream extends googlevertexai_connection_js_1.GoogleVertexAIStream {
8
+ constructor(body) {
9
+ super();
10
+ Object.defineProperty(this, "decoder", {
11
+ enumerable: true,
12
+ configurable: true,
13
+ writable: true,
14
+ value: void 0
15
+ });
16
+ this.decoder = new TextDecoder();
17
+ if (body) {
18
+ void this.run(body);
19
+ }
20
+ else {
21
+ console.error("Unexpected empty body while streaming");
22
+ }
23
+ }
24
+ async run(body) {
25
+ const reader = body.getReader();
26
+ let isDone = false;
27
+ while (!isDone) {
28
+ const { value, done } = await reader.read();
29
+ if (!done) {
30
+ const svalue = this.decoder.decode(value);
31
+ this.appendBuffer(svalue);
32
+ }
33
+ else {
34
+ isDone = done;
35
+ this.closeBuffer();
36
+ }
37
+ }
38
+ }
39
+ }
6
40
  class WebGoogleAuth {
7
41
  constructor(options) {
8
42
  Object.defineProperty(this, "options", {
@@ -15,7 +49,7 @@ class WebGoogleAuth {
15
49
  const credentials = options?.credentials ??
16
50
  (0, env_js_1.getEnvironmentVariable)("GOOGLE_VERTEX_AI_WEB_CREDENTIALS");
17
51
  if (credentials === undefined)
18
- throw new Error(`Credentials not found. Please set the GOOGLE_VERTEX_AI_WEB_CREDENTIALS or pass credentials into "authOptions.credentials".`);
52
+ throw new Error(`Credentials not found. Please set the GOOGLE_VERTEX_AI_WEB_CREDENTIALS environment variable or pass credentials into "authOptions.credentials".`);
19
53
  const scope = options?.scope ?? "https://www.googleapis.com/auth/cloud-platform";
20
54
  this.options = { ...options, accessToken, credentials, scope };
21
55
  }
@@ -48,7 +82,9 @@ class WebGoogleAuth {
48
82
  throw error;
49
83
  }
50
84
  return {
51
- data: await res.json(),
85
+ data: opts.responseType === "json"
86
+ ? await res.json()
87
+ : new GoogleVertexAIResponseStream(res.body),
52
88
  config: {},
53
89
  status: res.status,
54
90
  statusText: res.statusText,
@@ -1,5 +1,5 @@
1
1
  import { Credentials } from "web-auth-library/google";
2
- import type { GoogleAbstractedClient } from "../types/googlevertexai-types.js";
2
+ import type { GoogleAbstractedClient, GoogleAbstractedClientOps } from "../types/googlevertexai-types.js";
3
3
  export type WebGoogleAuthOptions = {
4
4
  credentials: string | Credentials;
5
5
  scope?: string | string[];
@@ -9,11 +9,7 @@ export declare class WebGoogleAuth implements GoogleAbstractedClient {
9
9
  options: WebGoogleAuthOptions;
10
10
  constructor(options?: WebGoogleAuthOptions);
11
11
  getProjectId(): Promise<string>;
12
- request(opts: {
13
- url?: string;
14
- method?: string;
15
- data?: unknown;
16
- }): Promise<{
12
+ request(opts: GoogleAbstractedClientOps): Promise<{
17
13
  data: any;
18
14
  config: {};
19
15
  status: number;
@@ -1,5 +1,39 @@
1
1
  import { getAccessToken, getCredentials, } from "web-auth-library/google";
2
2
  import { getEnvironmentVariable } from "./env.js";
3
+ import { GoogleVertexAIStream } from "./googlevertexai-connection.js";
4
+ class GoogleVertexAIResponseStream extends GoogleVertexAIStream {
5
+ constructor(body) {
6
+ super();
7
+ Object.defineProperty(this, "decoder", {
8
+ enumerable: true,
9
+ configurable: true,
10
+ writable: true,
11
+ value: void 0
12
+ });
13
+ this.decoder = new TextDecoder();
14
+ if (body) {
15
+ void this.run(body);
16
+ }
17
+ else {
18
+ console.error("Unexpected empty body while streaming");
19
+ }
20
+ }
21
+ async run(body) {
22
+ const reader = body.getReader();
23
+ let isDone = false;
24
+ while (!isDone) {
25
+ const { value, done } = await reader.read();
26
+ if (!done) {
27
+ const svalue = this.decoder.decode(value);
28
+ this.appendBuffer(svalue);
29
+ }
30
+ else {
31
+ isDone = done;
32
+ this.closeBuffer();
33
+ }
34
+ }
35
+ }
36
+ }
3
37
  export class WebGoogleAuth {
4
38
  constructor(options) {
5
39
  Object.defineProperty(this, "options", {
@@ -12,7 +46,7 @@ export class WebGoogleAuth {
12
46
  const credentials = options?.credentials ??
13
47
  getEnvironmentVariable("GOOGLE_VERTEX_AI_WEB_CREDENTIALS");
14
48
  if (credentials === undefined)
15
- throw new Error(`Credentials not found. Please set the GOOGLE_VERTEX_AI_WEB_CREDENTIALS or pass credentials into "authOptions.credentials".`);
49
+ throw new Error(`Credentials not found. Please set the GOOGLE_VERTEX_AI_WEB_CREDENTIALS environment variable or pass credentials into "authOptions.credentials".`);
16
50
  const scope = options?.scope ?? "https://www.googleapis.com/auth/cloud-platform";
17
51
  this.options = { ...options, accessToken, credentials, scope };
18
52
  }
@@ -45,7 +79,9 @@ export class WebGoogleAuth {
45
79
  throw error;
46
80
  }
47
81
  return {
48
- data: await res.json(),
82
+ data: opts.responseType === "json"
83
+ ? await res.json()
84
+ : new GoogleVertexAIResponseStream(res.body),
49
85
  config: {},
50
86
  status: res.status,
51
87
  statusText: res.statusText,