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
@@ -47,6 +47,12 @@ class ZepRetriever extends retriever_js_1.BaseRetriever {
47
47
  writable: true,
48
48
  value: void 0
49
49
  });
50
+ Object.defineProperty(this, "searchScope", {
51
+ enumerable: true,
52
+ configurable: true,
53
+ writable: true,
54
+ value: void 0
55
+ });
50
56
  Object.defineProperty(this, "searchType", {
51
57
  enumerable: true,
52
58
  configurable: true,
@@ -67,17 +73,18 @@ class ZepRetriever extends retriever_js_1.BaseRetriever {
67
73
  });
68
74
  this.sessionId = config.sessionId;
69
75
  this.topK = config.topK;
76
+ this.searchScope = config.searchScope;
70
77
  this.searchType = config.searchType;
71
78
  this.mmrLambda = config.mmrLambda;
72
79
  this.filter = config.filter;
73
80
  this.zepClientPromise = zep_js_1.ZepClient.init(config.url, config.apiKey);
74
81
  }
75
82
  /**
76
- * Converts an array of search results to an array of Document objects.
83
+ * Converts an array of message search results to an array of Document objects.
77
84
  * @param {MemorySearchResult[]} results - The array of search results.
78
85
  * @returns {Document[]} An array of Document objects representing the search results.
79
86
  */
80
- searchResultToDoc(results) {
87
+ searchMessageResultToDoc(results) {
81
88
  return results
82
89
  .filter((r) => r.message)
83
90
  .map(({ message: { content, metadata: messageMetadata } = {}, dist, ...rest }) => new document_js_1.Document({
@@ -85,6 +92,19 @@ class ZepRetriever extends retriever_js_1.BaseRetriever {
85
92
  metadata: { score: dist, ...messageMetadata, ...rest },
86
93
  }));
87
94
  }
95
+ /**
96
+ * Converts an array of summary search results to an array of Document objects.
97
+ * @param {MemorySearchResult[]} results - The array of search results.
98
+ * @returns {Document[]} An array of Document objects representing the search results.
99
+ */
100
+ searchSummaryResultToDoc(results) {
101
+ return results
102
+ .filter((r) => r.summary)
103
+ .map(({ summary: { content, metadata: summaryMetadata } = {}, dist, ...rest }) => new document_js_1.Document({
104
+ pageContent: content ?? "",
105
+ metadata: { score: dist, ...summaryMetadata, ...rest },
106
+ }));
107
+ }
88
108
  /**
89
109
  * Retrieves the relevant documents based on the given query.
90
110
  * @param {string} query - The query string.
@@ -94,6 +114,7 @@ class ZepRetriever extends retriever_js_1.BaseRetriever {
94
114
  const payload = {
95
115
  text: query,
96
116
  metadata: this.filter,
117
+ search_scope: this.searchScope,
97
118
  search_type: this.searchType,
98
119
  mmr_lambda: this.mmrLambda,
99
120
  };
@@ -104,7 +125,9 @@ class ZepRetriever extends retriever_js_1.BaseRetriever {
104
125
  }
105
126
  try {
106
127
  const results = await zepClient.memory.searchMemory(this.sessionId, payload, this.topK);
107
- return this.searchResultToDoc(results);
128
+ return this.searchScope === "summary"
129
+ ? this.searchSummaryResultToDoc(results)
130
+ : this.searchMessageResultToDoc(results);
108
131
  }
109
132
  catch (error) {
110
133
  // eslint-disable-next-line no-instanceof/no-instanceof
@@ -9,6 +9,7 @@ import { Document } from "../document.js";
9
9
  * @argument {string} url - The URL of the Zep API.
10
10
  * @argument {number} [topK] - The number of results to return.
11
11
  * @argument {string} [apiKey] - The API key for the Zep API.
12
+ * @argument [searchScope] [searchScope] - The scope of the search: "messages" or "summary".
12
13
  * @argument [searchType] [searchType] - The type of search to perform: "similarity" or "mmr".
13
14
  * @argument {number} [mmrLambda] - The lambda value for the MMR search.
14
15
  * @argument {Record<string, unknown>} [filter] - The metadata filter to apply to the search.
@@ -18,6 +19,7 @@ export interface ZepRetrieverConfig extends BaseRetrieverInput {
18
19
  url: string;
19
20
  topK?: number;
20
21
  apiKey?: string;
22
+ searchScope?: "messages" | "summary";
21
23
  searchType?: "similarity" | "mmr";
22
24
  mmrLambda?: number;
23
25
  filter?: Record<string, unknown>;
@@ -38,16 +40,23 @@ export declare class ZepRetriever extends BaseRetriever {
38
40
  zepClientPromise: Promise<ZepClient>;
39
41
  private sessionId;
40
42
  private topK?;
43
+ private searchScope?;
41
44
  private searchType?;
42
45
  private mmrLambda?;
43
46
  private filter?;
44
47
  constructor(config: ZepRetrieverConfig);
45
48
  /**
46
- * Converts an array of search results to an array of Document objects.
49
+ * Converts an array of message search results to an array of Document objects.
47
50
  * @param {MemorySearchResult[]} results - The array of search results.
48
51
  * @returns {Document[]} An array of Document objects representing the search results.
49
52
  */
50
- private searchResultToDoc;
53
+ private searchMessageResultToDoc;
54
+ /**
55
+ * Converts an array of summary search results to an array of Document objects.
56
+ * @param {MemorySearchResult[]} results - The array of search results.
57
+ * @returns {Document[]} An array of Document objects representing the search results.
58
+ */
59
+ private searchSummaryResultToDoc;
51
60
  /**
52
61
  * Retrieves the relevant documents based on the given query.
53
62
  * @param {string} query - The query string.
@@ -44,6 +44,12 @@ export class ZepRetriever extends BaseRetriever {
44
44
  writable: true,
45
45
  value: void 0
46
46
  });
47
+ Object.defineProperty(this, "searchScope", {
48
+ enumerable: true,
49
+ configurable: true,
50
+ writable: true,
51
+ value: void 0
52
+ });
47
53
  Object.defineProperty(this, "searchType", {
48
54
  enumerable: true,
49
55
  configurable: true,
@@ -64,17 +70,18 @@ export class ZepRetriever extends BaseRetriever {
64
70
  });
65
71
  this.sessionId = config.sessionId;
66
72
  this.topK = config.topK;
73
+ this.searchScope = config.searchScope;
67
74
  this.searchType = config.searchType;
68
75
  this.mmrLambda = config.mmrLambda;
69
76
  this.filter = config.filter;
70
77
  this.zepClientPromise = ZepClient.init(config.url, config.apiKey);
71
78
  }
72
79
  /**
73
- * Converts an array of search results to an array of Document objects.
80
+ * Converts an array of message search results to an array of Document objects.
74
81
  * @param {MemorySearchResult[]} results - The array of search results.
75
82
  * @returns {Document[]} An array of Document objects representing the search results.
76
83
  */
77
- searchResultToDoc(results) {
84
+ searchMessageResultToDoc(results) {
78
85
  return results
79
86
  .filter((r) => r.message)
80
87
  .map(({ message: { content, metadata: messageMetadata } = {}, dist, ...rest }) => new Document({
@@ -82,6 +89,19 @@ export class ZepRetriever extends BaseRetriever {
82
89
  metadata: { score: dist, ...messageMetadata, ...rest },
83
90
  }));
84
91
  }
92
+ /**
93
+ * Converts an array of summary search results to an array of Document objects.
94
+ * @param {MemorySearchResult[]} results - The array of search results.
95
+ * @returns {Document[]} An array of Document objects representing the search results.
96
+ */
97
+ searchSummaryResultToDoc(results) {
98
+ return results
99
+ .filter((r) => r.summary)
100
+ .map(({ summary: { content, metadata: summaryMetadata } = {}, dist, ...rest }) => new Document({
101
+ pageContent: content ?? "",
102
+ metadata: { score: dist, ...summaryMetadata, ...rest },
103
+ }));
104
+ }
85
105
  /**
86
106
  * Retrieves the relevant documents based on the given query.
87
107
  * @param {string} query - The query string.
@@ -91,6 +111,7 @@ export class ZepRetriever extends BaseRetriever {
91
111
  const payload = {
92
112
  text: query,
93
113
  metadata: this.filter,
114
+ search_scope: this.searchScope,
94
115
  search_type: this.searchType,
95
116
  mmr_lambda: this.mmrLambda,
96
117
  };
@@ -101,7 +122,9 @@ export class ZepRetriever extends BaseRetriever {
101
122
  }
102
123
  try {
103
124
  const results = await zepClient.memory.searchMemory(this.sessionId, payload, this.topK);
104
- return this.searchResultToDoc(results);
125
+ return this.searchScope === "summary"
126
+ ? this.searchSummaryResultToDoc(results)
127
+ : this.searchMessageResultToDoc(results);
105
128
  }
106
129
  catch (error) {
107
130
  // eslint-disable-next-line no-instanceof/no-instanceof
@@ -45,19 +45,21 @@ export interface GoogleVertexAIBaseLLMInput<AuthOptions> extends BaseLLMParams,
45
45
  export interface GoogleResponse {
46
46
  data: any;
47
47
  }
48
- export interface GoogleVertexAIBasePrediction extends GoogleResponse {
48
+ export interface GoogleVertexAIBasePrediction {
49
49
  safetyAttributes?: any;
50
50
  }
51
- export interface GoogleVertexAILLMResponse<PredictionType extends GoogleVertexAIBasePrediction> {
52
- data: {
53
- predictions: PredictionType[];
54
- };
51
+ export interface GoogleVertexAILLMPredictions<PredictionType extends GoogleVertexAIBasePrediction> {
52
+ predictions: PredictionType[];
55
53
  }
54
+ export type GoogleAbstractedClientOpsMethod = "GET" | "POST";
55
+ export type GoogleAbstractedClientOpsResponseType = "json" | "stream";
56
+ export type GoogleAbstractedClientOps = {
57
+ url?: string;
58
+ method?: GoogleAbstractedClientOpsMethod;
59
+ data?: unknown;
60
+ responseType?: GoogleAbstractedClientOpsResponseType;
61
+ };
56
62
  export interface GoogleAbstractedClient {
57
- request: (opts: {
58
- url?: string;
59
- method?: "GET" | "POST";
60
- data?: unknown;
61
- }) => unknown;
63
+ request: (opts: GoogleAbstractedClientOps) => unknown;
62
64
  getProjectId: () => Promise<string>;
63
65
  }
@@ -33,6 +33,8 @@ export interface BaseBedrockInput {
33
33
  stopSequences?: string[];
34
34
  /** Additional kwargs to pass to the model. */
35
35
  modelKwargs?: Record<string, unknown>;
36
+ /** Whether or not to stream responses */
37
+ streaming: boolean;
36
38
  }
37
39
  type Dict = {
38
40
  [key: string]: unknown;
@@ -1,8 +1,8 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.GoogleVertexAILLMConnection = exports.GoogleVertexAIConnection = exports.GoogleConnection = void 0;
3
+ exports.GoogleVertexAIStream = exports.GoogleVertexAILLMConnection = exports.simpleValue = exports.complexValue = exports.GoogleVertexAIConnection = exports.GoogleConnection = void 0;
4
4
  class GoogleConnection {
5
- constructor(caller, client) {
5
+ constructor(caller, client, streaming) {
6
6
  Object.defineProperty(this, "caller", {
7
7
  enumerable: true,
8
8
  configurable: true,
@@ -15,13 +15,19 @@ class GoogleConnection {
15
15
  writable: true,
16
16
  value: void 0
17
17
  });
18
+ Object.defineProperty(this, "streaming", {
19
+ enumerable: true,
20
+ configurable: true,
21
+ writable: true,
22
+ value: void 0
23
+ });
18
24
  this.caller = caller;
19
25
  this.client = client;
26
+ this.streaming = streaming ?? false;
20
27
  }
21
28
  async _request(data, options) {
22
29
  const url = await this.buildUrl();
23
30
  const method = this.buildMethod();
24
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
25
31
  const opts = {
26
32
  url,
27
33
  method,
@@ -29,6 +35,12 @@ class GoogleConnection {
29
35
  if (data && method === "POST") {
30
36
  opts.data = data;
31
37
  }
38
+ if (this.streaming) {
39
+ opts.responseType = "stream";
40
+ }
41
+ else {
42
+ opts.responseType = "json";
43
+ }
32
44
  try {
33
45
  const callResponse = await this.caller.callWithOptions({ signal: options?.signal }, async () => this.client.request(opts));
34
46
  const response = callResponse; // Done for typecast safety, I guess
@@ -42,8 +54,8 @@ class GoogleConnection {
42
54
  }
43
55
  exports.GoogleConnection = GoogleConnection;
44
56
  class GoogleVertexAIConnection extends GoogleConnection {
45
- constructor(fields, caller, client) {
46
- super(caller, client);
57
+ constructor(fields, caller, client, streaming) {
58
+ super(caller, client, streaming);
47
59
  Object.defineProperty(this, "endpoint", {
48
60
  enumerable: true,
49
61
  configurable: true,
@@ -73,9 +85,86 @@ class GoogleVertexAIConnection extends GoogleConnection {
73
85
  }
74
86
  }
75
87
  exports.GoogleVertexAIConnection = GoogleVertexAIConnection;
88
+ function complexValue(value) {
89
+ if (value === null || typeof value === "undefined") {
90
+ // I dunno what to put here. An error, probably
91
+ return undefined;
92
+ }
93
+ else if (typeof value === "object") {
94
+ if (Array.isArray(value)) {
95
+ return {
96
+ list_val: value.map((avalue) => complexValue(avalue)),
97
+ };
98
+ }
99
+ else {
100
+ const ret = {};
101
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
102
+ const v = value;
103
+ Object.keys(v).forEach((key) => {
104
+ ret[key] = complexValue(v[key]);
105
+ });
106
+ return { struct_val: ret };
107
+ }
108
+ }
109
+ else if (typeof value === "number") {
110
+ if (Number.isInteger(value)) {
111
+ return { int_val: value };
112
+ }
113
+ else {
114
+ return { float_val: value };
115
+ }
116
+ }
117
+ else {
118
+ return {
119
+ string_val: [value],
120
+ };
121
+ }
122
+ }
123
+ exports.complexValue = complexValue;
124
+ function simpleValue(val) {
125
+ if (val && typeof val === "object" && !Array.isArray(val)) {
126
+ // eslint-disable-next-line no-prototype-builtins
127
+ if (val.hasOwnProperty("stringVal")) {
128
+ return val.stringVal[0];
129
+ // eslint-disable-next-line no-prototype-builtins
130
+ }
131
+ else if (val.hasOwnProperty("boolVal")) {
132
+ return val.boolVal[0];
133
+ // eslint-disable-next-line no-prototype-builtins
134
+ }
135
+ else if (val.hasOwnProperty("listVal")) {
136
+ const { listVal } = val;
137
+ return listVal.map((aval) => simpleValue(aval));
138
+ // eslint-disable-next-line no-prototype-builtins
139
+ }
140
+ else if (val.hasOwnProperty("structVal")) {
141
+ const ret = {};
142
+ const struct = val.structVal;
143
+ Object.keys(struct).forEach((key) => {
144
+ ret[key] = simpleValue(struct[key]);
145
+ });
146
+ return ret;
147
+ }
148
+ else {
149
+ const ret = {};
150
+ const struct = val;
151
+ Object.keys(struct).forEach((key) => {
152
+ ret[key] = simpleValue(struct[key]);
153
+ });
154
+ return ret;
155
+ }
156
+ }
157
+ else if (Array.isArray(val)) {
158
+ return val.map((aval) => simpleValue(aval));
159
+ }
160
+ else {
161
+ return val;
162
+ }
163
+ }
164
+ exports.simpleValue = simpleValue;
76
165
  class GoogleVertexAILLMConnection extends GoogleVertexAIConnection {
77
- constructor(fields, caller, client) {
78
- super(fields, caller, client);
166
+ constructor(fields, caller, client, streaming) {
167
+ super(fields, caller, client, streaming);
79
168
  Object.defineProperty(this, "model", {
80
169
  enumerable: true,
81
170
  configurable: true,
@@ -93,16 +182,215 @@ class GoogleVertexAILLMConnection extends GoogleVertexAIConnection {
93
182
  }
94
183
  async buildUrl() {
95
184
  const projectId = await this.client.getProjectId();
96
- const url = `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:predict`;
185
+ const method = this.streaming ? "serverStreamingPredict" : "predict";
186
+ const url = `https://${this.endpoint}/v1/projects/${projectId}/locations/${this.location}/publishers/google/models/${this.model}:${method}`;
97
187
  return url;
98
188
  }
99
- async request(instances, parameters, options) {
100
- const data = {
189
+ formatStreamingData(inputs, parameters) {
190
+ return {
191
+ inputs: [inputs.map((i) => complexValue(i))],
192
+ parameters: complexValue(parameters),
193
+ };
194
+ }
195
+ formatStandardData(instances, parameters) {
196
+ return {
101
197
  instances,
102
198
  parameters,
103
199
  };
200
+ }
201
+ formatData(instances, parameters) {
202
+ return this.streaming
203
+ ? this.formatStreamingData(instances, parameters)
204
+ : this.formatStandardData(instances, parameters);
205
+ }
206
+ async request(instances, parameters, options) {
207
+ const data = this.formatData(instances, parameters);
104
208
  const response = await this._request(data, options);
105
209
  return response;
106
210
  }
107
211
  }
108
212
  exports.GoogleVertexAILLMConnection = GoogleVertexAILLMConnection;
213
+ class GoogleVertexAIStream {
214
+ constructor() {
215
+ Object.defineProperty(this, "_buffer", {
216
+ enumerable: true,
217
+ configurable: true,
218
+ writable: true,
219
+ value: ""
220
+ });
221
+ Object.defineProperty(this, "_bufferOpen", {
222
+ enumerable: true,
223
+ configurable: true,
224
+ writable: true,
225
+ value: true
226
+ });
227
+ Object.defineProperty(this, "_firstRun", {
228
+ enumerable: true,
229
+ configurable: true,
230
+ writable: true,
231
+ value: true
232
+ });
233
+ // Set up a potential Promise that the handler can resolve.
234
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
235
+ Object.defineProperty(this, "_chunkResolution", {
236
+ enumerable: true,
237
+ configurable: true,
238
+ writable: true,
239
+ value: void 0
240
+ });
241
+ // If there is no Promise (it is null), the handler must add it to the queue
242
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
243
+ Object.defineProperty(this, "_chunkPending", {
244
+ enumerable: true,
245
+ configurable: true,
246
+ writable: true,
247
+ value: null
248
+ });
249
+ // A queue that will collect chunks while there is no Promise
250
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
251
+ Object.defineProperty(this, "_chunkQueue", {
252
+ enumerable: true,
253
+ configurable: true,
254
+ writable: true,
255
+ value: []
256
+ });
257
+ }
258
+ /**
259
+ * Add data to the buffer. This may cause chunks to be generated, if available.
260
+ * @param data
261
+ */
262
+ appendBuffer(data) {
263
+ this._buffer += data;
264
+ // Our first time, skip to the opening of the array
265
+ if (this._firstRun) {
266
+ this._skipTo("[");
267
+ this._firstRun = false;
268
+ }
269
+ this._parseBuffer();
270
+ }
271
+ /**
272
+ * Indicate there is no more data that will be added to the text buffer.
273
+ * This should be called when all the data has been read and added to indicate
274
+ * that we should process everything remaining in the buffer.
275
+ */
276
+ closeBuffer() {
277
+ this._bufferOpen = false;
278
+ this._parseBuffer();
279
+ }
280
+ /**
281
+ * Skip characters in the buffer till we get to the start of an object.
282
+ * Then attempt to read a full object.
283
+ * If we do read a full object, turn it into a chunk and send it to the chunk handler.
284
+ * Repeat this for as much as we can.
285
+ */
286
+ _parseBuffer() {
287
+ let obj = null;
288
+ do {
289
+ this._skipTo("{");
290
+ obj = this._getFullObject();
291
+ if (obj !== null) {
292
+ const chunk = this._simplifyObject(obj);
293
+ this._handleChunk(chunk);
294
+ }
295
+ } while (obj !== null);
296
+ if (!this._bufferOpen) {
297
+ // No more data will be added, and we have parsed everything we could,
298
+ // so everything else is garbage.
299
+ this._handleChunk(null);
300
+ this._buffer = "";
301
+ }
302
+ }
303
+ /**
304
+ * If the string is present, move the start of the buffer to the first occurrence
305
+ * of that string. This is useful for skipping over elements or parts that we're not
306
+ * really interested in parsing. (ie - the opening characters, comma separators, etc.)
307
+ * @param start The string to start the buffer with
308
+ */
309
+ _skipTo(start) {
310
+ const index = this._buffer.indexOf(start);
311
+ if (index > 0) {
312
+ this._buffer = this._buffer.slice(index);
313
+ }
314
+ }
315
+ /**
316
+ * Given what is in the buffer, parse a single object out of it.
317
+ * If a complete object isn't available, return null.
318
+ * Assumes that we are at the start of an object to parse.
319
+ */
320
+ _getFullObject() {
321
+ let ret = null;
322
+ // Loop while we don't have something to return AND we have something in the buffer
323
+ let index = 0;
324
+ while (ret === null && this._buffer.length > index) {
325
+ // Advance to the next close bracket after our current index
326
+ index = this._buffer.indexOf("}", index + 1);
327
+ // If we don't find one, exit with null
328
+ if (index === -1) {
329
+ return null;
330
+ }
331
+ // If we have one, try to turn it into an object to return
332
+ try {
333
+ const objStr = this._buffer.substring(0, index + 1);
334
+ ret = JSON.parse(objStr);
335
+ // We only get here if it parsed it ok
336
+ // If we did turn it into an object, remove it from the buffer
337
+ this._buffer = this._buffer.slice(index + 1);
338
+ }
339
+ catch (xx) {
340
+ // It didn't parse it correctly, so we swallow the exception and continue
341
+ }
342
+ }
343
+ return ret;
344
+ }
345
+ _simplifyObject(obj) {
346
+ return simpleValue(obj);
347
+ }
348
+ /**
349
+ * Register that we have another chunk available for consumption.
350
+ * If we are waiting for a chunk, resolve the promise waiting for it immediately.
351
+ * If not, then add it to the queue.
352
+ * @param chunk
353
+ */
354
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
355
+ _handleChunk(chunk) {
356
+ if (this._chunkPending) {
357
+ this._chunkResolution(chunk);
358
+ this._chunkPending = null;
359
+ }
360
+ else {
361
+ this._chunkQueue.push(chunk);
362
+ }
363
+ }
364
+ /**
365
+ * Get the next chunk that is coming from the stream.
366
+ * This chunk may be null, usually indicating the last chunk in the stream.
367
+ */
368
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
369
+ async nextChunk() {
370
+ if (this._chunkQueue.length > 0) {
371
+ // If there is data in the queue, return the next queue chunk
372
+ return this._chunkQueue.shift();
373
+ }
374
+ else {
375
+ // Otherwise, set up a promise that handleChunk will cause to be resolved
376
+ this._chunkPending = new Promise((resolve) => {
377
+ this._chunkResolution = resolve;
378
+ });
379
+ return this._chunkPending;
380
+ }
381
+ }
382
+ /**
383
+ * Is the stream done?
384
+ * A stream is only done if all of the following are true:
385
+ * - There is no more data to be added to the text buffer
386
+ * - There is no more data in the text buffer
387
+ * - There are no chunks that are waiting to be consumed
388
+ */
389
+ get streamDone() {
390
+ return (!this._bufferOpen &&
391
+ this._buffer.length === 0 &&
392
+ this._chunkQueue.length === 0 &&
393
+ this._chunkPending === null);
394
+ }
395
+ }
396
+ exports.GoogleVertexAIStream = GoogleVertexAIStream;