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,20 +1,171 @@
|
|
|
1
1
|
/** SettingsTransport: the compose transport on the generated API (agent settings file + responses stream). */
|
|
2
|
-
import { randomUUID } from "node:crypto";
|
|
2
|
+
import { createHash, randomUUID } from "node:crypto";
|
|
3
3
|
import { AgentsApi } from "../apis/AgentsApi.js";
|
|
4
4
|
import { ConversationsApi } from "../apis/ConversationsApi.js";
|
|
5
5
|
import { ResponsesApi } from "../apis/ResponsesApi.js";
|
|
6
|
-
import { ResponseError } from "../runtime.js";
|
|
6
|
+
import { FetchError, ResponseError } from "../runtime.js";
|
|
7
7
|
import type { Configuration } from "../runtime.js";
|
|
8
|
-
import { answerClarify, reconnect, streamResponse } from "../streaming.js";
|
|
8
|
+
import { answerClarify, postToolResults, reconnect, streamResponse } from "../streaming.js";
|
|
9
9
|
import type { ResponseStream } from "../streaming.js";
|
|
10
10
|
import type { Agent } from "./agent.js";
|
|
11
11
|
import type { OutputType } from "./output.js";
|
|
12
|
-
import { NotSupportedByServerError, UserError } from "./errors.js";
|
|
13
|
-
import { fromUiChunk } from "./events.js";
|
|
12
|
+
import { NotSupportedByServerError, RunError, UserError } from "./errors.js";
|
|
13
|
+
import { chunksFromUiMessage, fromUiChunk } from "./events.js";
|
|
14
14
|
import type { Event } from "./events.js";
|
|
15
|
-
import type {
|
|
15
|
+
import type { FunctionResult } from "./functionTool.js";
|
|
16
|
+
import type { PendingFunctionCalls, RemoteAgent, SettingsWarning, Transport, TurnStream } from "./transport.js";
|
|
16
17
|
|
|
17
18
|
const PAGE = 100;
|
|
19
|
+
/** A post the server is still delivering (409 in_progress) is retried this many times, Retry-After apart. */
|
|
20
|
+
const IN_PROGRESS_RETRIES = 5;
|
|
21
|
+
/** A post the server could not deliver to the agent (503; nothing was kept) is re-posted this many times,
|
|
22
|
+
* Retry-After apart, with the same Idempotency-Key and results: the agent takes them once. */
|
|
23
|
+
const UNAVAILABLE_RETRIES = 5;
|
|
24
|
+
/** The longest wait one Retry-After can ask for, in seconds. */
|
|
25
|
+
const RETRY_AFTER_MAX = 30;
|
|
26
|
+
/** After a 409 expired or already_answered the server goes on with the turn; chat_service may still be picking that
|
|
27
|
+
* continuation up. The conversation is read again every `followPollMs.value` ms, at most FOLLOW_POLLS times. Mutable
|
|
28
|
+
* for tests; not exported from the compose root. */
|
|
29
|
+
export const followPollMs = { value: 1000 };
|
|
30
|
+
const FOLLOW_POLLS = 30;
|
|
31
|
+
/** 409 reasons after which the server went on with the turn without this post: the run follows it. */
|
|
32
|
+
const WENT_ON: Record<string, string> = {
|
|
33
|
+
expired: "the results arrived too late: the request expired, and the agent got a failed result for each call and " +
|
|
34
|
+
"went on without them",
|
|
35
|
+
already_answered: "another poster answered the request first; the agent went on with those results",
|
|
36
|
+
};
|
|
37
|
+
/** Why POST .../tool-results refused a post, by reason (`error.details[0].reason`); the run cannot go on from here. */
|
|
38
|
+
const REFUSALS: Record<string, string> = {
|
|
39
|
+
expired: "the request expired before its results arrived; the agent went on without them",
|
|
40
|
+
stopped: "the user stopped the turn before these results arrived; the server answered every call with an error " +
|
|
41
|
+
"and stopped the turn",
|
|
42
|
+
ended: "the turn waiting on these results has ended",
|
|
43
|
+
already_answered: "these function calls were already answered",
|
|
44
|
+
idempotency_key_reused: "the request was answered with other results under the same Idempotency-Key",
|
|
45
|
+
no_active_run: "no agent run is waiting on these results (the session has ended)",
|
|
46
|
+
results_too_large: "the outputs together are over the server's limit",
|
|
47
|
+
unknown_request: "the server has no function-call request with this id",
|
|
48
|
+
missing_tool_call_ids: "the results do not answer every call of the request",
|
|
49
|
+
unknown_tool_call_ids: "the results answer calls that are not part of the request",
|
|
50
|
+
duplicate_tool_call_ids: "the results answer a call more than once",
|
|
51
|
+
};
|
|
52
|
+
/** A post that got no answer (the connection broke or timed out) is retried this many times, with the same key. */
|
|
53
|
+
const LOST_POST_RETRIES = 3;
|
|
54
|
+
|
|
55
|
+
/** No answer from the server: fetch failed (a TypeError from undici, wrapped in FetchError by the runtime). */
|
|
56
|
+
function isLostPost(err: unknown, signal?: AbortSignal): boolean {
|
|
57
|
+
if (signal?.aborted) return false;
|
|
58
|
+
return err instanceof FetchError || err instanceof TypeError;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** `error.details[0].reason` of a chat_service error response, else null. */
|
|
62
|
+
async function reason(err: unknown, status: number): Promise<string | null> {
|
|
63
|
+
if (!(err instanceof ResponseError) || err.response.status !== status) return null;
|
|
64
|
+
try {
|
|
65
|
+
const value = (await err.response.clone().json()).error.details[0].reason;
|
|
66
|
+
return typeof value === "string" ? value : null;
|
|
67
|
+
} catch {
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** Whether a stored reply still ends on `requestId`: nothing after its `data-function-call-request` part but the
|
|
73
|
+
* paused segment's `data-output` (`skipped: "paused"`), so the turn has not gone on from it yet. */
|
|
74
|
+
function waitsOn(message: unknown, requestId: string): boolean {
|
|
75
|
+
const parts = message !== null && typeof message === "object" ? (message as Record<string, unknown>)["parts"] : null;
|
|
76
|
+
const list = Array.isArray(parts) ? (parts as Record<string, unknown>[]) : [];
|
|
77
|
+
const at = list.findIndex((p) => p !== null && typeof p === "object" && p["type"] === "data-function-call-request"
|
|
78
|
+
&& ((p["data"] as Record<string, unknown> | undefined)?.["requestId"] ?? p["id"]) === requestId);
|
|
79
|
+
if (at === -1) return false;
|
|
80
|
+
return list.slice(at + 1).every((p) => {
|
|
81
|
+
const kind = p !== null && typeof p === "object" ? p["type"] : undefined;
|
|
82
|
+
if (kind === "reasoning" || kind === "step-start") return true;
|
|
83
|
+
return kind === "data-output" && (p["data"] as Record<string, unknown> | undefined)?.["skipped"] === "paused";
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** The `error` object of a chat_service error response, else null (not a chat_service error). */
|
|
88
|
+
async function chatError(err: ResponseError): Promise<Record<string, unknown> | null> {
|
|
89
|
+
try {
|
|
90
|
+
const error = (await err.response.clone().json()).error;
|
|
91
|
+
return error !== null && typeof error === "object" && !Array.isArray(error) ? error : null;
|
|
92
|
+
} catch {
|
|
93
|
+
return null;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** `error.details[0]` of a chat_service error, else {}. */
|
|
98
|
+
function firstDetail(error: Record<string, unknown> | null): Record<string, unknown> {
|
|
99
|
+
const details = error?.["details"];
|
|
100
|
+
const first = Array.isArray(details) ? details[0] : undefined;
|
|
101
|
+
return first !== null && typeof first === "object" && !Array.isArray(first) ? { ...first } : {};
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
function retryAfterMs(err: ResponseError): number {
|
|
105
|
+
const seconds = Number(err.response.headers.get("retry-after") ?? 2);
|
|
106
|
+
if (!Number.isFinite(seconds) || seconds < 0) return 2000;
|
|
107
|
+
return Math.min(seconds, RETRY_AFTER_MAX) * 1000;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
/** A refused POST .../tool-results as the SDK's error: RunError with the server's reason as `code`,
|
|
111
|
+
* NotSupportedByServerError(["functions"]) for a server without the route, else the ResponseError itself. */
|
|
112
|
+
async function refused(err: ResponseError, requestId: string): Promise<Error> {
|
|
113
|
+
const status = err.response.status;
|
|
114
|
+
const error = await chatError(err);
|
|
115
|
+
const detail = firstDetail(error);
|
|
116
|
+
const why = typeof detail["reason"] === "string" ? (detail["reason"] as string) : null;
|
|
117
|
+
if (why !== null && Object.prototype.hasOwnProperty.call(REFUSALS, why)) {
|
|
118
|
+
let message = `function results for request ${requestId}: ${REFUSALS[why]}`;
|
|
119
|
+
if (why === "results_too_large" && detail["maxBytes"] !== undefined) message += ` (${String(detail["maxBytes"])} bytes)`;
|
|
120
|
+
const ids = detail["toolCallIds"];
|
|
121
|
+
if (Array.isArray(ids) && ids.length > 0) message += `: ${ids.map(String).join(", ")}`;
|
|
122
|
+
return new RunError(why, message, status, detail);
|
|
123
|
+
}
|
|
124
|
+
if (status === 404) {
|
|
125
|
+
if (error === null) return new NotSupportedByServerError(["functions"]); // the framework's own 404: no route
|
|
126
|
+
return new RunError("not_found", `function results for request ${requestId}: no such conversation for this caller`,
|
|
127
|
+
404, detail);
|
|
128
|
+
}
|
|
129
|
+
return err;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The `Idempotency-Key` for answering `requestId`: the same for every post of it, from any process. */
|
|
133
|
+
export function idempotencyKey(requestId: string): string {
|
|
134
|
+
return createHash("sha256").update(requestId, "utf8").digest("hex");
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function sleep(ms: number, signal?: AbortSignal): Promise<void> {
|
|
138
|
+
return new Promise((resolve, reject) => {
|
|
139
|
+
if (signal?.aborted) return reject(signal.reason);
|
|
140
|
+
const timer = setTimeout(() => {
|
|
141
|
+
signal?.removeEventListener("abort", onAbort);
|
|
142
|
+
resolve();
|
|
143
|
+
}, ms);
|
|
144
|
+
const onAbort = () => {
|
|
145
|
+
clearTimeout(timer);
|
|
146
|
+
reject(signal?.reason);
|
|
147
|
+
};
|
|
148
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
149
|
+
});
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** A turn that has already ended, read back from its stored reply (`chunksFromUiMessage`). A replay: it holds the
|
|
153
|
+
* whole turn, the requests this run answered too. */
|
|
154
|
+
class Finished implements TurnStream {
|
|
155
|
+
readonly responseId = null;
|
|
156
|
+
readonly lastEventId = null;
|
|
157
|
+
readonly replay = true;
|
|
158
|
+
constructor(readonly conversationId: string, private readonly chunks: Record<string, unknown>[]) {}
|
|
159
|
+
|
|
160
|
+
async *[Symbol.asyncIterator](): AsyncGenerator<Event> {
|
|
161
|
+
for (const chunk of this.chunks) {
|
|
162
|
+
const event = fromUiChunk(chunk);
|
|
163
|
+
if (event !== null) yield event;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
close(): void {}
|
|
168
|
+
}
|
|
18
169
|
|
|
19
170
|
interface Envelope {
|
|
20
171
|
settings?: { [key: string]: any } | null;
|
|
@@ -30,6 +181,8 @@ class Stream implements TurnStream {
|
|
|
30
181
|
constructor(
|
|
31
182
|
private readonly inner: ResponseStream,
|
|
32
183
|
readonly conversationId: string | null,
|
|
184
|
+
/** Read without a cursor after a duplicate post: the server replays the turn from its start. */
|
|
185
|
+
readonly replay = false,
|
|
33
186
|
) {}
|
|
34
187
|
|
|
35
188
|
get responseId(): string | null {
|
|
@@ -205,7 +358,17 @@ export class SettingsTransport implements Transport {
|
|
|
205
358
|
agentId,
|
|
206
359
|
message: { id: randomUUID(), role: "user", parts: [{ type: "text", text }] },
|
|
207
360
|
};
|
|
208
|
-
|
|
361
|
+
let inner: ResponseStream;
|
|
362
|
+
try {
|
|
363
|
+
inner = await streamResponse(this.config, body, { signal });
|
|
364
|
+
} catch (err) {
|
|
365
|
+
if ((await reason(err, 409)) === "function_call_pending") {
|
|
366
|
+
throw new RunError("function_call_pending", "the conversation is waiting on function results from an earlier " +
|
|
367
|
+
"run; continue it with run(agent, await RunState.fromSession(conversationId))");
|
|
368
|
+
}
|
|
369
|
+
throw err;
|
|
370
|
+
}
|
|
371
|
+
return new Stream(inner, conversationId);
|
|
209
372
|
}
|
|
210
373
|
|
|
211
374
|
async answerClarify(
|
|
@@ -232,6 +395,129 @@ export class SettingsTransport implements Transport {
|
|
|
232
395
|
await this.responses.stopResponse({ conversationId });
|
|
233
396
|
}
|
|
234
397
|
|
|
398
|
+
async postFunctionResults(
|
|
399
|
+
conversationId: string,
|
|
400
|
+
requestId: string,
|
|
401
|
+
results: FunctionResult[],
|
|
402
|
+
signal?: AbortSignal,
|
|
403
|
+
): Promise<TurnStream> {
|
|
404
|
+
const body = {
|
|
405
|
+
requestId,
|
|
406
|
+
results: results.map((r) => ({ toolCallId: r.callId, output: r.output, isError: r.isError })),
|
|
407
|
+
};
|
|
408
|
+
const key = idempotencyKey(requestId);
|
|
409
|
+
let inner: ResponseStream;
|
|
410
|
+
let busy = 0;
|
|
411
|
+
let unavailable = 0;
|
|
412
|
+
let lost = 0;
|
|
413
|
+
for (;;) {
|
|
414
|
+
try {
|
|
415
|
+
inner = await postToolResults(this.config, conversationId, body, { signal, idempotencyKey: key });
|
|
416
|
+
break;
|
|
417
|
+
} catch (err) {
|
|
418
|
+
if (isLostPost(err, signal)) {
|
|
419
|
+
// The server may have stored the results before the connection broke: the same key makes a retry safe,
|
|
420
|
+
// and a stored post comes back as a duplicate.
|
|
421
|
+
if (lost >= LOST_POST_RETRIES) {
|
|
422
|
+
const why = err instanceof Error ? `${err.name}: ${err.message}` : String(err);
|
|
423
|
+
throw new RunError("stream_lost",
|
|
424
|
+
`function results for request ${requestId} got no answer after ${lost + 1} tries (${why})`);
|
|
425
|
+
}
|
|
426
|
+
await sleep(250 * 2 ** lost, signal);
|
|
427
|
+
lost += 1;
|
|
428
|
+
continue;
|
|
429
|
+
}
|
|
430
|
+
if (!(err instanceof ResponseError)) throw err;
|
|
431
|
+
const status = err.response.status;
|
|
432
|
+
const why = status === 409 ? firstDetail(await chatError(err))["reason"] : undefined;
|
|
433
|
+
if (why === "in_progress") {
|
|
434
|
+
// The first post with this key is still being delivered; answered only while the request is the open
|
|
435
|
+
// pause, so the same post is safe to repeat.
|
|
436
|
+
if (busy >= IN_PROGRESS_RETRIES) {
|
|
437
|
+
throw new RunError(why, `function results for request ${requestId} were still being delivered after ` +
|
|
438
|
+
`${busy + 1} tries`, 409, firstDetail(await chatError(err)));
|
|
439
|
+
}
|
|
440
|
+
await sleep(retryAfterMs(err), signal);
|
|
441
|
+
busy += 1;
|
|
442
|
+
continue;
|
|
443
|
+
}
|
|
444
|
+
if (status === 503) {
|
|
445
|
+
// Not delivered and nothing kept, but the agent may have them: the same key and results again.
|
|
446
|
+
if (unavailable >= UNAVAILABLE_RETRIES) {
|
|
447
|
+
throw new RunError("unavailable", `function results for request ${requestId} could not be delivered to ` +
|
|
448
|
+
`the agent after ${unavailable + 1} tries`, 503, firstDetail(await chatError(err)));
|
|
449
|
+
}
|
|
450
|
+
await sleep(retryAfterMs(err), signal);
|
|
451
|
+
unavailable += 1;
|
|
452
|
+
continue;
|
|
453
|
+
}
|
|
454
|
+
if (status === 409 && typeof why === "string" && Object.prototype.hasOwnProperty.call(WENT_ON, why)) {
|
|
455
|
+
console.warn(`function results for request ${requestId} were not taken (409 ${why}): ${WENT_ON[why]}; ` +
|
|
456
|
+
"following the turn");
|
|
457
|
+
return this.followAfter(conversationId, requestId, why, signal);
|
|
458
|
+
}
|
|
459
|
+
throw await refused(err, requestId);
|
|
460
|
+
}
|
|
461
|
+
}
|
|
462
|
+
if (!inner.duplicate) return new Stream(inner, conversationId);
|
|
463
|
+
// The server already had these results (an earlier post, ours or another process's, got through).
|
|
464
|
+
return this.follow(conversationId, signal);
|
|
465
|
+
}
|
|
466
|
+
|
|
467
|
+
/** The turn after a request someone already answered, as a replay of it from its start (the run skips up to the
|
|
468
|
+
* answered request): the running response by reconnecting without a cursor, else the conversation's last reply
|
|
469
|
+
* as stored. A turn that paused again ends on its new request, unanswered. */
|
|
470
|
+
async follow(conversationId: string, signal?: AbortSignal): Promise<TurnStream> {
|
|
471
|
+
return this.followAfter(conversationId, null, null, signal);
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
/** `follow`, after a 409 expired / already_answered for `requestId`: a turn not yet picked up again (no active
|
|
475
|
+
* response, and the last reply still ends on that request) is read again every second, up to 30 times; then
|
|
476
|
+
* RunError(reason). An abort ends the wait. */
|
|
477
|
+
private async followAfter(conversationId: string, requestId: string | null, why: string | null,
|
|
478
|
+
signal?: AbortSignal): Promise<TurnStream> {
|
|
479
|
+
for (let polls = 0; ; polls++) {
|
|
480
|
+
// Read raw: the stored parts are passed through as they are, not through the generated models.
|
|
481
|
+
const raw = await this.conversations.getConversationRaw({ conversationId }, { signal });
|
|
482
|
+
const detail: unknown = await raw.raw.json();
|
|
483
|
+
const body = (detail !== null && typeof detail === "object" ? detail : {}) as Record<string, unknown>;
|
|
484
|
+
const responseId = body["activeResponseId"];
|
|
485
|
+
if (typeof responseId === "string" && responseId) {
|
|
486
|
+
return new Stream(await reconnect(this.config, conversationId, responseId, null, { signal }), conversationId, true);
|
|
487
|
+
}
|
|
488
|
+
const messages = Array.isArray(body["messages"]) ? body["messages"] : [];
|
|
489
|
+
const last = [...messages].reverse().find((m) => m !== null && typeof m === "object"
|
|
490
|
+
&& (m as Record<string, unknown>)["role"] === "assistant");
|
|
491
|
+
if (requestId === null || !waitsOn(last, requestId)) {
|
|
492
|
+
return new Finished(conversationId, chunksFromUiMessage(last ?? null));
|
|
493
|
+
}
|
|
494
|
+
if (polls >= FOLLOW_POLLS) {
|
|
495
|
+
const code = why ?? "expired";
|
|
496
|
+
throw new RunError(code, `function results for request ${requestId}: ${WENT_ON[code] ?? code}, but the turn ` +
|
|
497
|
+
`has not gone on after ${polls} reads; read the conversation later`, 409, { reason: code });
|
|
498
|
+
}
|
|
499
|
+
await sleep(followPollMs.value, signal);
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async pending(conversationId: string): Promise<PendingFunctionCalls[]> {
|
|
504
|
+
const detail = await this.conversations.getConversation({ conversationId });
|
|
505
|
+
const grouped = new Map<string, PendingFunctionCalls>();
|
|
506
|
+
for (const action of detail.requiredActions ?? []) {
|
|
507
|
+
if ((action.type ?? "function_call") !== "function_call") continue;
|
|
508
|
+
let request = grouped.get(action.requestId);
|
|
509
|
+
if (request === undefined) {
|
|
510
|
+
request = { requestId: action.requestId, calls: [] };
|
|
511
|
+
const expires = action.expiresAt as unknown;
|
|
512
|
+
if (expires instanceof Date) request.expiresAt = expires.toISOString();
|
|
513
|
+
else if (typeof expires === "string") request.expiresAt = expires;
|
|
514
|
+
grouped.set(action.requestId, request);
|
|
515
|
+
}
|
|
516
|
+
request.calls.push({ callId: action.toolCallId, name: action.name, arguments: { ...(action.arguments ?? {}) } });
|
|
517
|
+
}
|
|
518
|
+
return Array.from(grouped.values());
|
|
519
|
+
}
|
|
520
|
+
|
|
235
521
|
// -- helpers --------------------------------------------------------------------------------------------
|
|
236
522
|
|
|
237
523
|
/** Put back what updateAgent overwrote; a failing restore must not mask the original error. */
|
package/src/compose/transport.ts
CHANGED
|
@@ -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
|
|
|
6
7
|
export interface SettingsWarning {
|
|
7
8
|
code: string;
|
|
@@ -22,9 +23,18 @@ export interface TurnStream extends AsyncIterable<Event> {
|
|
|
22
23
|
readonly conversationId: string | null;
|
|
23
24
|
readonly responseId: string | null;
|
|
24
25
|
readonly lastEventId: string | null;
|
|
26
|
+
/** Read without a cursor after a duplicate post: the server replays the turn from its start. */
|
|
27
|
+
readonly replay?: boolean;
|
|
25
28
|
close(): void;
|
|
26
29
|
}
|
|
27
30
|
|
|
31
|
+
/** A function-call request the conversation is waiting on (`requiredActions`, grouped by request). */
|
|
32
|
+
export interface PendingFunctionCalls {
|
|
33
|
+
requestId: string;
|
|
34
|
+
calls: FunctionCallRequest[];
|
|
35
|
+
expiresAt?: string;
|
|
36
|
+
}
|
|
37
|
+
|
|
28
38
|
export interface Transport {
|
|
29
39
|
readonly kind: "settings";
|
|
30
40
|
findAgents(sdkName: string): Promise<RemoteAgent[]>;
|
|
@@ -46,4 +56,17 @@ export interface Transport {
|
|
|
46
56
|
signal?: AbortSignal,
|
|
47
57
|
): Promise<TurnStream>;
|
|
48
58
|
stop(conversationId: string): Promise<void>;
|
|
59
|
+
/** Post the results of a function-call request and stream the rest of the turn. Optional so a transport written
|
|
60
|
+
* before function tools still type-checks; run() needs it only when the model calls a function. */
|
|
61
|
+
postFunctionResults?(
|
|
62
|
+
conversationId: string,
|
|
63
|
+
requestId: string,
|
|
64
|
+
results: FunctionResult[],
|
|
65
|
+
signal?: AbortSignal,
|
|
66
|
+
): Promise<TurnStream>;
|
|
67
|
+
/** The function-call requests the conversation is waiting on; used by `RunState.fromSession`. */
|
|
68
|
+
pending?(conversationId: string): Promise<PendingFunctionCalls[]>;
|
|
69
|
+
/** The turn after a request answered elsewhere, replayed from its start (`replay`); resuming a stale RunState
|
|
70
|
+
* follows it instead of running the calls again. */
|
|
71
|
+
follow?(conversationId: string, signal?: AbortSignal): Promise<TurnStream>;
|
|
49
72
|
}
|
|
@@ -27,6 +27,13 @@ import {
|
|
|
27
27
|
FieldHighlightToJSON,
|
|
28
28
|
FieldHighlightToJSONTyped,
|
|
29
29
|
} from './FieldHighlight.js';
|
|
30
|
+
import type { RequiredAction } from './RequiredAction.js';
|
|
31
|
+
import {
|
|
32
|
+
RequiredActionFromJSON,
|
|
33
|
+
RequiredActionFromJSONTyped,
|
|
34
|
+
RequiredActionToJSON,
|
|
35
|
+
RequiredActionToJSONTyped,
|
|
36
|
+
} from './RequiredAction.js';
|
|
30
37
|
import type { QueuedTurnView } from './QueuedTurnView.js';
|
|
31
38
|
import {
|
|
32
39
|
QueuedTurnViewFromJSON,
|
|
@@ -155,6 +162,12 @@ export interface AgentConversationDetail {
|
|
|
155
162
|
* @memberof AgentConversationDetail
|
|
156
163
|
*/
|
|
157
164
|
queuedTurns?: Array<QueuedTurnView>;
|
|
165
|
+
/**
|
|
166
|
+
*
|
|
167
|
+
* @type {Array<RequiredAction>}
|
|
168
|
+
* @memberof AgentConversationDetail
|
|
169
|
+
*/
|
|
170
|
+
requiredActions?: Array<RequiredAction>;
|
|
158
171
|
/**
|
|
159
172
|
*
|
|
160
173
|
* @type {boolean}
|
|
@@ -234,6 +247,7 @@ export function AgentConversationDetailFromJSONTyped(json: any, ignoreDiscrimina
|
|
|
234
247
|
'hasMore': json['hasMore'] == null ? undefined : json['hasMore'],
|
|
235
248
|
'nextBeforeCursor': json['nextBeforeCursor'] == null ? undefined : json['nextBeforeCursor'],
|
|
236
249
|
'queuedTurns': json['queuedTurns'] == null ? undefined : ((json['queuedTurns'] as Array<any>).map(QueuedTurnViewFromJSON)),
|
|
250
|
+
'requiredActions': json['requiredActions'] == null ? undefined : ((json['requiredActions'] as Array<any>).map(RequiredActionFromJSON)),
|
|
237
251
|
'isMine': json['isMine'] == null ? undefined : json['isMine'],
|
|
238
252
|
'panjaWsId': json['panjaWsId'],
|
|
239
253
|
'readOnly': json['readOnly'] == null ? undefined : json['readOnly'],
|
|
@@ -271,6 +285,7 @@ export function AgentConversationDetailToJSONTyped(value?: AgentConversationDeta
|
|
|
271
285
|
'hasMore': value['hasMore'],
|
|
272
286
|
'nextBeforeCursor': value['nextBeforeCursor'],
|
|
273
287
|
'queuedTurns': value['queuedTurns'] == null ? undefined : ((value['queuedTurns'] as Array<any>).map(QueuedTurnViewToJSON)),
|
|
288
|
+
'requiredActions': value['requiredActions'] == null ? undefined : ((value['requiredActions'] as Array<any>).map(RequiredActionToJSON)),
|
|
274
289
|
'isMine': value['isMine'],
|
|
275
290
|
'panjaWsId': value['panjaWsId'],
|
|
276
291
|
'readOnly': value['readOnly'],
|
|
@@ -37,6 +37,12 @@ export interface ClarifyBody {
|
|
|
37
37
|
* @memberof ClarifyBody
|
|
38
38
|
*/
|
|
39
39
|
answers?: { [key: string]: any; };
|
|
40
|
+
/**
|
|
41
|
+
*
|
|
42
|
+
* @type {string}
|
|
43
|
+
* @memberof ClarifyBody
|
|
44
|
+
*/
|
|
45
|
+
endUserId?: string | null;
|
|
40
46
|
}
|
|
41
47
|
|
|
42
48
|
/**
|
|
@@ -60,6 +66,7 @@ export function ClarifyBodyFromJSONTyped(json: any, ignoreDiscriminator: boolean
|
|
|
60
66
|
'requestId': json['requestId'],
|
|
61
67
|
'action': json['action'] == null ? undefined : json['action'],
|
|
62
68
|
'answers': json['answers'] == null ? undefined : json['answers'],
|
|
69
|
+
'endUserId': json['endUserId'] == null ? undefined : json['endUserId'],
|
|
63
70
|
};
|
|
64
71
|
}
|
|
65
72
|
|
|
@@ -77,6 +84,7 @@ export function ClarifyBodyToJSONTyped(value?: ClarifyBody | null, ignoreDiscrim
|
|
|
77
84
|
'requestId': value['requestId'],
|
|
78
85
|
'action': value['action'],
|
|
79
86
|
'answers': value['answers'],
|
|
87
|
+
'endUserId': value['endUserId'],
|
|
80
88
|
};
|
|
81
89
|
}
|
|
82
90
|
|
|
@@ -27,6 +27,13 @@ import {
|
|
|
27
27
|
FieldHighlightToJSON,
|
|
28
28
|
FieldHighlightToJSONTyped,
|
|
29
29
|
} from './FieldHighlight.js';
|
|
30
|
+
import type { RequiredAction } from './RequiredAction.js';
|
|
31
|
+
import {
|
|
32
|
+
RequiredActionFromJSON,
|
|
33
|
+
RequiredActionFromJSONTyped,
|
|
34
|
+
RequiredActionToJSON,
|
|
35
|
+
RequiredActionToJSONTyped,
|
|
36
|
+
} from './RequiredAction.js';
|
|
30
37
|
import type { QueuedTurnView } from './QueuedTurnView.js';
|
|
31
38
|
import {
|
|
32
39
|
QueuedTurnViewFromJSON,
|
|
@@ -156,6 +163,12 @@ export interface ConversationDetail {
|
|
|
156
163
|
* @memberof ConversationDetail
|
|
157
164
|
*/
|
|
158
165
|
queuedTurns?: Array<QueuedTurnView>;
|
|
166
|
+
/**
|
|
167
|
+
*
|
|
168
|
+
* @type {Array<RequiredAction>}
|
|
169
|
+
* @memberof ConversationDetail
|
|
170
|
+
*/
|
|
171
|
+
requiredActions?: Array<RequiredAction>;
|
|
159
172
|
}
|
|
160
173
|
|
|
161
174
|
/**
|
|
@@ -209,6 +222,7 @@ export function ConversationDetailFromJSONTyped(json: any, ignoreDiscriminator:
|
|
|
209
222
|
'hasMore': json['hasMore'] == null ? undefined : json['hasMore'],
|
|
210
223
|
'nextBeforeCursor': json['nextBeforeCursor'] == null ? undefined : json['nextBeforeCursor'],
|
|
211
224
|
'queuedTurns': json['queuedTurns'] == null ? undefined : ((json['queuedTurns'] as Array<any>).map(QueuedTurnViewFromJSON)),
|
|
225
|
+
'requiredActions': json['requiredActions'] == null ? undefined : ((json['requiredActions'] as Array<any>).map(RequiredActionFromJSON)),
|
|
212
226
|
};
|
|
213
227
|
}
|
|
214
228
|
|
|
@@ -242,6 +256,7 @@ export function ConversationDetailToJSONTyped(value?: ConversationDetail | null,
|
|
|
242
256
|
'hasMore': value['hasMore'],
|
|
243
257
|
'nextBeforeCursor': value['nextBeforeCursor'],
|
|
244
258
|
'queuedTurns': value['queuedTurns'] == null ? undefined : ((value['queuedTurns'] as Array<any>).map(QueuedTurnViewToJSON)),
|
|
259
|
+
'requiredActions': value['requiredActions'] == null ? undefined : ((value['requiredActions'] as Array<any>).map(RequiredActionToJSON)),
|
|
245
260
|
};
|
|
246
261
|
}
|
|
247
262
|
|
|
@@ -70,7 +70,8 @@ export const ErrorDetailCodeEnum = {
|
|
|
70
70
|
RateLimit: 'CHAT_RATE_LIMIT',
|
|
71
71
|
Unavailable: 'CHAT_UNAVAILABLE',
|
|
72
72
|
Upstream: 'CHAT_UPSTREAM',
|
|
73
|
-
Internal: 'CHAT_INTERNAL'
|
|
73
|
+
Internal: 'CHAT_INTERNAL',
|
|
74
|
+
BalanceExhausted: 'CHAT_BALANCE_EXHAUSTED'
|
|
74
75
|
} as const;
|
|
75
76
|
export type ErrorDetailCodeEnum = typeof ErrorDetailCodeEnum[keyof typeof ErrorDetailCodeEnum];
|
|
76
77
|
|
|
@@ -0,0 +1,83 @@
|
|
|
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
|
+
|
|
15
|
+
import { mapValues } from '../runtime.js';
|
|
16
|
+
/**
|
|
17
|
+
* One call's result, as the app ran it.
|
|
18
|
+
* @export
|
|
19
|
+
* @interface FunctionResultBody
|
|
20
|
+
*/
|
|
21
|
+
export interface FunctionResultBody {
|
|
22
|
+
/**
|
|
23
|
+
*
|
|
24
|
+
* @type {string}
|
|
25
|
+
* @memberof FunctionResultBody
|
|
26
|
+
*/
|
|
27
|
+
toolCallId: string;
|
|
28
|
+
/**
|
|
29
|
+
*
|
|
30
|
+
* @type {string}
|
|
31
|
+
* @memberof FunctionResultBody
|
|
32
|
+
*/
|
|
33
|
+
output: string;
|
|
34
|
+
/**
|
|
35
|
+
*
|
|
36
|
+
* @type {boolean}
|
|
37
|
+
* @memberof FunctionResultBody
|
|
38
|
+
*/
|
|
39
|
+
isError?: boolean;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Check if a given object implements the FunctionResultBody interface.
|
|
44
|
+
*/
|
|
45
|
+
export function instanceOfFunctionResultBody(value: object): value is FunctionResultBody {
|
|
46
|
+
if (!('toolCallId' in value) || value['toolCallId'] === undefined) return false;
|
|
47
|
+
if (!('output' in value) || value['output'] === undefined) return false;
|
|
48
|
+
return true;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export function FunctionResultBodyFromJSON(json: any): FunctionResultBody {
|
|
52
|
+
return FunctionResultBodyFromJSONTyped(json, false);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function FunctionResultBodyFromJSONTyped(json: any, ignoreDiscriminator: boolean): FunctionResultBody {
|
|
56
|
+
if (json == null) {
|
|
57
|
+
return json;
|
|
58
|
+
}
|
|
59
|
+
return {
|
|
60
|
+
|
|
61
|
+
'toolCallId': json['toolCallId'],
|
|
62
|
+
'output': json['output'],
|
|
63
|
+
'isError': json['isError'] == null ? undefined : json['isError'],
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function FunctionResultBodyToJSON(json: any): FunctionResultBody {
|
|
68
|
+
return FunctionResultBodyToJSONTyped(json, false);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
export function FunctionResultBodyToJSONTyped(value?: FunctionResultBody | null, ignoreDiscriminator: boolean = false): any {
|
|
72
|
+
if (value == null) {
|
|
73
|
+
return value;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
return {
|
|
77
|
+
|
|
78
|
+
'toolCallId': value['toolCallId'],
|
|
79
|
+
'output': value['output'],
|
|
80
|
+
'isError': value['isError'],
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
@@ -51,6 +51,18 @@ export interface QueueMessageInput {
|
|
|
51
51
|
* @memberof QueueMessageInput
|
|
52
52
|
*/
|
|
53
53
|
retryOf?: string | null;
|
|
54
|
+
/**
|
|
55
|
+
*
|
|
56
|
+
* @type {string}
|
|
57
|
+
* @memberof QueueMessageInput
|
|
58
|
+
*/
|
|
59
|
+
surface?: QueueMessageInputSurfaceEnum | null;
|
|
60
|
+
/**
|
|
61
|
+
*
|
|
62
|
+
* @type {string}
|
|
63
|
+
* @memberof QueueMessageInput
|
|
64
|
+
*/
|
|
65
|
+
endUserId?: string | null;
|
|
54
66
|
}
|
|
55
67
|
|
|
56
68
|
|
|
@@ -63,6 +75,18 @@ export const QueueMessageInputDeliveryEnum = {
|
|
|
63
75
|
} as const;
|
|
64
76
|
export type QueueMessageInputDeliveryEnum = typeof QueueMessageInputDeliveryEnum[keyof typeof QueueMessageInputDeliveryEnum];
|
|
65
77
|
|
|
78
|
+
/**
|
|
79
|
+
* @export
|
|
80
|
+
*/
|
|
81
|
+
export const QueueMessageInputSurfaceEnum = {
|
|
82
|
+
Builder: 'builder',
|
|
83
|
+
Playground: 'playground',
|
|
84
|
+
Tests: 'tests',
|
|
85
|
+
Evals: 'evals',
|
|
86
|
+
Cowork: 'cowork'
|
|
87
|
+
} as const;
|
|
88
|
+
export type QueueMessageInputSurfaceEnum = typeof QueueMessageInputSurfaceEnum[keyof typeof QueueMessageInputSurfaceEnum];
|
|
89
|
+
|
|
66
90
|
|
|
67
91
|
/**
|
|
68
92
|
* Check if a given object implements the QueueMessageInput interface.
|
|
@@ -86,6 +110,8 @@ export function QueueMessageInputFromJSONTyped(json: any, ignoreDiscriminator: b
|
|
|
86
110
|
'delivery': json['delivery'] == null ? undefined : json['delivery'],
|
|
87
111
|
'agentId': json['agentId'] == null ? undefined : json['agentId'],
|
|
88
112
|
'retryOf': json['retryOf'] == null ? undefined : json['retryOf'],
|
|
113
|
+
'surface': json['surface'] == null ? undefined : json['surface'],
|
|
114
|
+
'endUserId': json['endUserId'] == null ? undefined : json['endUserId'],
|
|
89
115
|
};
|
|
90
116
|
}
|
|
91
117
|
|
|
@@ -104,6 +130,8 @@ export function QueueMessageInputToJSONTyped(value?: QueueMessageInput | null, i
|
|
|
104
130
|
'delivery': value['delivery'],
|
|
105
131
|
'agentId': value['agentId'],
|
|
106
132
|
'retryOf': value['retryOf'],
|
|
133
|
+
'surface': value['surface'],
|
|
134
|
+
'endUserId': value['endUserId'],
|
|
107
135
|
};
|
|
108
136
|
}
|
|
109
137
|
|