@weaviate/agents 0.0.0-stage → 0.0.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.
Files changed (35) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +130 -2
  3. package/dist/index.d.ts +1 -0
  4. package/dist/index.js +1 -0
  5. package/dist/query/agent.d.ts +539 -0
  6. package/dist/query/agent.js +373 -0
  7. package/dist/query/agent.test.d.ts +1 -0
  8. package/dist/query/agent.test.js +1118 -0
  9. package/dist/query/collection.d.ts +22 -0
  10. package/dist/query/collection.js +12 -0
  11. package/dist/query/connection.d.ts +10 -0
  12. package/dist/query/connection.js +19 -0
  13. package/dist/query/filter.d.ts +2 -0
  14. package/dist/query/filter.js +20 -0
  15. package/dist/query/index.d.ts +4 -0
  16. package/dist/query/index.js +3 -0
  17. package/dist/query/media.d.ts +25 -0
  18. package/dist/query/media.js +24 -0
  19. package/dist/query/response/api-response-mapping.d.ts +3 -0
  20. package/dist/query/response/api-response-mapping.js +172 -0
  21. package/dist/query/response/api-response.d.ts +219 -0
  22. package/dist/query/response/api-response.js +1 -0
  23. package/dist/query/response/error.d.ts +6 -0
  24. package/dist/query/response/error.js +34 -0
  25. package/dist/query/response/index.d.ts +2 -0
  26. package/dist/query/response/index.js +2 -0
  27. package/dist/query/response/response-mapping.d.ts +23 -0
  28. package/dist/query/response/response-mapping.js +308 -0
  29. package/dist/query/response/response.d.ts +332 -0
  30. package/dist/query/response/response.js +44 -0
  31. package/dist/query/response/server-sent-events.d.ts +14 -0
  32. package/dist/query/response/server-sent-events.js +85 -0
  33. package/dist/query/search.d.ts +37 -0
  34. package/dist/query/search.js +87 -0
  35. package/package.json +46 -3
@@ -0,0 +1,373 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }
11
+ var __asyncValues = (this && this.__asyncValues) || function (o) {
12
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
13
+ var m = o[Symbol.asyncIterator], i;
14
+ return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i);
15
+ function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }
16
+ function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }
17
+ };
18
+ var __asyncGenerator = (this && this.__asyncGenerator) || function (thisArg, _arguments, generator) {
19
+ if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
20
+ var g = generator.apply(thisArg, _arguments || []), i, q = [];
21
+ return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i;
22
+ function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; }
23
+ function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } }
24
+ function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }
25
+ function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }
26
+ function fulfill(value) { resume("next", value); }
27
+ function reject(value) { resume("throw", value); }
28
+ function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }
29
+ };
30
+ import { z } from "zod";
31
+ import { mapResponse, mapProgressMessageFromSSE, mapStreamedTokensFromSSE, mapAskModeResponse, mapSuggestQueryResponse, isZodSchema, } from "./response/response-mapping.js";
32
+ import { mapApiResponse } from "./response/api-response-mapping.js";
33
+ import { fetchServerSentEvents } from "./response/server-sent-events.js";
34
+ import { mapCollections, } from "./collection.js";
35
+ import { handleError } from "./response/error.js";
36
+ import { QueryAgentSearcher } from "./search.js";
37
+ import { getHeaders } from "./connection.js";
38
+ import { hideImageBase64 } from "./media.js";
39
+ /**
40
+ * An agent for executing agentic queries against Weaviate.
41
+ *
42
+ * For more information, see the [Weaviate Agents - Query Agent Docs](https://weaviate.io/developers/agents).
43
+ */
44
+ export class QueryAgent {
45
+ /**
46
+ * Initialize the Query Agent.
47
+ *
48
+ * @param client - The Weaviate client connected to a Weaviate Cloud cluster.
49
+ * @param options - Configuration for the agent.
50
+ * @param options.collections - The collections to query. Either a list of strings, or a list of
51
+ * {@link QueryAgentCollectionConfig} objects. Will be overridden if passed in any of the agent's
52
+ * methods that support it.
53
+ * @param options.systemPrompt - Optional prompt to control the tone, format, and style of the
54
+ * agent's final response. This prompt is both passed to the query writer agent, and applied
55
+ * when generating the answer after all research and data retrieval is complete.
56
+ * @param options.agentsHost - Optional host of the agents service.
57
+ */
58
+ constructor(client, { collections, systemPrompt, agentsHost = "https://api.agents.weaviate.io", } = {}) {
59
+ this.client = client;
60
+ this.validateCollections = (collections) => {
61
+ const targetCollections = collections !== null && collections !== void 0 ? collections : this.collections;
62
+ if (!targetCollections) {
63
+ throw Error("No collections provided to the query agent.");
64
+ }
65
+ return targetCollections;
66
+ };
67
+ this.collections = collections;
68
+ this.systemPrompt = systemPrompt;
69
+ this.agentsHost = agentsHost;
70
+ }
71
+ /**
72
+ * Run the query agent.
73
+ *
74
+ * @deprecated The `run` method is deprecated; use {@link ask} instead.
75
+ * @param query - The natural language query string for the agent.
76
+ * @param options - Options for this run.
77
+ * @param options.collections - The collections to query. Will override any collections passed in the constructor.
78
+ * @param options.context - Optional previous response from the agent.
79
+ * @returns The response from the query agent.
80
+ */
81
+ run(query_1) {
82
+ return __awaiter(this, arguments, void 0, function* (query, { collections, context } = {}) {
83
+ const targetCollections = collections !== null && collections !== void 0 ? collections : this.collections;
84
+ if (!targetCollections) {
85
+ throw Error("No collections provided to the query agent.");
86
+ }
87
+ const { host, bearerToken, headers } = yield this.client.getConnectionDetails();
88
+ const response = yield fetch(`${this.agentsHost}/agent/query`, {
89
+ method: "POST",
90
+ headers: {
91
+ "Content-Type": "application/json",
92
+ Authorization: bearerToken,
93
+ "X-Weaviate-Cluster-Url": host,
94
+ "X-Agent-Request-Origin": "typescript-client",
95
+ },
96
+ body: JSON.stringify({
97
+ headers,
98
+ query,
99
+ collections: mapCollections(targetCollections),
100
+ system_prompt: this.systemPrompt,
101
+ previous_response: context ? mapApiResponse(context) : undefined,
102
+ result_evaluation: "none",
103
+ }),
104
+ });
105
+ if (!response.ok) {
106
+ yield handleError(yield response.text());
107
+ }
108
+ return mapResponse(yield response.json());
109
+ });
110
+ }
111
+ ask(query_1) {
112
+ return __awaiter(this, arguments, void 0, function* (query, { collections, resultEvaluation, outputFormat, } = {}) {
113
+ const targetCollections = this.validateCollections(collections);
114
+ const { requestHeaders, connectionHeaders } = yield getHeaders(this.client);
115
+ const response = yield fetch(`${this.agentsHost}/query/ask`, {
116
+ method: "POST",
117
+ headers: requestHeaders,
118
+ body: JSON.stringify({
119
+ headers: connectionHeaders,
120
+ query: typeof query === "string" ? query : { messages: query },
121
+ collections: mapCollections(targetCollections),
122
+ system_prompt: this.systemPrompt,
123
+ result_evaluation: resultEvaluation !== null && resultEvaluation !== void 0 ? resultEvaluation : "none",
124
+ output_format: mapOutputFormat(outputFormat),
125
+ }),
126
+ });
127
+ if (!response.ok) {
128
+ yield handleError(yield response.text());
129
+ }
130
+ const json = yield response.json();
131
+ return outputFormat === undefined
132
+ ? mapAskModeResponse(json)
133
+ : mapAskModeResponse(json, outputFormat);
134
+ });
135
+ }
136
+ stream(query_1) {
137
+ return __asyncGenerator(this, arguments, function* stream_1(query, { collections, context, includeProgress, includeFinalState, } = {}) {
138
+ var _a, e_1, _b, _c;
139
+ const targetCollections = collections !== null && collections !== void 0 ? collections : this.collections;
140
+ if (!targetCollections) {
141
+ throw Error("No collections provided to the query agent.");
142
+ }
143
+ const { host, bearerToken, headers } = yield __await(this.client.getConnectionDetails());
144
+ const sseStream = fetchServerSentEvents(`${this.agentsHost}/agent/stream_query`, {
145
+ method: "POST",
146
+ headers: {
147
+ "Content-Type": "application/json",
148
+ Authorization: bearerToken,
149
+ "X-Weaviate-Cluster-Url": host,
150
+ "X-Agent-Request-Origin": "typescript-client",
151
+ },
152
+ body: JSON.stringify({
153
+ headers,
154
+ query,
155
+ collections: mapCollections(targetCollections),
156
+ system_prompt: this.systemPrompt,
157
+ previous_response: context ? mapApiResponse(context) : undefined,
158
+ include_progress: includeProgress !== null && includeProgress !== void 0 ? includeProgress : true,
159
+ include_final_state: includeFinalState !== null && includeFinalState !== void 0 ? includeFinalState : true,
160
+ result_evaluation: "none",
161
+ }),
162
+ });
163
+ try {
164
+ for (var _d = true, sseStream_1 = __asyncValues(sseStream), sseStream_1_1; sseStream_1_1 = yield __await(sseStream_1.next()), _a = sseStream_1_1.done, !_a; _d = true) {
165
+ _c = sseStream_1_1.value;
166
+ _d = false;
167
+ const event = _c;
168
+ if (event.event === "error") {
169
+ yield __await(handleError(event.data));
170
+ }
171
+ let output;
172
+ if (event.event === "progress_message") {
173
+ output = mapProgressMessageFromSSE(event);
174
+ }
175
+ else if (event.event === "streamed_tokens") {
176
+ output = mapStreamedTokensFromSSE(event);
177
+ }
178
+ else if (event.event === "final_state") {
179
+ output = mapResponse(JSON.parse(event.data));
180
+ }
181
+ else {
182
+ throw new Error(`Unexpected event type: ${event.event}: ${event.data}`);
183
+ }
184
+ yield yield __await(output);
185
+ }
186
+ }
187
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
188
+ finally {
189
+ try {
190
+ if (!_d && !_a && (_b = sseStream_1.return)) yield __await(_b.call(sseStream_1));
191
+ }
192
+ finally { if (e_1) throw e_1.error; }
193
+ }
194
+ });
195
+ }
196
+ askStream(query_1) {
197
+ return __asyncGenerator(this, arguments, function* askStream_1(query, { collections, includeProgress, includeFinalState, resultEvaluation, outputFormat, } = {}) {
198
+ var _a, e_2, _b, _c;
199
+ const targetCollections = collections !== null && collections !== void 0 ? collections : this.collections;
200
+ if (!targetCollections) {
201
+ throw Error("No collections provided to the query agent.");
202
+ }
203
+ const { host, bearerToken, headers } = yield __await(this.client.getConnectionDetails());
204
+ const sseStream = fetchServerSentEvents(`${this.agentsHost}/query/stream_ask`, {
205
+ method: "POST",
206
+ headers: {
207
+ "Content-Type": "application/json",
208
+ Authorization: bearerToken,
209
+ "X-Weaviate-Cluster-Url": host,
210
+ "X-Agent-Request-Origin": "typescript-client",
211
+ },
212
+ body: JSON.stringify({
213
+ headers,
214
+ query: typeof query === "string" ? query : { messages: query },
215
+ collections: mapCollections(targetCollections),
216
+ system_prompt: this.systemPrompt,
217
+ include_progress: includeProgress !== null && includeProgress !== void 0 ? includeProgress : true,
218
+ include_final_state: includeFinalState !== null && includeFinalState !== void 0 ? includeFinalState : true,
219
+ result_evaluation: resultEvaluation !== null && resultEvaluation !== void 0 ? resultEvaluation : "none",
220
+ output_format: mapOutputFormat(outputFormat),
221
+ }),
222
+ });
223
+ try {
224
+ for (var _d = true, sseStream_2 = __asyncValues(sseStream), sseStream_2_1; sseStream_2_1 = yield __await(sseStream_2.next()), _a = sseStream_2_1.done, !_a; _d = true) {
225
+ _c = sseStream_2_1.value;
226
+ _d = false;
227
+ const event = _c;
228
+ if (event.event === "error") {
229
+ yield __await(handleError(event.data));
230
+ }
231
+ let output;
232
+ if (event.event === "progress_message") {
233
+ output = mapProgressMessageFromSSE(event);
234
+ }
235
+ else if (event.event === "streamed_tokens") {
236
+ output = mapStreamedTokensFromSSE(event);
237
+ }
238
+ else if (event.event === "final_state") {
239
+ const finalState = JSON.parse(event.data);
240
+ output =
241
+ outputFormat === undefined
242
+ ? mapAskModeResponse(finalState)
243
+ : mapAskModeResponse(finalState, outputFormat);
244
+ }
245
+ else {
246
+ throw new Error(`Unexpected event type: ${event.event}: ${event.data}`);
247
+ }
248
+ yield yield __await(output);
249
+ }
250
+ }
251
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
252
+ finally {
253
+ try {
254
+ if (!_d && !_a && (_b = sseStream_2.return)) yield __await(_b.call(sseStream_2));
255
+ }
256
+ finally { if (e_2) throw e_2.error; }
257
+ }
258
+ });
259
+ }
260
+ /**
261
+ * Run the Query Agent search-only mode.
262
+ *
263
+ * Sends the initial search request and returns a {@link SearchModeResponse} containing the
264
+ * first page of results. To paginate, call `response.next({ limit, offset })` on the returned
265
+ * response. This reuses the same underlying searches to ensure a consistent result set across
266
+ * pages.
267
+ *
268
+ * @param query - The natural language query string, or a list of chat messages, for the agent.
269
+ * @param options - Options for this search invocation.
270
+ * @param options.limit - The maximum number of results to return for the first page. Defaults to 20.
271
+ * @param options.collections - The collections to query. Either a list of strings, or a list of
272
+ * {@link QueryAgentCollectionConfig} objects. Will override any collections passed in the constructor.
273
+ * @param options.diversityWeight - Optional number between `0.0` and `1.0` to diversify results
274
+ * with MMR reranking. Higher values push for more topical variety at the cost of relevance.
275
+ * Defaults to no diversity.
276
+ * @param options.filtering - The filtering strategy: `"recall"` for broader retrieval or
277
+ * `"precision"` for more targeted results. Defaults to `"recall"`.
278
+ * @param options.effort - The amount of effort the agent should put into the search. One of
279
+ * `"medium"`, `"high"`, or `"ultrahigh"`. Higher effort may improve result quality at the
280
+ * expense of increased latency and cost.
281
+ * @returns A {@link SearchModeResponse} for the first page of results. Use
282
+ * `response.next({ limit, offset })` to paginate.
283
+ *
284
+ * @example
285
+ * ```ts
286
+ * const agent = new QueryAgent(client, { collections: ["FinancialContracts"] });
287
+ * const page1 = await agent.search("Find all NDAs signed by Jane Doe in 2024.", { limit: 5 });
288
+ * const page2 = await page1.next({ limit: 5, offset: 5 });
289
+ * const page3 = await page2.next({ limit: 5, offset: 10 });
290
+ * ```
291
+ */
292
+ search(query_1) {
293
+ return __awaiter(this, arguments, void 0, function* (query, { limit = 20, collections, diversityWeight, filtering, effort, } = {}) {
294
+ const searcher = new QueryAgentSearcher(this.client, query, this.validateCollections(collections), this.systemPrompt, this.agentsHost, diversityWeight, filtering, effort);
295
+ return searcher.run({ limit, offset: 0 });
296
+ });
297
+ }
298
+ /**
299
+ * Suggest queries for the data in your collections.
300
+ *
301
+ * Uses the agent to generate example queries that can be run against the given collections.
302
+ * This can help users discover what kinds of questions they can ask, or generate example prompts
303
+ * for a dataset.
304
+ *
305
+ * @param options - Options for the suggest-queries request.
306
+ * @param options.collections - Optional override for the collections configured at instantiation.
307
+ * Either a list of strings, or a list of {@link QueryAgentCollectionConfig} objects.
308
+ * @param options.numQueries - The number of queries to suggest. Defaults to 3.
309
+ * @param options.instructions - Optional natural language guidance for the style, topic, or
310
+ * language of the suggested queries. Supplied in addition to the agent's system instructions.
311
+ * @param options.conversation - Optional conversation history to contextualise suggested queries
312
+ * as follow-up questions. Each element is a {@link ChatMessage} with `role` and `content`.
313
+ * @returns A {@link SuggestQueryResponse} containing the list of suggested queries, along with
314
+ * additional metadata if present.
315
+ *
316
+ * @example
317
+ * ```ts
318
+ * const agent = new QueryAgent(client, { collections: ["FinancialContracts"] });
319
+ * const suggestions = await agent.suggestQueries({
320
+ * collections: ["Products"],
321
+ * numQueries: 5,
322
+ * instructions: "Focus on questions about eco-friendly features.",
323
+ * conversation: [
324
+ * { role: "user", content: "What topics are covered?" },
325
+ * { role: "assistant", content: "The collection covers ML and economics." },
326
+ * ],
327
+ * });
328
+ * ```
329
+ */
330
+ suggestQueries() {
331
+ return __awaiter(this, arguments, void 0, function* ({ collections, numQueries, instructions, conversation, } = {}) {
332
+ const targetCollections = this.validateCollections(collections);
333
+ const { requestHeaders, connectionHeaders } = yield getHeaders(this.client);
334
+ const body = {
335
+ headers: connectionHeaders,
336
+ collections: mapCollections(targetCollections),
337
+ num_queries: numQueries !== null && numQueries !== void 0 ? numQueries : 3,
338
+ };
339
+ if (instructions !== undefined) {
340
+ body.instructions = instructions;
341
+ }
342
+ if (conversation !== undefined) {
343
+ body.conversation_context = { messages: conversation };
344
+ }
345
+ const response = yield fetch(`${this.agentsHost}/query/suggest_queries`, {
346
+ method: "POST",
347
+ headers: requestHeaders,
348
+ body: JSON.stringify(body),
349
+ });
350
+ if (!response.ok) {
351
+ yield handleError(yield response.text());
352
+ }
353
+ return mapSuggestQueryResponse(yield response.json());
354
+ });
355
+ }
356
+ }
357
+ /**
358
+ * Convert a user-supplied {@link OutputFormat} into the JSON Schema the agents
359
+ * API expects on the request body: a Zod schema is serialised to a Draft
360
+ * 2020-12 JSON Schema, a raw JSON Schema object is sent through unchanged, and
361
+ * `undefined` (no structured output) stays `undefined`.
362
+ */
363
+ const mapOutputFormat = (outputFormat) => {
364
+ if (outputFormat === undefined) {
365
+ return undefined;
366
+ }
367
+ return isZodSchema(outputFormat)
368
+ ? z.toJSONSchema(outputFormat, {
369
+ target: "draft-2020-12",
370
+ override: hideImageBase64,
371
+ })
372
+ : outputFormat;
373
+ };
@@ -0,0 +1 @@
1
+ export {};