sarvam-agents-client 0.3.0 → 0.3.1
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/README.md +16 -1
- package/dist/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/apis/FunctionToolsApi.js +65 -0
- package/dist/apis/index.d.ts +1 -0
- package/dist/apis/index.js +1 -0
- package/dist/compose/agent.d.ts +16 -3
- package/dist/compose/agent.js +76 -7
- package/dist/compose/errors.d.ts +5 -1
- package/dist/compose/errors.js +4 -1
- package/dist/compose/events.d.ts +4 -0
- package/dist/compose/events.js +34 -0
- package/dist/compose/functionTool.d.ts +101 -0
- package/dist/compose/functionTool.js +420 -0
- package/dist/compose/index.d.ts +5 -2
- package/dist/compose/index.js +3 -1
- package/dist/compose/output.d.ts +11 -0
- package/dist/compose/output.js +32 -7
- package/dist/compose/run.d.ts +5 -1
- package/dist/compose/run.js +118 -25
- package/dist/compose/runState.d.ts +26 -1
- package/dist/compose/runState.js +30 -0
- package/dist/compose/settingsTransport.d.ts +20 -1
- package/dist/compose/settingsTransport.js +295 -3
- package/dist/compose/transport.d.ts +18 -1
- package/dist/esm/apis/FunctionToolsApi.d.ts +33 -0
- package/dist/esm/apis/FunctionToolsApi.js +61 -0
- package/dist/esm/apis/index.d.ts +1 -0
- package/dist/esm/apis/index.js +1 -0
- package/dist/esm/compose/agent.d.ts +16 -3
- package/dist/esm/compose/agent.js +76 -7
- package/dist/esm/compose/errors.d.ts +5 -1
- package/dist/esm/compose/errors.js +4 -1
- package/dist/esm/compose/events.d.ts +4 -0
- package/dist/esm/compose/events.js +33 -0
- package/dist/esm/compose/functionTool.d.ts +101 -0
- package/dist/esm/compose/functionTool.js +406 -0
- package/dist/esm/compose/index.d.ts +5 -2
- package/dist/esm/compose/index.js +1 -0
- package/dist/esm/compose/output.d.ts +11 -0
- package/dist/esm/compose/output.js +30 -9
- package/dist/esm/compose/run.d.ts +5 -1
- package/dist/esm/compose/run.js +118 -25
- package/dist/esm/compose/runState.d.ts +26 -1
- package/dist/esm/compose/runState.js +31 -1
- package/dist/esm/compose/settingsTransport.d.ts +20 -1
- package/dist/esm/compose/settingsTransport.js +298 -7
- package/dist/esm/compose/transport.d.ts +18 -1
- package/dist/esm/models/AgentConversationDetail.d.ts +7 -0
- package/dist/esm/models/AgentConversationDetail.js +3 -0
- package/dist/esm/models/ClarifyBody.d.ts +6 -0
- package/dist/esm/models/ClarifyBody.js +2 -0
- package/dist/esm/models/ConversationDetail.d.ts +7 -0
- package/dist/esm/models/ConversationDetail.js +3 -0
- package/dist/esm/models/ErrorDetail.d.ts +1 -0
- package/dist/esm/models/ErrorDetail.js +2 -1
- package/dist/esm/models/FunctionResultBody.d.ts +44 -0
- package/dist/esm/models/FunctionResultBody.js +49 -0
- package/dist/esm/models/QueueMessageInput.d.ts +23 -0
- package/dist/esm/models/QueueMessageInput.js +14 -0
- package/dist/esm/models/RequiredAction.d.ts +77 -0
- package/dist/esm/models/RequiredAction.js +69 -0
- package/dist/esm/models/ResponseDetail.d.ts +8 -0
- package/dist/esm/models/ResponseDetail.js +2 -0
- package/dist/esm/models/ResponseInput.d.ts +23 -0
- package/dist/esm/models/ResponseInput.js +14 -0
- package/dist/esm/models/ToolResults200Response.d.ts +38 -0
- package/dist/esm/models/ToolResults200Response.js +47 -0
- package/dist/esm/models/ToolResultsBody.d.ts +39 -0
- package/dist/esm/models/ToolResultsBody.js +48 -0
- package/dist/esm/models/index.d.ts +4 -0
- package/dist/esm/models/index.js +4 -0
- package/dist/esm/streaming.d.ts +14 -2
- package/dist/esm/streaming.js +26 -4
- package/dist/models/AgentConversationDetail.d.ts +7 -0
- package/dist/models/AgentConversationDetail.js +3 -0
- package/dist/models/ClarifyBody.d.ts +6 -0
- package/dist/models/ClarifyBody.js +2 -0
- package/dist/models/ConversationDetail.d.ts +7 -0
- package/dist/models/ConversationDetail.js +3 -0
- package/dist/models/ErrorDetail.d.ts +1 -0
- package/dist/models/ErrorDetail.js +2 -1
- package/dist/models/FunctionResultBody.d.ts +44 -0
- package/dist/models/FunctionResultBody.js +56 -0
- package/dist/models/QueueMessageInput.d.ts +23 -0
- package/dist/models/QueueMessageInput.js +15 -1
- package/dist/models/RequiredAction.d.ts +77 -0
- package/dist/models/RequiredAction.js +77 -0
- package/dist/models/ResponseDetail.d.ts +8 -0
- package/dist/models/ResponseDetail.js +2 -0
- package/dist/models/ResponseInput.d.ts +23 -0
- package/dist/models/ResponseInput.js +15 -0
- package/dist/models/ToolResults200Response.d.ts +38 -0
- package/dist/models/ToolResults200Response.js +54 -0
- package/dist/models/ToolResultsBody.d.ts +39 -0
- package/dist/models/ToolResultsBody.js +55 -0
- package/dist/models/index.d.ts +4 -0
- package/dist/models/index.js +4 -0
- package/dist/streaming.d.ts +14 -2
- package/dist/streaming.js +27 -4
- package/package.json +1 -1
- package/src/apis/FunctionToolsApi.ts +102 -0
- package/src/apis/index.ts +1 -0
- package/src/compose/agent.ts +87 -9
- package/src/compose/errors.ts +7 -1
- package/src/compose/events.ts +30 -0
- package/src/compose/functionTool.ts +441 -0
- package/src/compose/index.ts +5 -2
- package/src/compose/output.ts +30 -9
- package/src/compose/run.ts +115 -18
- package/src/compose/runState.ts +44 -5
- package/src/compose/settingsTransport.ts +293 -7
- package/src/compose/transport.ts +24 -1
- package/src/models/AgentConversationDetail.ts +15 -0
- package/src/models/ClarifyBody.ts +8 -0
- package/src/models/ConversationDetail.ts +15 -0
- package/src/models/ErrorDetail.ts +2 -1
- package/src/models/FunctionResultBody.ts +83 -0
- package/src/models/QueueMessageInput.ts +28 -0
- package/src/models/RequiredAction.ts +128 -0
- package/src/models/ResponseDetail.ts +8 -0
- package/src/models/ResponseInput.ts +30 -0
- package/src/models/ToolResults200Response.ts +75 -0
- package/src/models/ToolResultsBody.ts +83 -0
- package/src/models/index.ts +4 -0
- package/src/streaming.ts +39 -3
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.SettingsTransport = void 0;
|
|
3
|
+
exports.SettingsTransport = exports.followPollMs = void 0;
|
|
4
|
+
exports.idempotencyKey = idempotencyKey;
|
|
4
5
|
/** SettingsTransport: the compose transport on the generated API (agent settings file + responses stream). */
|
|
5
6
|
const node_crypto_1 = require("node:crypto");
|
|
6
7
|
const AgentsApi_js_1 = require("../apis/AgentsApi.js");
|
|
@@ -11,14 +12,174 @@ const streaming_js_1 = require("../streaming.js");
|
|
|
11
12
|
const errors_js_1 = require("./errors.js");
|
|
12
13
|
const events_js_1 = require("./events.js");
|
|
13
14
|
const PAGE = 100;
|
|
15
|
+
/** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
|
|
16
|
+
const IN_PROGRESS_RETRIES = 5;
|
|
17
|
+
/** A post the server could not deliver to the agent (503; nothing was kept) is re-posted this many times,
|
|
18
|
+
* Retry-After apart, with the same Idempotency-Key and results: the agent takes them once. */
|
|
19
|
+
const UNAVAILABLE_RETRIES = 5;
|
|
20
|
+
/** The longest wait one Retry-After can ask for, in seconds. */
|
|
21
|
+
const RETRY_AFTER_MAX = 30;
|
|
22
|
+
/** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
|
|
23
|
+
* continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
|
|
24
|
+
* for tests; not exported from the compose root. */
|
|
25
|
+
exports.followPollMs = { value: 1000 };
|
|
26
|
+
const FOLLOW_POLLS = 30;
|
|
27
|
+
/** 409 reasons after which the server went on with the turn without this post: the run follows it. */
|
|
28
|
+
const WENT_ON = {
|
|
29
|
+
expired: "the results arrived too late: the request expired, and the agent got a failed result for each call and " +
|
|
30
|
+
"went on without them",
|
|
31
|
+
already_answered: "another poster answered the request first; the agent went on with those results",
|
|
32
|
+
};
|
|
33
|
+
/** Why POST .../tool-results refused a post, by reason (`error.details[0].reason`); the run cannot go on from here. */
|
|
34
|
+
const REFUSALS = {
|
|
35
|
+
expired: "the request expired before its results arrived; the agent went on without them",
|
|
36
|
+
stopped: "the user stopped the turn before these results arrived; the server answered every call with an error " +
|
|
37
|
+
"and stopped the turn",
|
|
38
|
+
ended: "the turn waiting on these results has ended",
|
|
39
|
+
already_answered: "these function calls were already answered",
|
|
40
|
+
idempotency_key_reused: "the request was answered with other results under the same Idempotency-Key",
|
|
41
|
+
no_active_run: "no agent run is waiting on these results (the session has ended)",
|
|
42
|
+
results_too_large: "the outputs together are over the server's limit",
|
|
43
|
+
unknown_request: "the server has no function-call request with this id",
|
|
44
|
+
missing_tool_call_ids: "the results do not answer every call of the request",
|
|
45
|
+
unknown_tool_call_ids: "the results answer calls that are not part of the request",
|
|
46
|
+
duplicate_tool_call_ids: "the results answer a call more than once",
|
|
47
|
+
};
|
|
48
|
+
/** A post that got no answer (the connection broke or timed out) is retried this many times, with the same key. */
|
|
49
|
+
const LOST_POST_RETRIES = 3;
|
|
50
|
+
/** No answer from the server: fetch failed (a TypeError from undici, wrapped in FetchError by the runtime). */
|
|
51
|
+
function isLostPost(err, signal) {
|
|
52
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted)
|
|
53
|
+
return false;
|
|
54
|
+
return err instanceof runtime_js_1.FetchError || err instanceof TypeError;
|
|
55
|
+
}
|
|
56
|
+
/** `error.details[0].reason` of a chat_service error response, else null. */
|
|
57
|
+
async function reason(err, status) {
|
|
58
|
+
if (!(err instanceof runtime_js_1.ResponseError) || err.response.status !== status)
|
|
59
|
+
return null;
|
|
60
|
+
try {
|
|
61
|
+
const value = (await err.response.clone().json()).error.details[0].reason;
|
|
62
|
+
return typeof value === "string" ? value : null;
|
|
63
|
+
}
|
|
64
|
+
catch (_a) {
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Whether a stored reply still ends on `requestId`: nothing after its `data-function-call-request` part but the
|
|
69
|
+
* paused segment's `data-output` (`skipped: "paused"`), so the turn has not gone on from it yet. */
|
|
70
|
+
function waitsOn(message, requestId) {
|
|
71
|
+
const parts = message !== null && typeof message === "object" ? message["parts"] : null;
|
|
72
|
+
const list = Array.isArray(parts) ? parts : [];
|
|
73
|
+
const at = list.findIndex((p) => {
|
|
74
|
+
var _a, _b;
|
|
75
|
+
return p !== null && typeof p === "object" && p["type"] === "data-function-call-request"
|
|
76
|
+
&& ((_b = (_a = p["data"]) === null || _a === void 0 ? void 0 : _a["requestId"]) !== null && _b !== void 0 ? _b : p["id"]) === requestId;
|
|
77
|
+
});
|
|
78
|
+
if (at === -1)
|
|
79
|
+
return false;
|
|
80
|
+
return list.slice(at + 1).every((p) => {
|
|
81
|
+
var _a;
|
|
82
|
+
const kind = p !== null && typeof p === "object" ? p["type"] : undefined;
|
|
83
|
+
if (kind === "reasoning" || kind === "step-start")
|
|
84
|
+
return true;
|
|
85
|
+
return kind === "data-output" && ((_a = p["data"]) === null || _a === void 0 ? void 0 : _a["skipped"]) === "paused";
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
/** The `error` object of a chat_service error response, else null (not a chat_service error). */
|
|
89
|
+
async function chatError(err) {
|
|
90
|
+
try {
|
|
91
|
+
const error = (await err.response.clone().json()).error;
|
|
92
|
+
return error !== null && typeof error === "object" && !Array.isArray(error) ? error : null;
|
|
93
|
+
}
|
|
94
|
+
catch (_a) {
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
/** `error.details[0]` of a chat_service error, else {}. */
|
|
99
|
+
function firstDetail(error) {
|
|
100
|
+
const details = error === null || error === void 0 ? void 0 : error["details"];
|
|
101
|
+
const first = Array.isArray(details) ? details[0] : undefined;
|
|
102
|
+
return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
|
|
103
|
+
}
|
|
104
|
+
function retryAfterMs(err) {
|
|
105
|
+
var _a;
|
|
106
|
+
const seconds = Number((_a = err.response.headers.get("retry-after")) !== null && _a !== void 0 ? _a : 2);
|
|
107
|
+
if (!Number.isFinite(seconds) || seconds < 0)
|
|
108
|
+
return 2000;
|
|
109
|
+
return Math.min(seconds, RETRY_AFTER_MAX) * 1000;
|
|
110
|
+
}
|
|
111
|
+
/** A refused POST .../tool-results as the SDK's error: RunError with the server's reason as `code`,
|
|
112
|
+
* NotSupportedByServerError(["functions"]) for a server without the route, else the ResponseError itself. */
|
|
113
|
+
async function refused(err, requestId) {
|
|
114
|
+
const status = err.response.status;
|
|
115
|
+
const error = await chatError(err);
|
|
116
|
+
const detail = firstDetail(error);
|
|
117
|
+
const why = typeof detail["reason"] === "string" ? detail["reason"] : null;
|
|
118
|
+
if (why !== null && Object.prototype.hasOwnProperty.call(REFUSALS, why)) {
|
|
119
|
+
let message = `function results for request ${requestId}: ${REFUSALS[why]}`;
|
|
120
|
+
if (why === "results_too_large" && detail["maxBytes"] !== undefined)
|
|
121
|
+
message += ` (${String(detail["maxBytes"])} bytes)`;
|
|
122
|
+
const ids = detail["toolCallIds"];
|
|
123
|
+
if (Array.isArray(ids) && ids.length > 0)
|
|
124
|
+
message += `: ${ids.map(String).join(", ")}`;
|
|
125
|
+
return new errors_js_1.RunError(why, message, status, detail);
|
|
126
|
+
}
|
|
127
|
+
if (status === 404) {
|
|
128
|
+
if (error === null)
|
|
129
|
+
return new errors_js_1.NotSupportedByServerError(["functions"]); // the framework's own 404: no route
|
|
130
|
+
return new errors_js_1.RunError("not_found", `function results for request ${requestId}: no such conversation for this caller`, 404, detail);
|
|
131
|
+
}
|
|
132
|
+
return err;
|
|
133
|
+
}
|
|
134
|
+
/** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
|
|
135
|
+
function idempotencyKey(requestId) {
|
|
136
|
+
return (0, node_crypto_1.createHash)("sha256").update(requestId, "utf8").digest("hex");
|
|
137
|
+
}
|
|
138
|
+
function sleep(ms, signal) {
|
|
139
|
+
return new Promise((resolve, reject) => {
|
|
140
|
+
if (signal === null || signal === void 0 ? void 0 : signal.aborted)
|
|
141
|
+
return reject(signal.reason);
|
|
142
|
+
const timer = setTimeout(() => {
|
|
143
|
+
signal === null || signal === void 0 ? void 0 : signal.removeEventListener("abort", onAbort);
|
|
144
|
+
resolve();
|
|
145
|
+
}, ms);
|
|
146
|
+
const onAbort = () => {
|
|
147
|
+
clearTimeout(timer);
|
|
148
|
+
reject(signal === null || signal === void 0 ? void 0 : signal.reason);
|
|
149
|
+
};
|
|
150
|
+
signal === null || signal === void 0 ? void 0 : signal.addEventListener("abort", onAbort, { once: true });
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
/** A turn that has already ended, read back from its stored reply (`chunksFromUiMessage`). A replay: it holds the
|
|
154
|
+
* whole turn, the requests this run answered too. */
|
|
155
|
+
class Finished {
|
|
156
|
+
constructor(conversationId, chunks) {
|
|
157
|
+
this.conversationId = conversationId;
|
|
158
|
+
this.chunks = chunks;
|
|
159
|
+
this.responseId = null;
|
|
160
|
+
this.lastEventId = null;
|
|
161
|
+
this.replay = true;
|
|
162
|
+
}
|
|
163
|
+
async *[Symbol.asyncIterator]() {
|
|
164
|
+
for (const chunk of this.chunks) {
|
|
165
|
+
const event = (0, events_js_1.fromUiChunk)(chunk);
|
|
166
|
+
if (event !== null)
|
|
167
|
+
yield event;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
close() { }
|
|
171
|
+
}
|
|
14
172
|
function isNotFound(err) {
|
|
15
173
|
return err instanceof runtime_js_1.ResponseError && err.response.status === 404;
|
|
16
174
|
}
|
|
17
175
|
/** TurnStream over a streaming ResponseStream; ids are read live from the underlying stream. */
|
|
18
176
|
class Stream {
|
|
19
|
-
constructor(inner, conversationId
|
|
177
|
+
constructor(inner, conversationId,
|
|
178
|
+
/** Read without a cursor after a duplicate post: the server replays the turn from its start. */
|
|
179
|
+
replay = false) {
|
|
20
180
|
this.inner = inner;
|
|
21
181
|
this.conversationId = conversationId;
|
|
182
|
+
this.replay = replay;
|
|
22
183
|
}
|
|
23
184
|
get responseId() {
|
|
24
185
|
return this.inner.responseId;
|
|
@@ -191,7 +352,18 @@ class SettingsTransport {
|
|
|
191
352
|
agentId,
|
|
192
353
|
message: { id: (0, node_crypto_1.randomUUID)(), role: "user", parts: [{ type: "text", text }] },
|
|
193
354
|
};
|
|
194
|
-
|
|
355
|
+
let inner;
|
|
356
|
+
try {
|
|
357
|
+
inner = await (0, streaming_js_1.streamResponse)(this.config, body, { signal });
|
|
358
|
+
}
|
|
359
|
+
catch (err) {
|
|
360
|
+
if ((await reason(err, 409)) === "function_call_pending") {
|
|
361
|
+
throw new errors_js_1.RunError("function_call_pending", "the conversation is waiting on function results from an earlier " +
|
|
362
|
+
"run; continue it with run(agent, await RunState.fromSession(conversationId))");
|
|
363
|
+
}
|
|
364
|
+
throw err;
|
|
365
|
+
}
|
|
366
|
+
return new Stream(inner, conversationId);
|
|
195
367
|
}
|
|
196
368
|
async answerClarify(conversationId, requestId, answers, signal) {
|
|
197
369
|
const inner = await (0, streaming_js_1.answerClarify)(this.config, conversationId, { requestId, answers }, { signal });
|
|
@@ -204,6 +376,126 @@ class SettingsTransport {
|
|
|
204
376
|
async stop(conversationId) {
|
|
205
377
|
await this.responses.stopResponse({ conversationId });
|
|
206
378
|
}
|
|
379
|
+
async postFunctionResults(conversationId, requestId, results, signal) {
|
|
380
|
+
const body = {
|
|
381
|
+
requestId,
|
|
382
|
+
results: results.map((r) => ({ toolCallId: r.callId, output: r.output, isError: r.isError })),
|
|
383
|
+
};
|
|
384
|
+
const key = idempotencyKey(requestId);
|
|
385
|
+
let inner;
|
|
386
|
+
let busy = 0;
|
|
387
|
+
let unavailable = 0;
|
|
388
|
+
let lost = 0;
|
|
389
|
+
for (;;) {
|
|
390
|
+
try {
|
|
391
|
+
inner = await (0, streaming_js_1.postToolResults)(this.config, conversationId, body, { signal, idempotencyKey: key });
|
|
392
|
+
break;
|
|
393
|
+
}
|
|
394
|
+
catch (err) {
|
|
395
|
+
if (isLostPost(err, signal)) {
|
|
396
|
+
// The server may have stored the results before the connection broke: the same key makes a retry safe,
|
|
397
|
+
// and a stored post comes back as a duplicate.
|
|
398
|
+
if (lost >= LOST_POST_RETRIES) {
|
|
399
|
+
const why = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
|
|
400
|
+
throw new errors_js_1.RunError("stream_lost", `function results for request ${requestId} got no answer after ${lost + 1} tries (${why})`);
|
|
401
|
+
}
|
|
402
|
+
await sleep(250 * 2 ** lost, signal);
|
|
403
|
+
lost += 1;
|
|
404
|
+
continue;
|
|
405
|
+
}
|
|
406
|
+
if (!(err instanceof runtime_js_1.ResponseError))
|
|
407
|
+
throw err;
|
|
408
|
+
const status = err.response.status;
|
|
409
|
+
const why = status === 409 ? firstDetail(await chatError(err))["reason"] : undefined;
|
|
410
|
+
if (why === "in_progress") {
|
|
411
|
+
// The first post with this key is still being delivered; answered only while the request is the open
|
|
412
|
+
// pause, so the same post is safe to repeat.
|
|
413
|
+
if (busy >= IN_PROGRESS_RETRIES) {
|
|
414
|
+
throw new errors_js_1.RunError(why, `function results for request ${requestId} were still being delivered after ` +
|
|
415
|
+
`${busy + 1} tries`, 409, firstDetail(await chatError(err)));
|
|
416
|
+
}
|
|
417
|
+
await sleep(retryAfterMs(err), signal);
|
|
418
|
+
busy += 1;
|
|
419
|
+
continue;
|
|
420
|
+
}
|
|
421
|
+
if (status === 503) {
|
|
422
|
+
// Not delivered and nothing kept, but the agent may have them: the same key and results again.
|
|
423
|
+
if (unavailable >= UNAVAILABLE_RETRIES) {
|
|
424
|
+
throw new errors_js_1.RunError("unavailable", `function results for request ${requestId} could not be delivered to ` +
|
|
425
|
+
`the agent after ${unavailable + 1} tries`, 503, firstDetail(await chatError(err)));
|
|
426
|
+
}
|
|
427
|
+
await sleep(retryAfterMs(err), signal);
|
|
428
|
+
unavailable += 1;
|
|
429
|
+
continue;
|
|
430
|
+
}
|
|
431
|
+
if (status === 409 && typeof why === "string" && Object.prototype.hasOwnProperty.call(WENT_ON, why)) {
|
|
432
|
+
console.warn(`function results for request ${requestId} were not taken (409 ${why}): ${WENT_ON[why]}; ` +
|
|
433
|
+
"following the turn");
|
|
434
|
+
return this.followAfter(conversationId, requestId, why, signal);
|
|
435
|
+
}
|
|
436
|
+
throw await refused(err, requestId);
|
|
437
|
+
}
|
|
438
|
+
}
|
|
439
|
+
if (!inner.duplicate)
|
|
440
|
+
return new Stream(inner, conversationId);
|
|
441
|
+
// The server already had these results (an earlier post, ours or another process's, got through).
|
|
442
|
+
return this.follow(conversationId, signal);
|
|
443
|
+
}
|
|
444
|
+
/** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
|
|
445
|
+
* answered request): the running response by reconnecting without a cursor, else the conversation's last reply
|
|
446
|
+
* as stored. A turn that paused again ends on its new request, unanswered. */
|
|
447
|
+
async follow(conversationId, signal) {
|
|
448
|
+
return this.followAfter(conversationId, null, null, signal);
|
|
449
|
+
}
|
|
450
|
+
/** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
|
|
451
|
+
* response, and the last reply still ends on that request) is read again every second, up to 30 times; then
|
|
452
|
+
* RunError(reason). An abort ends the wait. */
|
|
453
|
+
async followAfter(conversationId, requestId, why, signal) {
|
|
454
|
+
var _a;
|
|
455
|
+
for (let polls = 0;; polls++) {
|
|
456
|
+
// Read raw: the stored parts are passed through as they are, not through the generated models.
|
|
457
|
+
const raw = await this.conversations.getConversationRaw({ conversationId }, { signal });
|
|
458
|
+
const detail = await raw.raw.json();
|
|
459
|
+
const body = (detail !== null && typeof detail === "object" ? detail : {});
|
|
460
|
+
const responseId = body["activeResponseId"];
|
|
461
|
+
if (typeof responseId === "string" && responseId) {
|
|
462
|
+
return new Stream(await (0, streaming_js_1.reconnect)(this.config, conversationId, responseId, null, { signal }), conversationId, true);
|
|
463
|
+
}
|
|
464
|
+
const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
|
|
465
|
+
const last = [...messages].reverse().find((m) => m !== null && typeof m === "object"
|
|
466
|
+
&& m["role"] === "assistant");
|
|
467
|
+
if (requestId === null || !waitsOn(last, requestId)) {
|
|
468
|
+
return new Finished(conversationId, (0, events_js_1.chunksFromUiMessage)(last !== null && last !== void 0 ? last : null));
|
|
469
|
+
}
|
|
470
|
+
if (polls >= FOLLOW_POLLS) {
|
|
471
|
+
const code = why !== null && why !== void 0 ? why : "expired";
|
|
472
|
+
throw new errors_js_1.RunError(code, `function results for request ${requestId}: ${(_a = WENT_ON[code]) !== null && _a !== void 0 ? _a : code}, but the turn ` +
|
|
473
|
+
`has not gone on after ${polls} reads; read the conversation later`, 409, { reason: code });
|
|
474
|
+
}
|
|
475
|
+
await sleep(exports.followPollMs.value, signal);
|
|
476
|
+
}
|
|
477
|
+
}
|
|
478
|
+
async pending(conversationId) {
|
|
479
|
+
var _a, _b, _c;
|
|
480
|
+
const detail = await this.conversations.getConversation({ conversationId });
|
|
481
|
+
const grouped = new Map();
|
|
482
|
+
for (const action of (_a = detail.requiredActions) !== null && _a !== void 0 ? _a : []) {
|
|
483
|
+
if (((_b = action.type) !== null && _b !== void 0 ? _b : "function_call") !== "function_call")
|
|
484
|
+
continue;
|
|
485
|
+
let request = grouped.get(action.requestId);
|
|
486
|
+
if (request === undefined) {
|
|
487
|
+
request = { requestId: action.requestId, calls: [] };
|
|
488
|
+
const expires = action.expiresAt;
|
|
489
|
+
if (expires instanceof Date)
|
|
490
|
+
request.expiresAt = expires.toISOString();
|
|
491
|
+
else if (typeof expires === "string")
|
|
492
|
+
request.expiresAt = expires;
|
|
493
|
+
grouped.set(action.requestId, request);
|
|
494
|
+
}
|
|
495
|
+
request.calls.push({ callId: action.toolCallId, name: action.name, arguments: { ...((_c = action.arguments) !== null && _c !== void 0 ? _c : {}) } });
|
|
496
|
+
}
|
|
497
|
+
return Array.from(grouped.values());
|
|
498
|
+
}
|
|
207
499
|
// -- helpers --------------------------------------------------------------------------------------------
|
|
208
500
|
/** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
|
|
209
501
|
async restore(agentId, settings, instructions) {
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
/** Transport interface: the seam between the compose layer and the server. */
|
|
2
2
|
import type { Agent } from "./agent.js";
|
|
3
3
|
import type { OutputType } from "./output.js";
|
|
4
|
-
import type { Event } from "./events.js";
|
|
4
|
+
import type { Event, FunctionCallRequest } from "./events.js";
|
|
5
|
+
import type { FunctionResult } from "./functionTool.js";
|
|
5
6
|
export interface SettingsWarning {
|
|
6
7
|
code: string;
|
|
7
8
|
path: string;
|
|
@@ -19,8 +20,16 @@ export interface TurnStream extends AsyncIterable<Event> {
|
|
|
19
20
|
readonly conversationId: string | null;
|
|
20
21
|
readonly responseId: string | null;
|
|
21
22
|
readonly lastEventId: string | null;
|
|
23
|
+
/** Read without a cursor after a duplicate post: the server replays the turn from its start. */
|
|
24
|
+
readonly replay?: boolean;
|
|
22
25
|
close(): void;
|
|
23
26
|
}
|
|
27
|
+
/** A function-call request the conversation is waiting on (`requiredActions`, grouped by request). */
|
|
28
|
+
export interface PendingFunctionCalls {
|
|
29
|
+
requestId: string;
|
|
30
|
+
calls: FunctionCallRequest[];
|
|
31
|
+
expiresAt?: string;
|
|
32
|
+
}
|
|
24
33
|
export interface Transport {
|
|
25
34
|
readonly kind: "settings";
|
|
26
35
|
findAgents(sdkName: string): Promise<RemoteAgent[]>;
|
|
@@ -32,4 +41,12 @@ export interface Transport {
|
|
|
32
41
|
answerClarify(conversationId: string, requestId: string, answers: Record<string, unknown>, signal?: AbortSignal): Promise<TurnStream>;
|
|
33
42
|
resume(conversationId: string, responseId: string, lastEventId: string | null, signal?: AbortSignal): Promise<TurnStream>;
|
|
34
43
|
stop(conversationId: string): Promise<void>;
|
|
44
|
+
/** Post the results of a function-call request and stream the rest of the turn. Optional so a transport written
|
|
45
|
+
* before function tools still type-checks; run() needs it only when the model calls a function. */
|
|
46
|
+
postFunctionResults?(conversationId: string, requestId: string, results: FunctionResult[], signal?: AbortSignal): Promise<TurnStream>;
|
|
47
|
+
/** The function-call requests the conversation is waiting on; used by `RunState.fromSession`. */
|
|
48
|
+
pending?(conversationId: string): Promise<PendingFunctionCalls[]>;
|
|
49
|
+
/** The turn after a request answered elsewhere, replayed from its start (`replay`); resuming a stale RunState
|
|
50
|
+
* follows it instead of running the calls again. */
|
|
51
|
+
follow?(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
35
52
|
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sarvam Agents API
|
|
3
|
+
* Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
|
|
4
|
+
*
|
|
5
|
+
* The version of the OpenAPI document: 0.1.0
|
|
6
|
+
* Contact: support@sarvam.ai
|
|
7
|
+
*
|
|
8
|
+
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
|
9
|
+
* https://openapi-generator.tech
|
|
10
|
+
* Do not edit the class manually.
|
|
11
|
+
*/
|
|
12
|
+
import * as runtime from '../runtime.js';
|
|
13
|
+
import type { ToolResults200Response, ToolResultsBody } from '../models/index.js';
|
|
14
|
+
export interface ToolResultsRequest {
|
|
15
|
+
conversationId: string;
|
|
16
|
+
toolResultsBody: ToolResultsBody;
|
|
17
|
+
idempotencyKey?: string | null;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
*
|
|
21
|
+
*/
|
|
22
|
+
export declare class FunctionToolsApi extends runtime.BaseAPI {
|
|
23
|
+
/**
|
|
24
|
+
* Answer a paused turn\'s function calls and stream its continuation.
|
|
25
|
+
* Tool Results Route
|
|
26
|
+
*/
|
|
27
|
+
toolResultsRaw(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<runtime.ApiResponse<ToolResults200Response>>;
|
|
28
|
+
/**
|
|
29
|
+
* Answer a paused turn\'s function calls and stream its continuation.
|
|
30
|
+
* Tool Results Route
|
|
31
|
+
*/
|
|
32
|
+
toolResults(requestParameters: ToolResultsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<ToolResults200Response>;
|
|
33
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/* tslint:disable */
|
|
2
|
+
/* eslint-disable */
|
|
3
|
+
/**
|
|
4
|
+
* Sarvam Agents API
|
|
5
|
+
* Chat with a Sarvam agent, exchange files with it, and set it up (instructions, skills, knowledge bases, connectors, deploy) from your own code. Authenticate with a service token sent as a Bearer token, and send the header X-Panja-Origin: managed_agents on every request.
|
|
6
|
+
*
|
|
7
|
+
* The version of the OpenAPI document: 0.1.0
|
|
8
|
+
* Contact: support@sarvam.ai
|
|
9
|
+
*
|
|
10
|
+
* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
|
|
11
|
+
* https://openapi-generator.tech
|
|
12
|
+
* Do not edit the class manually.
|
|
13
|
+
*/
|
|
14
|
+
import * as runtime from '../runtime.js';
|
|
15
|
+
import { ToolResults200ResponseFromJSON, ToolResultsBodyToJSON, } from '../models/index.js';
|
|
16
|
+
/**
|
|
17
|
+
*
|
|
18
|
+
*/
|
|
19
|
+
export class FunctionToolsApi extends runtime.BaseAPI {
|
|
20
|
+
/**
|
|
21
|
+
* Answer a paused turn\'s function calls and stream its continuation.
|
|
22
|
+
* Tool Results Route
|
|
23
|
+
*/
|
|
24
|
+
async toolResultsRaw(requestParameters, initOverrides) {
|
|
25
|
+
if (requestParameters['conversationId'] == null) {
|
|
26
|
+
throw new runtime.RequiredError('conversationId', 'Required parameter "conversationId" was null or undefined when calling toolResults().');
|
|
27
|
+
}
|
|
28
|
+
if (requestParameters['toolResultsBody'] == null) {
|
|
29
|
+
throw new runtime.RequiredError('toolResultsBody', 'Required parameter "toolResultsBody" was null or undefined when calling toolResults().');
|
|
30
|
+
}
|
|
31
|
+
const queryParameters = {};
|
|
32
|
+
const headerParameters = {};
|
|
33
|
+
headerParameters['Content-Type'] = 'application/json';
|
|
34
|
+
if (requestParameters['idempotencyKey'] != null) {
|
|
35
|
+
headerParameters['Idempotency-Key'] = String(requestParameters['idempotencyKey']);
|
|
36
|
+
}
|
|
37
|
+
if (this.configuration && this.configuration.accessToken) {
|
|
38
|
+
const token = this.configuration.accessToken;
|
|
39
|
+
const tokenString = await token("bearerAuth", []);
|
|
40
|
+
if (tokenString) {
|
|
41
|
+
headerParameters["Authorization"] = `Bearer ${tokenString}`;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const response = await this.request({
|
|
45
|
+
path: `/v1/conversations/{conversationId}/tool-results`.replace(`{${"conversationId"}}`, runtime.encodePathParam('conversationId', requestParameters['conversationId'])),
|
|
46
|
+
method: 'POST',
|
|
47
|
+
headers: headerParameters,
|
|
48
|
+
query: queryParameters,
|
|
49
|
+
body: ToolResultsBodyToJSON(requestParameters['toolResultsBody']),
|
|
50
|
+
}, initOverrides);
|
|
51
|
+
return new runtime.JSONApiResponse(response, (jsonValue) => ToolResults200ResponseFromJSON(jsonValue));
|
|
52
|
+
}
|
|
53
|
+
/**
|
|
54
|
+
* Answer a paused turn\'s function calls and stream its continuation.
|
|
55
|
+
* Tool Results Route
|
|
56
|
+
*/
|
|
57
|
+
async toolResults(requestParameters, initOverrides) {
|
|
58
|
+
const response = await this.toolResultsRaw(requestParameters, initOverrides);
|
|
59
|
+
return await response.value();
|
|
60
|
+
}
|
|
61
|
+
}
|
package/dist/esm/apis/index.d.ts
CHANGED
|
@@ -7,6 +7,7 @@ export * from './CollectionsApi.js';
|
|
|
7
7
|
export * from './ConversationsApi.js';
|
|
8
8
|
export * from './CronsApi.js';
|
|
9
9
|
export * from './CustomAPIsApi.js';
|
|
10
|
+
export * from './FunctionToolsApi.js';
|
|
10
11
|
export * from './MessagesApi.js';
|
|
11
12
|
export * from './ModelsApi.js';
|
|
12
13
|
export * from './QueueApi.js';
|
package/dist/esm/apis/index.js
CHANGED
|
@@ -9,6 +9,7 @@ export * from './CollectionsApi.js';
|
|
|
9
9
|
export * from './ConversationsApi.js';
|
|
10
10
|
export * from './CronsApi.js';
|
|
11
11
|
export * from './CustomAPIsApi.js';
|
|
12
|
+
export * from './FunctionToolsApi.js';
|
|
12
13
|
export * from './MessagesApi.js';
|
|
13
14
|
export * from './ModelsApi.js';
|
|
14
15
|
export * from './QueueApi.js';
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { BuiltinTool } from "./tools.js";
|
|
2
|
+
import type { FunctionTool } from "./functionTool.js";
|
|
2
3
|
import type { OutputType } from "./output.js";
|
|
3
4
|
export interface ModelSettings {
|
|
4
5
|
temperature?: number;
|
|
@@ -14,6 +15,8 @@ export interface Limits {
|
|
|
14
15
|
maxToolCallsPerTurn?: number;
|
|
15
16
|
maxTokensPerTurn?: number;
|
|
16
17
|
}
|
|
18
|
+
/** An entry of `Agent` `tools`: a built-in (`sandbox()`, `webSearchTool()`, ...) or a function tool (`tool()`). */
|
|
19
|
+
export type AgentTool = BuiltinTool | FunctionTool;
|
|
17
20
|
export interface AgentOptions<TOutput extends OutputType | undefined = undefined> {
|
|
18
21
|
name: string;
|
|
19
22
|
instructions?: string;
|
|
@@ -22,8 +25,11 @@ export interface AgentOptions<TOutput extends OutputType | undefined = undefined
|
|
|
22
25
|
endpoint?: string;
|
|
23
26
|
modelSettings?: ModelSettings;
|
|
24
27
|
fallbackModels?: string[];
|
|
25
|
-
/** Exact list of built-ins
|
|
26
|
-
|
|
28
|
+
/** Exact list of what the agent may use: built-ins (the unlisted ones are turned off) and function tools (agent.json
|
|
29
|
+
* `functions`). Omit to keep the server default (every built-in on, no functions). */
|
|
30
|
+
tools?: AgentTool[];
|
|
31
|
+
/** Seconds (10 to 3000, default 600) the server waits for this process to answer a function call (`function_timeout_seconds`). */
|
|
32
|
+
functionTimeoutSeconds?: number;
|
|
27
33
|
limits?: Limits;
|
|
28
34
|
metadata?: Record<string, string>;
|
|
29
35
|
/** The shape of the final answer: `{ type: "json_schema", schema }` or a zod schema. `finalOutput` follows it. */
|
|
@@ -38,13 +44,20 @@ export declare class Agent<TOutput extends OutputType | undefined = undefined> {
|
|
|
38
44
|
readonly endpoint?: string;
|
|
39
45
|
readonly modelSettings?: ModelSettings;
|
|
40
46
|
readonly fallbackModels?: string[];
|
|
41
|
-
|
|
47
|
+
/** Built-ins and function tools, in the order given. */
|
|
48
|
+
readonly tools?: readonly AgentTool[];
|
|
49
|
+
readonly functionTimeoutSeconds?: number;
|
|
42
50
|
readonly limits?: Limits;
|
|
43
51
|
readonly metadata?: Record<string, string>;
|
|
44
52
|
/** Kept by reference and not frozen: a zod schema must stay usable. Non-enumerable, so deepFreeze skips it. */
|
|
45
53
|
readonly outputType: TOutput;
|
|
46
54
|
constructor(rawOpts: AgentOptions<TOutput>);
|
|
47
55
|
private check;
|
|
56
|
+
private checkFunctions;
|
|
57
|
+
/** The built-in tools in `tools`, in order. */
|
|
58
|
+
get builtinTools(): readonly BuiltinTool[];
|
|
59
|
+
/** The function tools in `tools`, in order. */
|
|
60
|
+
get functionTools(): readonly FunctionTool[];
|
|
48
61
|
private baseSettings;
|
|
49
62
|
specHash(): string;
|
|
50
63
|
toSettings(): Record<string, unknown>;
|