@moss-dev/moss-web 1.6.0 → 1.7.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.
- package/README.md +98 -9
- package/dist/index.d.ts +1 -1
- package/dist/inference/error.d.ts +12 -3
- package/dist/inference/index.js +89 -28
- package/dist/inference/stream.d.ts +13 -3
- package/dist/inference/stream.js +156 -51
- package/dist/inference/types.d.ts +107 -11
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -18,7 +18,7 @@ Built on WebAssembly for near-native performance in any modern browser.
|
|
|
18
18
|
npm install @moss-dev/moss-web
|
|
19
19
|
```
|
|
20
20
|
|
|
21
|
-
Version 1.
|
|
21
|
+
Version 1.7.0 resolves `@moss-dev/moss-wasm@0.18.2`. Text `query()` loads its
|
|
22
22
|
model through the Moss service using the client's credentials, so the service
|
|
23
23
|
must be reachable the first time a model is loaded; there is no offline
|
|
24
24
|
fallback. Before 1.2.0 the only published npm versions were 1.0.0 and 1.0.1,
|
|
@@ -313,9 +313,18 @@ a page that uses [the proxy route](#the-proxy-route) leaves it to the route.
|
|
|
313
313
|
|
|
314
314
|
The other client options are `timeout` for each whole call (no limit by
|
|
315
315
|
default), `idleTimeout` for the longest wait for response headers or for more of
|
|
316
|
-
the body (120 000 ms by default, `null` for none) and `headers`.
|
|
317
|
-
`apiKey`, `signal`, `timeout`, `idleTimeout` and
|
|
318
|
-
to the client's for that call.
|
|
316
|
+
the body (120 000 ms by default, `null` for none), `maxRetries` and `headers`.
|
|
317
|
+
Each call takes `apiKey`, `signal`, `timeout`, `idleTimeout`, `maxRetries` and
|
|
318
|
+
`headers`, which replace or add to the client's for that call.
|
|
319
|
+
|
|
320
|
+
`maxRetries` (2 by default, `0` for none) sends a call again when the connection
|
|
321
|
+
fails, or when the gateway answers 408, 409, 429 or 5xx before the stream
|
|
322
|
+
starts, after a `Retry-After` of up to 60 s, else a backoff of 0.5 s doubling
|
|
323
|
+
up to 8 s, within `timeout`. `retrieve: false` or `indexes: []` skips the
|
|
324
|
+
search, and leaving `indexes` out searches every index. Moss can answer an
|
|
325
|
+
identical request from its reply cache; `cache: false` always asks the model.
|
|
326
|
+
`stream.requestId` and a completion's `requestId`, which `JSON.stringify` leaves
|
|
327
|
+
out, hold the response's `X-Moss-Request-Id`.
|
|
319
328
|
|
|
320
329
|
Leaving the `for await` loop early, or calling `stream.controller.abort()`,
|
|
321
330
|
closes the connection, stops the model and ends the loop quietly. An abort with
|
|
@@ -334,6 +343,72 @@ mid-reply as a network error, which is a `connection_error`. The client does
|
|
|
334
343
|
not follow redirects: a redirect throws `InferenceError`, with no `status` in a
|
|
335
344
|
browser, which hides it.
|
|
336
345
|
|
|
346
|
+
### Tool calls
|
|
347
|
+
|
|
348
|
+
`tools`, `tool_choice` and `parallel_tool_calls` take OpenAI's shapes, and your
|
|
349
|
+
code runs each call. After streaming the text, `finalChatCompletion()` joins
|
|
350
|
+
the stream into the reply. Push its message onto `messages` as it is: its tool
|
|
351
|
+
calls keep fields beyond OpenAI's, such as Gemini's `extra_content`, which the
|
|
352
|
+
model needs back. Then add one `tool` message per call and ask again:
|
|
353
|
+
|
|
354
|
+
```typescript
|
|
355
|
+
import type { ChatCompletionMessageParam, ChatCompletionTool } from "@moss-dev/moss-web";
|
|
356
|
+
|
|
357
|
+
const tools: ChatCompletionTool[] = [
|
|
358
|
+
{
|
|
359
|
+
type: "function",
|
|
360
|
+
function: {
|
|
361
|
+
name: "order_status",
|
|
362
|
+
parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
|
|
363
|
+
},
|
|
364
|
+
},
|
|
365
|
+
];
|
|
366
|
+
const history: ChatCompletionMessageParam[] = [{ role: "user", content: "Where is order A1?" }];
|
|
367
|
+
const stream = await client.chat.completions.create({ messages: history, tools, stream: true });
|
|
368
|
+
for await (const chunk of stream) answer.textContent += chunk.choices[0]?.delta.content ?? "";
|
|
369
|
+
const { message } = (await stream.finalChatCompletion()).choices[0];
|
|
370
|
+
history.push(message);
|
|
371
|
+
for (const call of message.tool_calls ?? []) {
|
|
372
|
+
const status = await orderStatus(JSON.parse(call.function.arguments).id);
|
|
373
|
+
history.push({ role: "tool", tool_call_id: call.id, content: status });
|
|
374
|
+
}
|
|
375
|
+
const reply = await client.chat.completions.create({ messages: history, tools });
|
|
376
|
+
```
|
|
377
|
+
|
|
378
|
+
### MCP servers
|
|
379
|
+
|
|
380
|
+
A `tools` entry of type `mcp`, typed `McpServer`, asks the gateway to call that
|
|
381
|
+
MCP server for the model during the turn. The server's `headers` hold its
|
|
382
|
+
credentials, and like a project key they are visible to every visitor in page
|
|
383
|
+
code, so [the proxy route](#the-proxy-route) adds the entry and the page sends
|
|
384
|
+
none. One chunk before and one after each tool call carries `moss_tool_step`,
|
|
385
|
+
and a completion lists the steps in `moss_tool_steps`:
|
|
386
|
+
|
|
387
|
+
```typescript
|
|
388
|
+
const stream = await client.chat.completions.create({ messages, stream: true });
|
|
389
|
+
for await (const chunk of stream) {
|
|
390
|
+
const step = chunk.moss_tool_step;
|
|
391
|
+
if (step?.type === "result") console.log(step.name, step.is_error, step.duration_ms);
|
|
392
|
+
answer.textContent += chunk.choices[0]?.delta.content ?? "";
|
|
393
|
+
}
|
|
394
|
+
const { moss_tool_steps } = await stream.finalChatCompletion();
|
|
395
|
+
console.log(moss_tool_steps?.map((step) => `${step.type} ${step.name}`));
|
|
396
|
+
```
|
|
397
|
+
|
|
398
|
+
A turn with tools can run for a few minutes.
|
|
399
|
+
|
|
400
|
+
| `status` | `type` | `errorCode` | When |
|
|
401
|
+
| --- | --- | --- | --- |
|
|
402
|
+
| 403 | `permission_error` | `mcp_not_enabled` | MCP is switched off on the gateway |
|
|
403
|
+
| 429 | `capacity` | `mcp_loops_busy` | The gateway is busy; retry after `retryAfter` |
|
|
404
|
+
| 400, 424 | `mcp_error` | `mcp_server_error` | The URL was refused, or the server failed |
|
|
405
|
+
| 400 | `invalid_request_error` | (none) | A bad `tools` entry, or a label or tool name used twice |
|
|
406
|
+
|
|
407
|
+
After a tool step every failure has `errorCode` `failed_after_tool_call`, and
|
|
408
|
+
the SDK never retries. Nor does it retry any stream that fails after it started.
|
|
409
|
+
The tool may have changed data, and so may a call you abort or time out after a
|
|
410
|
+
step, so do not replay such a call blindly.
|
|
411
|
+
|
|
337
412
|
### The proxy route
|
|
338
413
|
|
|
339
414
|
With `null` credentials the client sends no `Authorization` header, and an
|
|
@@ -346,13 +421,21 @@ a `Response`, it can look like this:
|
|
|
346
421
|
```typescript
|
|
347
422
|
// Serves POST /moss/v1/chat/completions. Check the visitor's session first,
|
|
348
423
|
// since every call through this route spends your project's quota.
|
|
424
|
+
import type { McpServer } from "@moss-dev/moss-web";
|
|
425
|
+
|
|
349
426
|
const GATEWAY = "https://inference.moss.dev/v1/chat/completions";
|
|
350
427
|
const INDEXES = ["faq"];
|
|
428
|
+
const CRM: McpServer = {
|
|
429
|
+
type: "mcp",
|
|
430
|
+
server_label: "crm",
|
|
431
|
+
server_url: "https://mcp.example.com/mcp",
|
|
432
|
+
allowed_tools: ["lookup_order"],
|
|
433
|
+
};
|
|
351
434
|
const FORWARD = ["content-type", "accept"];
|
|
352
435
|
const REPLY = ["content-type", "retry-after", "x-moss-request-id"];
|
|
353
436
|
|
|
354
437
|
export async function POST(request: Request): Promise<Response> {
|
|
355
|
-
const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY } = process.env;
|
|
438
|
+
const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY, CRM_TOKEN } = process.env;
|
|
356
439
|
const indexes = request.headers.get("x-moss-indexes")?.split(",") ?? INDEXES;
|
|
357
440
|
if (!indexes.every((name) => INDEXES.includes(name))) {
|
|
358
441
|
return Response.json({ detail: "This page cannot search that index." }, { status: 403 });
|
|
@@ -364,10 +447,14 @@ export async function POST(request: Request): Promise<Response> {
|
|
|
364
447
|
}
|
|
365
448
|
headers.set("X-Moss-Indexes", indexes.join(","));
|
|
366
449
|
headers.set("Authorization", `Bearer ${MOSS_PROJECT_ID}:${MOSS_PROJECT_KEY}`);
|
|
450
|
+
const body = await request.json();
|
|
451
|
+
const tools = Array.isArray(body.tools) ? body.tools : [];
|
|
452
|
+
const crm = { ...CRM, headers: { Authorization: `Bearer ${CRM_TOKEN}` } };
|
|
453
|
+
body.tools = [...tools.filter((tool) => tool?.type !== "mcp"), crm];
|
|
367
454
|
const reply = await fetch(GATEWAY, {
|
|
368
455
|
method: "POST",
|
|
369
456
|
headers,
|
|
370
|
-
body:
|
|
457
|
+
body: JSON.stringify(body),
|
|
371
458
|
signal: request.signal,
|
|
372
459
|
redirect: "manual",
|
|
373
460
|
});
|
|
@@ -381,9 +468,11 @@ since every visitor can set them. Back to the page it passes `Content-Type`,
|
|
|
381
468
|
`Retry-After` and `X-Moss-Request-Id`, so an `InferenceError` there carries
|
|
382
469
|
`retryAfter` and `requestId`. The route refuses an index that is not in its
|
|
383
470
|
list, and always sends `X-Moss-Indexes`, because a call without it searches
|
|
384
|
-
every index in the project. So `retrieve` and `apiKey`
|
|
385
|
-
reach the gateway, and a route that wants them sets those
|
|
386
|
-
as `X-Moss-Provider-Key` for your own provider key.
|
|
471
|
+
every index in the project. So `retrieve`, `indexes: []`, `cache` and `apiKey`
|
|
472
|
+
in page code do not reach the gateway, and a route that wants them sets those
|
|
473
|
+
headers itself, such as `X-Moss-Provider-Key` for your own provider key. The
|
|
474
|
+
route also drops any MCP entry the page sends and adds its own server, so the
|
|
475
|
+
page never holds MCP credentials.
|
|
387
476
|
|
|
388
477
|
Passing the project id and key instead of `null`, without `baseURL`, sends them
|
|
389
478
|
from the page straight to the gateway, which suits prototypes and internal tools.
|
package/dist/index.d.ts
CHANGED
|
@@ -6,5 +6,5 @@ export type { ChatCompletions } from "./inference/index.js";
|
|
|
6
6
|
export { ChatCompletionStream } from "./inference/stream.js";
|
|
7
7
|
export { InferenceError } from "./inference/error.js";
|
|
8
8
|
export type { InferenceErrorType } from "./inference/error.js";
|
|
9
|
-
export type { ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionChunkChoice, ChatCompletionChunkDelta, ChatCompletionChunkToolCall, ChatCompletionContentPart, ChatCompletionCreateParams, ChatCompletionCreateParamsBase, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTool, CompletionUsage, InferenceRequestOptions, MossInferenceOptions, } from "./inference/types.js";
|
|
9
|
+
export type { ChatCompletion, ChatCompletionChoice, ChatCompletionChunk, ChatCompletionChunkChoice, ChatCompletionChunkDelta, ChatCompletionChunkToolCall, ChatCompletionContentPart, ChatCompletionCreateParams, ChatCompletionCreateParamsBase, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, ChatCompletionLogprobs, ChatCompletionMessage, ChatCompletionMessageParam, ChatCompletionMessageToolCall, ChatCompletionTokenLogprob, ChatCompletionTool, CompletionUsage, InferenceRequestOptions, McpServer, MossInferenceOptions, ToolStep, } from "./inference/types.js";
|
|
10
10
|
export type { MossClientOptions, MossModel, IndexInfo, SearchResult, QueryResultDocumentInfo, QueryOptions, MetadataFilter, FilterCondition, RefreshResult, ModelRef, ModelArtifactIdentity, ModelDownloadProgress, DocumentInfo, MutationResult, CreateIndexOptions, MutationOptions, ParseFileInput, JobStatus, JobPhase, JobProgress, JobStatusResponse, GetDocumentsOptions, LoadIndexOptions, LoadIndexesResult, ISODate, } from "./types.js";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** The kind of failure an {@link InferenceError} reports. */
|
|
2
|
-
export type InferenceErrorType = "authentication_error" | "permission_error" | "not_found_error" | "invalid_request_error" | "rate_limit_error" | "model_error" | "server_error" | "connection_error" | "timeout" | "incomplete_stream" | (string & {});
|
|
2
|
+
export type InferenceErrorType = "authentication_error" | "permission_error" | "not_found_error" | "invalid_request_error" | "rate_limit_error" | "capacity" | "mcp_error" | "model_error" | "server_error" | "connection_error" | "timeout" | "incomplete_stream" | (string & {});
|
|
3
3
|
/**
|
|
4
4
|
* The error every inference call throws, before or during the stream.
|
|
5
5
|
* Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
|
|
@@ -10,7 +10,14 @@ export declare class InferenceError extends Error {
|
|
|
10
10
|
readonly status: number | undefined;
|
|
11
11
|
/** The gateway's `error.type`, or one derived from the status or the failure. */
|
|
12
12
|
readonly type: InferenceErrorType;
|
|
13
|
-
/**
|
|
13
|
+
/**
|
|
14
|
+
* The gateway's `error.code`, a string or a safe integer in decimal. Undefined otherwise.
|
|
15
|
+
*
|
|
16
|
+
* `failed_after_tool_call` once the stream carried an MCP tool step.
|
|
17
|
+
* The tool may have changed data, so do not replay the call blindly.
|
|
18
|
+
* The same holds for a call you abort after a step, which has no such code,
|
|
19
|
+
* as with `stream.controller.abort()` or a signal such as `AbortSignal.timeout()`.
|
|
20
|
+
*/
|
|
14
21
|
readonly errorCode?: string;
|
|
15
22
|
/** The `X-Moss-Request-Id` of the response. Undefined when the call failed before one arrived. */
|
|
16
23
|
readonly requestId?: string;
|
|
@@ -28,10 +35,12 @@ export declare class InferenceError extends Error {
|
|
|
28
35
|
cause?: unknown;
|
|
29
36
|
});
|
|
30
37
|
}
|
|
31
|
-
/** What
|
|
38
|
+
/** What every {@link InferenceError} of a call takes from its response. */
|
|
32
39
|
export interface ResponseFields {
|
|
33
40
|
requestId?: string;
|
|
34
41
|
retryAfter?: number;
|
|
42
|
+
/** Set once the stream carries an MCP tool step. */
|
|
43
|
+
errorCode?: "failed_after_tool_call";
|
|
35
44
|
}
|
|
36
45
|
/**
|
|
37
46
|
* The request id of any response, and for an error response
|
package/dist/inference/index.js
CHANGED
|
@@ -9,15 +9,18 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_own, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_apiKey, _MossInference_create;
|
|
12
|
+
var _MossInference_instances, _MossInference_path, _MossInference_headers, _MossInference_own, _MossInference_timeout, _MossInference_idleTimeout, _MossInference_maxRetries, _MossInference_apiKey, _MossInference_create;
|
|
13
13
|
import { InferenceError, errorFromResponse, responseFields, transportError, } from "./error.js";
|
|
14
|
-
import { ChatCompletionStream,
|
|
14
|
+
import { ChatCompletionStream, errorText, idleTimer } from "./stream.js";
|
|
15
15
|
/** The production gateway, up to and including `/v1`. */
|
|
16
16
|
const DEFAULT_URL = "https://inference.moss.dev/v1";
|
|
17
17
|
const DEFAULT_MODEL = "moss";
|
|
18
18
|
const DEFAULT_IDLE_TIMEOUT = 120000;
|
|
19
|
+
const DEFAULT_RETRIES = 2;
|
|
19
20
|
/** The longest delay `setTimeout` holds. */
|
|
20
21
|
const MAX_DELAY = 2 ** 31 - 1;
|
|
22
|
+
/** The longest `Retry-After` a retry waits, in milliseconds. A longer one waits the backoff. */
|
|
23
|
+
const MAX_RETRY_AFTER = 60000;
|
|
21
24
|
function invalid(message) {
|
|
22
25
|
return new InferenceError(message, { type: "invalid_request_error" });
|
|
23
26
|
}
|
|
@@ -57,6 +60,34 @@ function delay(what, value) {
|
|
|
57
60
|
return Math.min(value, MAX_DELAY);
|
|
58
61
|
throw invalid(`${what} must be a positive number of milliseconds, or null for no limit.`);
|
|
59
62
|
}
|
|
63
|
+
/** A retry count, a whole number of 0 or more. */
|
|
64
|
+
function retries(value) {
|
|
65
|
+
if (typeof value === "number" && Number.isSafeInteger(value) && value >= 0)
|
|
66
|
+
return value;
|
|
67
|
+
throw invalid("maxRetries must be a whole number of 0 or more.");
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* True when a failed response may be sent again.
|
|
71
|
+
* Its `x-should-retry` decides when present, else a 408, 409, 429 or 5xx does.
|
|
72
|
+
*/
|
|
73
|
+
function retryable(response) {
|
|
74
|
+
const header = response.headers.get("x-should-retry");
|
|
75
|
+
if (header === "true" || header === "false")
|
|
76
|
+
return header === "true";
|
|
77
|
+
return [408, 409, 429].includes(response.status) || response.status >= 500;
|
|
78
|
+
}
|
|
79
|
+
/** Resolves after `ms`, or at once when `signal` aborts. */
|
|
80
|
+
function pause(ms, signal) {
|
|
81
|
+
return new Promise((resolve) => {
|
|
82
|
+
const done = () => {
|
|
83
|
+
clearTimeout(timer);
|
|
84
|
+
signal.removeEventListener("abort", done);
|
|
85
|
+
resolve();
|
|
86
|
+
};
|
|
87
|
+
const timer = setTimeout(done, ms);
|
|
88
|
+
signal.addEventListener("abort", done, { once: true });
|
|
89
|
+
});
|
|
90
|
+
}
|
|
60
91
|
/**
|
|
61
92
|
* A path with one leading slash, in printable ASCII without a space or backslash.
|
|
62
93
|
* Resolved against an http or https page, it always stays on the page's origin.
|
|
@@ -105,6 +136,7 @@ export class MossInference {
|
|
|
105
136
|
_MossInference_own.set(this, void 0);
|
|
106
137
|
_MossInference_timeout.set(this, void 0);
|
|
107
138
|
_MossInference_idleTimeout.set(this, void 0);
|
|
139
|
+
_MossInference_maxRetries.set(this, void 0);
|
|
108
140
|
/** The provider key for calls that do not pass their own. */
|
|
109
141
|
_MossInference_apiKey.set(this, void 0);
|
|
110
142
|
__classPrivateFieldSet(this, _MossInference_own, new Headers({ "Content-Type": "application/json", Accept: "text/event-stream" }), "f");
|
|
@@ -122,8 +154,9 @@ export class MossInference {
|
|
|
122
154
|
}
|
|
123
155
|
__classPrivateFieldSet(this, _MossInference_path, options.baseURL == null ? undefined : proxyPath(options.baseURL), "f");
|
|
124
156
|
__classPrivateFieldSet(this, _MossInference_timeout, delay("timeout", options.timeout ?? null), "f");
|
|
125
|
-
const { idleTimeout = DEFAULT_IDLE_TIMEOUT } = options;
|
|
157
|
+
const { idleTimeout = DEFAULT_IDLE_TIMEOUT, maxRetries = DEFAULT_RETRIES } = options;
|
|
126
158
|
__classPrivateFieldSet(this, _MossInference_idleTimeout, delay("idleTimeout", idleTimeout), "f");
|
|
159
|
+
__classPrivateFieldSet(this, _MossInference_maxRetries, retries(maxRetries), "f");
|
|
127
160
|
__classPrivateFieldSet(this, _MossInference_headers, headersOf(options.headers), "f");
|
|
128
161
|
__classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
|
|
129
162
|
const create = (params, call) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_create).call(this, params, call);
|
|
@@ -132,9 +165,9 @@ export class MossInference {
|
|
|
132
165
|
});
|
|
133
166
|
}
|
|
134
167
|
}
|
|
135
|
-
_MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _MossInference_own = new WeakMap(), _MossInference_timeout = new WeakMap(), _MossInference_idleTimeout = new WeakMap(), _MossInference_apiKey = new WeakMap(), _MossInference_instances = new WeakSet(), _MossInference_create = async function _MossInference_create(params, options = {}) {
|
|
168
|
+
_MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _MossInference_own = new WeakMap(), _MossInference_timeout = new WeakMap(), _MossInference_idleTimeout = new WeakMap(), _MossInference_maxRetries = new WeakMap(), _MossInference_apiKey = new WeakMap(), _MossInference_instances = new WeakSet(), _MossInference_create = async function _MossInference_create(params, options = {}) {
|
|
136
169
|
const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/chat/completions` : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
|
|
137
|
-
const { indexes, retrieve, model = DEFAULT_MODEL, ...body } = params;
|
|
170
|
+
const { indexes, retrieve, cache, model = DEFAULT_MODEL, ...body } = params;
|
|
138
171
|
if (body.apiKey !== undefined || body.api_key !== undefined)
|
|
139
172
|
throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
|
|
140
173
|
if (indexes !== undefined && !Array.isArray(indexes))
|
|
@@ -150,6 +183,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
150
183
|
const idleTimeout = options.idleTimeout === undefined
|
|
151
184
|
? __classPrivateFieldGet(this, _MossInference_idleTimeout, "f")
|
|
152
185
|
: delay("idleTimeout", options.idleTimeout);
|
|
186
|
+
const maxRetries = options.maxRetries === undefined ? __classPrivateFieldGet(this, _MossInference_maxRetries, "f") : retries(options.maxRetries);
|
|
153
187
|
const headers = new Headers(__classPrivateFieldGet(this, _MossInference_headers, "f"));
|
|
154
188
|
for (const [name, value] of headersOf(options.headers))
|
|
155
189
|
headers.set(name, value);
|
|
@@ -157,8 +191,12 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
157
191
|
headers.set(name, value);
|
|
158
192
|
if (indexes?.length)
|
|
159
193
|
headers.set("X-Moss-Indexes", indexes.join(","));
|
|
160
|
-
if (
|
|
194
|
+
else if (indexes)
|
|
195
|
+
headers.delete("X-Moss-Indexes");
|
|
196
|
+
if (retrieve === false || indexes?.length === 0)
|
|
161
197
|
headers.set("X-Moss-Retrieve", "off");
|
|
198
|
+
if (cache === false)
|
|
199
|
+
headers.set("X-Moss-Cache", "off");
|
|
162
200
|
if (apiKey !== undefined)
|
|
163
201
|
headers.set("X-Moss-Provider-Key", apiKey);
|
|
164
202
|
let payload;
|
|
@@ -166,7 +204,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
166
204
|
payload = JSON.stringify({ model, ...body, stream: true });
|
|
167
205
|
}
|
|
168
206
|
catch (cause) {
|
|
169
|
-
throw new InferenceError(
|
|
207
|
+
throw new InferenceError("The parameters cannot be sent as JSON.", {
|
|
170
208
|
type: "invalid_request_error",
|
|
171
209
|
cause,
|
|
172
210
|
});
|
|
@@ -178,6 +216,7 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
178
216
|
const timer = timeout === null
|
|
179
217
|
? undefined
|
|
180
218
|
: setTimeout(expire(`The request timed out after ${timeout} ms.`), timeout);
|
|
219
|
+
const deadline = timeout === null ? Infinity : Date.now() + timeout;
|
|
181
220
|
const idle = idleTimer(idleTimeout, expire(`The gateway sent nothing for ${idleTimeout} ms.`));
|
|
182
221
|
const onAbort = () => controller.abort(signal?.reason);
|
|
183
222
|
signal?.addEventListener("abort", onAbort, { once: true });
|
|
@@ -189,28 +228,50 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
189
228
|
signal?.removeEventListener("abort", onAbort);
|
|
190
229
|
};
|
|
191
230
|
let response;
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
231
|
+
for (let attempt = 0;; attempt++) {
|
|
232
|
+
fields = {};
|
|
233
|
+
let wait = Math.min(500 * 2 ** attempt, 8000) * (1 - Math.random() / 4);
|
|
234
|
+
try {
|
|
235
|
+
idle.arm();
|
|
236
|
+
response = await fetch(url, {
|
|
237
|
+
method: "POST",
|
|
238
|
+
headers,
|
|
239
|
+
body: payload,
|
|
240
|
+
signal: controller.signal,
|
|
241
|
+
redirect: "manual",
|
|
242
|
+
});
|
|
243
|
+
idle.clear();
|
|
244
|
+
fields = responseFields(response);
|
|
245
|
+
const after = fields.retryAfter ?? Infinity;
|
|
246
|
+
if (after <= MAX_RETRY_AFTER)
|
|
247
|
+
wait = after;
|
|
248
|
+
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
249
|
+
if (response.ok || last || !retryable(response))
|
|
250
|
+
break;
|
|
251
|
+
response.body?.cancel().catch(() => { });
|
|
252
|
+
}
|
|
253
|
+
catch (error) {
|
|
254
|
+
idle.clear();
|
|
255
|
+
const code = error?.cause?.code;
|
|
256
|
+
const headersTimeout = code === "UND_ERR_HEADERS_TIMEOUT";
|
|
257
|
+
const last = attempt >= maxRetries || Date.now() + wait >= deadline;
|
|
258
|
+
if (controller.signal.aborted || headersTimeout || last) {
|
|
259
|
+
settle();
|
|
260
|
+
if (controller.signal.aborted)
|
|
261
|
+
throw controller.signal.reason;
|
|
262
|
+
const failure = transportError(error, "The inference gateway did not answer");
|
|
263
|
+
if (failure.type === "connection_error") {
|
|
264
|
+
failure.message = `${failure.message.replace(/\.$/, "")}. Check the network, and that the gateway allows this page's origin (CORS).`;
|
|
265
|
+
}
|
|
266
|
+
throw failure;
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
await pause(wait, controller.signal);
|
|
270
|
+
if (controller.signal.aborted) {
|
|
271
|
+
settle();
|
|
205
272
|
throw controller.signal.reason;
|
|
206
|
-
const failure = transportError(error, "The inference gateway did not answer");
|
|
207
|
-
if (failure.type === "connection_error") {
|
|
208
|
-
failure.message = `${failure.message.replace(/\.$/, "")}. Check the network, and that the gateway allows this page's origin (CORS).`;
|
|
209
273
|
}
|
|
210
|
-
throw failure;
|
|
211
274
|
}
|
|
212
|
-
idle.clear();
|
|
213
|
-
fields = responseFields(response);
|
|
214
275
|
if (response.type === "opaqueredirect") {
|
|
215
276
|
settle();
|
|
216
277
|
const message = "The gateway answered with a redirect, which the client does not follow.";
|
|
@@ -223,6 +284,6 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
223
284
|
throw controller.signal.reason;
|
|
224
285
|
throw errorFromResponse(response, text);
|
|
225
286
|
}
|
|
226
|
-
const stream = new ChatCompletionStream(response, controller, idle, settle);
|
|
227
|
-
return params.stream ? stream :
|
|
287
|
+
const stream = new ChatCompletionStream(response, controller, idle, settle, fields, model);
|
|
288
|
+
return params.stream ? stream : stream.finalChatCompletion();
|
|
228
289
|
};
|
|
@@ -17,15 +17,25 @@ export declare function errorText(response: Response, idle: IdleTimer): Promise<
|
|
|
17
17
|
* Iterate it once with `for await`. Leaving the loop early, or calling
|
|
18
18
|
* `controller.abort()`, ends the loop quietly, closes the connection and stops the model.
|
|
19
19
|
* An abort with any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws it.
|
|
20
|
-
* A failure inside the stream throws an {@link InferenceError} after the chunks that came before it
|
|
20
|
+
* A failure inside the stream throws an {@link InferenceError} after the chunks that came before it,
|
|
21
|
+
* with `errorCode` `failed_after_tool_call` once a chunk carried a `moss_tool_step`.
|
|
21
22
|
*/
|
|
22
23
|
export declare class ChatCompletionStream implements AsyncIterable<ChatCompletionChunk> {
|
|
23
24
|
#private;
|
|
24
25
|
/** Aborts the request. */
|
|
25
26
|
readonly controller: AbortController;
|
|
27
|
+
/** The `X-Moss-Request-Id` of the response, undefined when it has none. */
|
|
28
|
+
readonly requestId: string | undefined;
|
|
26
29
|
/** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
|
|
27
30
|
[Symbol.asyncIterator](): AsyncIterator<ChatCompletionChunk>;
|
|
31
|
+
/**
|
|
32
|
+
* The whole stream joined into one completion, as a call without `stream: true` returns.
|
|
33
|
+
*
|
|
34
|
+
* Every call returns the same completion.
|
|
35
|
+
* Call it after the loop ends, or instead of one.
|
|
36
|
+
* It reads the chunks the loop has not read, then joins them with the ones it has.
|
|
37
|
+
* It rejects with what the loop throws, or with the signal's reason after an abort.
|
|
38
|
+
*/
|
|
39
|
+
finalChatCompletion(): Promise<ChatCompletion>;
|
|
28
40
|
}
|
|
29
|
-
/** Consumes every chunk and builds one completion, as a non-streaming call returns. */
|
|
30
|
-
export declare function aggregate(stream: ChatCompletionStream, model: string): Promise<ChatCompletion>;
|
|
31
41
|
export {};
|
package/dist/inference/stream.js
CHANGED
|
@@ -9,8 +9,8 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
9
9
|
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
|
|
10
10
|
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
|
|
11
11
|
};
|
|
12
|
-
var _ChatCompletionStream_chunks;
|
|
13
|
-
import { InferenceError, codeText,
|
|
12
|
+
var _ChatCompletionStream_instances, _ChatCompletionStream_chunks, _ChatCompletionStream_next, _ChatCompletionStream_join, _ChatCompletionStream_failure, _ChatCompletionStream_final, _ChatCompletionStream_drain;
|
|
13
|
+
import { InferenceError, codeText, transportError } from "./error.js";
|
|
14
14
|
/** The most UTF-16 code units in one line or in the data of one event. */
|
|
15
15
|
const MAX_EVENT = 1 << 20;
|
|
16
16
|
/** The most bytes of an error body read for its message. */
|
|
@@ -120,16 +120,37 @@ async function* sseData(body, idle, fields) {
|
|
|
120
120
|
* Iterate it once with `for await`. Leaving the loop early, or calling
|
|
121
121
|
* `controller.abort()`, ends the loop quietly, closes the connection and stops the model.
|
|
122
122
|
* An abort with any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws it.
|
|
123
|
-
* A failure inside the stream throws an {@link InferenceError} after the chunks that came before it
|
|
123
|
+
* A failure inside the stream throws an {@link InferenceError} after the chunks that came before it,
|
|
124
|
+
* with `errorCode` `failed_after_tool_call` once a chunk carried a `moss_tool_step`.
|
|
124
125
|
*/
|
|
125
126
|
export class ChatCompletionStream {
|
|
126
127
|
/** @internal */
|
|
127
|
-
constructor(response, controller, idle, onSettled) {
|
|
128
|
+
constructor(response, controller, idle, onSettled, fields, model) {
|
|
129
|
+
_ChatCompletionStream_instances.add(this);
|
|
128
130
|
_ChatCompletionStream_chunks.set(this, void 0);
|
|
131
|
+
_ChatCompletionStream_next.set(this, void 0);
|
|
132
|
+
_ChatCompletionStream_join.set(this, void 0);
|
|
133
|
+
/** What reading the chunks threw, which the completion throws again. */
|
|
134
|
+
_ChatCompletionStream_failure.set(this, void 0);
|
|
135
|
+
_ChatCompletionStream_final.set(this, void 0);
|
|
129
136
|
this.controller = controller;
|
|
130
|
-
|
|
137
|
+
this.requestId = fields.requestId;
|
|
138
|
+
__classPrivateFieldSet(this, _ChatCompletionStream_join, new Join(model), "f");
|
|
139
|
+
const generator = chunks(response, controller, idle, onSettled, fields);
|
|
140
|
+
__classPrivateFieldSet(this, _ChatCompletionStream_next, async () => {
|
|
141
|
+
try {
|
|
142
|
+
const result = await generator.next();
|
|
143
|
+
if (!result.done)
|
|
144
|
+
__classPrivateFieldGet(this, _ChatCompletionStream_join, "f").add(result.value);
|
|
145
|
+
return result;
|
|
146
|
+
}
|
|
147
|
+
catch (error) {
|
|
148
|
+
__classPrivateFieldSet(this, _ChatCompletionStream_failure, { error }, "f");
|
|
149
|
+
throw error;
|
|
150
|
+
}
|
|
151
|
+
}, "f");
|
|
131
152
|
__classPrivateFieldSet(this, _ChatCompletionStream_chunks, {
|
|
132
|
-
next: (
|
|
153
|
+
next: __classPrivateFieldGet(this, _ChatCompletionStream_next, "f"),
|
|
133
154
|
return: (value) => {
|
|
134
155
|
controller.abort();
|
|
135
156
|
onSettled();
|
|
@@ -138,17 +159,37 @@ export class ChatCompletionStream {
|
|
|
138
159
|
}, "f");
|
|
139
160
|
}
|
|
140
161
|
/** Iterates the chunks once. Its `return()` closes the connection, even before the first chunk. */
|
|
141
|
-
[(_ChatCompletionStream_chunks = new WeakMap(), Symbol.asyncIterator)]() {
|
|
162
|
+
[(_ChatCompletionStream_chunks = new WeakMap(), _ChatCompletionStream_next = new WeakMap(), _ChatCompletionStream_join = new WeakMap(), _ChatCompletionStream_failure = new WeakMap(), _ChatCompletionStream_final = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), Symbol.asyncIterator)]() {
|
|
142
163
|
const iterator = __classPrivateFieldGet(this, _ChatCompletionStream_chunks, "f");
|
|
143
164
|
if (!iterator)
|
|
144
165
|
throw new Error("A ChatCompletionStream can be iterated only once.");
|
|
145
166
|
__classPrivateFieldSet(this, _ChatCompletionStream_chunks, undefined, "f");
|
|
146
167
|
return iterator;
|
|
147
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
* The whole stream joined into one completion, as a call without `stream: true` returns.
|
|
171
|
+
*
|
|
172
|
+
* Every call returns the same completion.
|
|
173
|
+
* Call it after the loop ends, or instead of one.
|
|
174
|
+
* It reads the chunks the loop has not read, then joins them with the ones it has.
|
|
175
|
+
* It rejects with what the loop throws, or with the signal's reason after an abort.
|
|
176
|
+
*/
|
|
177
|
+
finalChatCompletion() {
|
|
178
|
+
return (__classPrivateFieldSet(this, _ChatCompletionStream_final, __classPrivateFieldGet(this, _ChatCompletionStream_final, "f") ?? __classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_drain).call(this), "f"));
|
|
179
|
+
}
|
|
148
180
|
}
|
|
149
|
-
async function
|
|
181
|
+
_ChatCompletionStream_drain = async function _ChatCompletionStream_drain() {
|
|
182
|
+
while (!(await __classPrivateFieldGet(this, _ChatCompletionStream_next, "f").call(this)).done)
|
|
183
|
+
;
|
|
184
|
+
if (__classPrivateFieldGet(this, _ChatCompletionStream_failure, "f"))
|
|
185
|
+
throw __classPrivateFieldGet(this, _ChatCompletionStream_failure, "f").error;
|
|
186
|
+
const { signal } = this.controller;
|
|
187
|
+
if (signal.aborted)
|
|
188
|
+
throw signal.reason;
|
|
189
|
+
return Object.defineProperty(__classPrivateFieldGet(this, _ChatCompletionStream_join, "f").build(), "requestId", { value: this.requestId });
|
|
190
|
+
};
|
|
191
|
+
async function* chunks(response, controller, idle, onSettled, fields) {
|
|
150
192
|
const notObject = "The gateway sent an event that is not a JSON object.";
|
|
151
|
-
const fields = responseFields(response);
|
|
152
193
|
let done = false;
|
|
153
194
|
try {
|
|
154
195
|
if (!response.body) {
|
|
@@ -180,6 +221,8 @@ async function* chunks(response, controller, idle, onSettled) {
|
|
|
180
221
|
...fields,
|
|
181
222
|
});
|
|
182
223
|
}
|
|
224
|
+
if (event.moss_tool_step)
|
|
225
|
+
fields.errorCode = "failed_after_tool_call";
|
|
183
226
|
yield event;
|
|
184
227
|
}
|
|
185
228
|
throw new InferenceError("The stream ended before [DONE].", {
|
|
@@ -211,60 +254,122 @@ async function* chunks(response, controller, idle, onSettled) {
|
|
|
211
254
|
onSettled();
|
|
212
255
|
}
|
|
213
256
|
}
|
|
214
|
-
/**
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
257
|
+
/** True for a JSON object, not null or an array. */
|
|
258
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
259
|
+
/**
|
|
260
|
+
* Joins chunks as they pass into one completion, as a non-streaming call returns.
|
|
261
|
+
*
|
|
262
|
+
* It joins tool call pieces as the gateway does, keeping fields beyond OpenAI's.
|
|
263
|
+
* A piece with no integer `index` joins the call that has its `id`, else the latest call.
|
|
264
|
+
* A new `id` starts the next call instead, unless the latest call has no id yet and takes it.
|
|
265
|
+
*/
|
|
266
|
+
class Join {
|
|
267
|
+
constructor(model) {
|
|
268
|
+
this.model = model;
|
|
269
|
+
this.choices = new Map();
|
|
270
|
+
this.steps = [];
|
|
271
|
+
this.usage = null;
|
|
272
|
+
}
|
|
273
|
+
add(chunk) {
|
|
274
|
+
var _a;
|
|
275
|
+
this.first ?? (this.first = chunk);
|
|
222
276
|
if (chunk.usage)
|
|
223
|
-
usage = chunk.usage;
|
|
224
|
-
|
|
277
|
+
this.usage = chunk.usage;
|
|
278
|
+
if (chunk.moss_tool_step)
|
|
279
|
+
this.steps.push(chunk.moss_tool_step);
|
|
280
|
+
for (const choice of Array.isArray(chunk.choices) ? chunk.choices : []) {
|
|
281
|
+
if (!isObject(choice))
|
|
282
|
+
continue;
|
|
225
283
|
const index = choice.index ?? 0;
|
|
226
|
-
let state = choices.get(index);
|
|
227
|
-
if (!state)
|
|
228
|
-
|
|
284
|
+
let state = this.choices.get(index);
|
|
285
|
+
if (!state) {
|
|
286
|
+
state = {
|
|
287
|
+
content: null,
|
|
288
|
+
logprobs: null,
|
|
289
|
+
finishReason: null,
|
|
290
|
+
toolCalls: new Map(),
|
|
291
|
+
last: -1,
|
|
292
|
+
};
|
|
293
|
+
this.choices.set(index, state);
|
|
294
|
+
}
|
|
229
295
|
const delta = choice.delta ?? {};
|
|
230
296
|
if (delta.content)
|
|
231
297
|
state.content = (state.content ?? "") + delta.content;
|
|
232
|
-
|
|
233
|
-
|
|
298
|
+
if (isObject(choice.logprobs)) {
|
|
299
|
+
state.logprobs ?? (state.logprobs = { content: null, refusal: null });
|
|
300
|
+
for (const key of ["content", "refusal"]) {
|
|
301
|
+
const tokens = choice.logprobs[key];
|
|
302
|
+
if (Array.isArray(tokens))
|
|
303
|
+
((_a = state.logprobs)[key] ?? (_a[key] = [])).push(...tokens);
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
const parts = Array.isArray(delta.tool_calls) ? delta.tool_calls : [];
|
|
307
|
+
for (const part of parts) {
|
|
308
|
+
if (!isObject(part))
|
|
309
|
+
continue;
|
|
310
|
+
let slot = part.index;
|
|
311
|
+
if (!Number.isInteger(slot)) {
|
|
312
|
+
const known = [...state.toolCalls].find(([, joined]) => part.id && joined.id === part.id);
|
|
313
|
+
const latest = state.toolCalls.get(state.last);
|
|
314
|
+
if (known)
|
|
315
|
+
slot = known[0];
|
|
316
|
+
else if (latest && !(part.id && latest.id))
|
|
317
|
+
slot = state.last;
|
|
318
|
+
else
|
|
319
|
+
slot = Math.max(-1, ...state.toolCalls.keys()) + 1;
|
|
320
|
+
}
|
|
321
|
+
state.last = slot;
|
|
322
|
+
const call = state.toolCalls.get(slot) ?? {
|
|
234
323
|
id: "",
|
|
235
324
|
type: "function",
|
|
236
325
|
function: { name: "", arguments: "" },
|
|
237
326
|
};
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
327
|
+
if (part.id)
|
|
328
|
+
call.id = part.id;
|
|
329
|
+
if (part.type)
|
|
330
|
+
call.type = part.type;
|
|
331
|
+
if (part.function?.name)
|
|
332
|
+
call.function.name = part.function.name;
|
|
333
|
+
if (typeof part.function?.arguments === "string")
|
|
334
|
+
call.function.arguments += part.function.arguments;
|
|
335
|
+
for (const [key, value] of Object.entries(part)) {
|
|
336
|
+
if (value == null || ["index", "id", "type", "function"].includes(key))
|
|
337
|
+
continue;
|
|
338
|
+
const merged = isObject(value) && isObject(call[key]) ? { ...call[key], ...value } : value;
|
|
339
|
+
Object.defineProperty(call, key, {
|
|
340
|
+
value: merged,
|
|
341
|
+
enumerable: true,
|
|
342
|
+
writable: true,
|
|
343
|
+
configurable: true,
|
|
344
|
+
});
|
|
345
|
+
}
|
|
346
|
+
state.toolCalls.set(slot, call);
|
|
242
347
|
}
|
|
243
348
|
if (choice.finish_reason != null)
|
|
244
349
|
state.finishReason = choice.finish_reason;
|
|
245
350
|
}
|
|
246
351
|
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
index,
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
352
|
+
build() {
|
|
353
|
+
const byIndex = (map) => [...map].sort(([a], [b]) => a - b);
|
|
354
|
+
return {
|
|
355
|
+
id: this.first?.id ?? "",
|
|
356
|
+
object: "chat.completion",
|
|
357
|
+
created: this.first?.created ?? 0,
|
|
358
|
+
model: this.first?.model ?? this.model,
|
|
359
|
+
choices: byIndex(this.choices).map(([index, state]) => ({
|
|
360
|
+
index,
|
|
361
|
+
message: {
|
|
362
|
+
role: "assistant",
|
|
363
|
+
content: state.content ?? (state.toolCalls.size > 0 ? null : ""),
|
|
364
|
+
...(state.toolCalls.size > 0 && {
|
|
365
|
+
tool_calls: byIndex(state.toolCalls).map(([, call]) => call),
|
|
366
|
+
}),
|
|
367
|
+
},
|
|
368
|
+
logprobs: state.logprobs,
|
|
369
|
+
finish_reason: state.finishReason,
|
|
370
|
+
})),
|
|
371
|
+
usage: this.usage,
|
|
372
|
+
...(this.steps.length > 0 && { moss_tool_steps: this.steps }),
|
|
373
|
+
};
|
|
374
|
+
}
|
|
270
375
|
}
|
|
@@ -4,7 +4,10 @@ export interface ChatCompletionContentPart {
|
|
|
4
4
|
text?: string;
|
|
5
5
|
[key: string]: any;
|
|
6
6
|
}
|
|
7
|
-
/**
|
|
7
|
+
/**
|
|
8
|
+
* A tool call the model made, as the API returns it.
|
|
9
|
+
* Fields the model adds, such as Gemini's `extra_content`, stay on the object.
|
|
10
|
+
*/
|
|
8
11
|
export interface ChatCompletionMessageToolCall {
|
|
9
12
|
id: string;
|
|
10
13
|
type: "function";
|
|
@@ -12,6 +15,7 @@ export interface ChatCompletionMessageToolCall {
|
|
|
12
15
|
name: string;
|
|
13
16
|
arguments: string;
|
|
14
17
|
};
|
|
18
|
+
[key: string]: any;
|
|
15
19
|
}
|
|
16
20
|
/** One message of the conversation, in OpenAI's shape. */
|
|
17
21
|
export interface ChatCompletionMessageParam {
|
|
@@ -25,7 +29,7 @@ export interface ChatCompletionMessageParam {
|
|
|
25
29
|
tool_call_id?: string;
|
|
26
30
|
[key: string]: any;
|
|
27
31
|
}
|
|
28
|
-
/** A function the model may call. */
|
|
32
|
+
/** A function the model may call. Your code runs it and sends back the result. */
|
|
29
33
|
export interface ChatCompletionTool {
|
|
30
34
|
type: "function";
|
|
31
35
|
function: {
|
|
@@ -35,34 +39,84 @@ export interface ChatCompletionTool {
|
|
|
35
39
|
strict?: boolean | null;
|
|
36
40
|
};
|
|
37
41
|
}
|
|
42
|
+
/** An MCP server the gateway calls for the model during the turn. */
|
|
43
|
+
export interface McpServer {
|
|
44
|
+
/** Marks this `tools` entry as an MCP server. */
|
|
45
|
+
type: "mcp";
|
|
46
|
+
/** The server's label, unique in the request. */
|
|
47
|
+
server_label: string;
|
|
48
|
+
/** The server's https URL. */
|
|
49
|
+
server_url: string;
|
|
50
|
+
/**
|
|
51
|
+
* Headers for this server only.
|
|
52
|
+
* In page code every visitor can read them, `Authorization` included.
|
|
53
|
+
*/
|
|
54
|
+
headers?: Record<string, string>;
|
|
55
|
+
/** The only tools of the server the model may call. */
|
|
56
|
+
allowed_tools?: string[];
|
|
57
|
+
/** `streamable_http` by default, or `sse` for an older server. */
|
|
58
|
+
transport?: "streamable_http" | "sse";
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* One MCP tool call the gateway runs, streamed once before the call (`call`)
|
|
62
|
+
* and once after it (`result`). Fields this type does not name stay on the object.
|
|
63
|
+
*/
|
|
64
|
+
export interface ToolStep {
|
|
65
|
+
/** `call` before the tool runs, `result` after. */
|
|
66
|
+
type: "call" | "result";
|
|
67
|
+
/** The same on the `call` and the `result` of one tool call. */
|
|
68
|
+
id: string;
|
|
69
|
+
/** The label of the MCP server, as sent in `tools`. */
|
|
70
|
+
server_label: string;
|
|
71
|
+
/** The tool's name on its server. */
|
|
72
|
+
name: string;
|
|
73
|
+
/** The arguments as JSON text, on `call` only. */
|
|
74
|
+
arguments?: string;
|
|
75
|
+
/** True when the tool failed, on `result` only. */
|
|
76
|
+
is_error?: boolean;
|
|
77
|
+
/** How long the call took in milliseconds, on `result` only. */
|
|
78
|
+
duration_ms?: number;
|
|
79
|
+
/** The tool's result, cut when long, on `result` only. */
|
|
80
|
+
output?: string;
|
|
81
|
+
[key: string]: any;
|
|
82
|
+
}
|
|
38
83
|
/**
|
|
39
|
-
* OpenAI's chat completion parameters plus the Moss
|
|
40
|
-
* `indexes` and `
|
|
41
|
-
* including parameters this type does not name. The body always says `stream: true`.
|
|
84
|
+
* OpenAI's chat completion parameters plus the Moss options.
|
|
85
|
+
* `indexes`, `retrieve` and `cache` travel as headers, the rest in the body
|
|
86
|
+
* unchanged, including parameters this type does not name. The body always says `stream: true`.
|
|
42
87
|
*/
|
|
43
88
|
export interface ChatCompletionCreateParamsBase {
|
|
44
89
|
/** `moss` by default, Moss's own model. A vendor model such as `gpt-4o-mini` needs `apiKey`. */
|
|
45
90
|
model?: string;
|
|
46
91
|
messages: ChatCompletionMessageParam[];
|
|
47
92
|
stream?: boolean | null;
|
|
48
|
-
/**
|
|
93
|
+
/**
|
|
94
|
+
* Moss indexes to search, every index when left out and none when empty.
|
|
95
|
+
* Names travel in a single header, so each must be Latin-1 text with no comma.
|
|
96
|
+
*/
|
|
49
97
|
indexes?: string[];
|
|
50
98
|
/** False skips retrieval for this call. */
|
|
51
99
|
retrieve?: boolean;
|
|
100
|
+
/** False always asks the model instead of the gateway's reply cache. */
|
|
101
|
+
cache?: boolean;
|
|
52
102
|
temperature?: number | null;
|
|
53
103
|
top_p?: number | null;
|
|
54
104
|
max_tokens?: number | null;
|
|
55
105
|
max_completion_tokens?: number | null;
|
|
56
106
|
stop?: string | string[] | null;
|
|
57
107
|
seed?: number | null;
|
|
58
|
-
|
|
108
|
+
/** Functions your code runs, MCP servers the gateway calls, or any other tool object. */
|
|
109
|
+
tools?: (ChatCompletionTool | McpServer | {
|
|
59
110
|
type: string;
|
|
60
111
|
[key: string]: any;
|
|
61
112
|
})[];
|
|
113
|
+
/** Whether and which tool the model calls, such as `{ type: "function", function: { name } }`. */
|
|
62
114
|
tool_choice?: "none" | "auto" | "required" | {
|
|
63
115
|
type: string;
|
|
64
116
|
[key: string]: any;
|
|
65
117
|
};
|
|
118
|
+
/** False asks the model for at most one tool call per reply. */
|
|
119
|
+
parallel_tool_calls?: boolean | null;
|
|
66
120
|
response_format?: {
|
|
67
121
|
type: string;
|
|
68
122
|
[key: string]: any;
|
|
@@ -105,6 +159,11 @@ export interface MossInferenceOptions {
|
|
|
105
159
|
timeout?: number | null;
|
|
106
160
|
/** The longest wait for response headers or for more of the body. 120 000 by default. */
|
|
107
161
|
idleTimeout?: number | null;
|
|
162
|
+
/**
|
|
163
|
+
* Retries before the stream starts, 2 by default and 0 for none.
|
|
164
|
+
* A failed connection or a 408, 409, 429 or 5xx response is retried.
|
|
165
|
+
*/
|
|
166
|
+
maxRetries?: number;
|
|
108
167
|
/** Headers sent on every call. */
|
|
109
168
|
headers?: Record<string, string>;
|
|
110
169
|
}
|
|
@@ -118,16 +177,40 @@ export interface InferenceRequestOptions {
|
|
|
118
177
|
timeout?: number | null;
|
|
119
178
|
/** Replaces the client's `idleTimeout` for this call. */
|
|
120
179
|
idleTimeout?: number | null;
|
|
180
|
+
/** Replaces the client's `maxRetries` for this call. */
|
|
181
|
+
maxRetries?: number;
|
|
121
182
|
/** Headers for this call, over the client's. The SDK's own headers win over both. */
|
|
122
183
|
headers?: Record<string, string>;
|
|
123
184
|
}
|
|
124
|
-
/** Token counts for one call. */
|
|
185
|
+
/** Token counts for one call, with every field the gateway sent. */
|
|
125
186
|
export interface CompletionUsage {
|
|
126
187
|
prompt_tokens: number;
|
|
127
188
|
completion_tokens: number;
|
|
128
189
|
total_tokens: number;
|
|
190
|
+
/** Such as `reasoning_tokens`. */
|
|
191
|
+
completion_tokens_details?: Record<string, any>;
|
|
192
|
+
/** Such as `cached_tokens`. */
|
|
193
|
+
prompt_tokens_details?: Record<string, any>;
|
|
194
|
+
[key: string]: any;
|
|
129
195
|
}
|
|
130
|
-
/**
|
|
196
|
+
/** The log probability of one token, with the likeliest tokens in its place when asked for. */
|
|
197
|
+
export interface ChatCompletionTokenLogprob {
|
|
198
|
+
token: string;
|
|
199
|
+
logprob: number;
|
|
200
|
+
bytes: number[] | null;
|
|
201
|
+
top_logprobs: {
|
|
202
|
+
token: string;
|
|
203
|
+
logprob: number;
|
|
204
|
+
bytes: number[] | null;
|
|
205
|
+
}[];
|
|
206
|
+
[key: string]: any;
|
|
207
|
+
}
|
|
208
|
+
/** The log probabilities of a choice's tokens, for its text and for a refusal. */
|
|
209
|
+
export interface ChatCompletionLogprobs {
|
|
210
|
+
content: ChatCompletionTokenLogprob[] | null;
|
|
211
|
+
refusal: ChatCompletionTokenLogprob[] | null;
|
|
212
|
+
}
|
|
213
|
+
/** A piece of a tool call inside a streamed delta, with any fields beyond OpenAI's. */
|
|
131
214
|
export interface ChatCompletionChunkToolCall {
|
|
132
215
|
index: number;
|
|
133
216
|
id?: string;
|
|
@@ -136,6 +219,7 @@ export interface ChatCompletionChunkToolCall {
|
|
|
136
219
|
name?: string;
|
|
137
220
|
arguments?: string;
|
|
138
221
|
};
|
|
222
|
+
[key: string]: any;
|
|
139
223
|
}
|
|
140
224
|
/** What one chunk adds to a choice. */
|
|
141
225
|
export interface ChatCompletionChunkDelta {
|
|
@@ -147,6 +231,7 @@ export interface ChatCompletionChunkDelta {
|
|
|
147
231
|
export interface ChatCompletionChunkChoice {
|
|
148
232
|
index: number;
|
|
149
233
|
delta: ChatCompletionChunkDelta;
|
|
234
|
+
logprobs?: ChatCompletionLogprobs | null;
|
|
150
235
|
finish_reason: string | null;
|
|
151
236
|
}
|
|
152
237
|
/**
|
|
@@ -162,11 +247,16 @@ export interface ChatCompletionChunk {
|
|
|
162
247
|
model: string;
|
|
163
248
|
choices: ChatCompletionChunkChoice[];
|
|
164
249
|
usage?: CompletionUsage | null;
|
|
250
|
+
/** An MCP tool call the gateway runs, on a chunk whose one choice has an empty delta. */
|
|
251
|
+
moss_tool_step?: ToolStep;
|
|
165
252
|
}
|
|
166
|
-
/**
|
|
253
|
+
/**
|
|
254
|
+
* The reply the model built for one choice.
|
|
255
|
+
* Push it onto `messages` unchanged, then one `tool` message per tool call.
|
|
256
|
+
*/
|
|
167
257
|
export interface ChatCompletionMessage {
|
|
168
258
|
role: "assistant";
|
|
169
|
-
/** All text joined,
|
|
259
|
+
/** All text joined. Without text, null when the model called tools and empty otherwise. */
|
|
170
260
|
content: string | null;
|
|
171
261
|
/** Present only when the model called tools. */
|
|
172
262
|
tool_calls?: ChatCompletionMessageToolCall[];
|
|
@@ -175,6 +265,8 @@ export interface ChatCompletionMessage {
|
|
|
175
265
|
export interface ChatCompletionChoice {
|
|
176
266
|
index: number;
|
|
177
267
|
message: ChatCompletionMessage;
|
|
268
|
+
/** The tokens of every chunk joined in order, or null when no chunk had any. */
|
|
269
|
+
logprobs: ChatCompletionLogprobs | null;
|
|
178
270
|
finish_reason: string | null;
|
|
179
271
|
}
|
|
180
272
|
/** A whole reply, built from every chunk of the stream. */
|
|
@@ -185,4 +277,8 @@ export interface ChatCompletion {
|
|
|
185
277
|
model: string;
|
|
186
278
|
choices: ChatCompletionChoice[];
|
|
187
279
|
usage: CompletionUsage | null;
|
|
280
|
+
/** Every MCP tool step of the stream in order, present only when there is one. */
|
|
281
|
+
moss_tool_steps?: ToolStep[];
|
|
282
|
+
/** The `X-Moss-Request-Id` of the response. `JSON.stringify` leaves it out. */
|
|
283
|
+
readonly requestId?: string;
|
|
188
284
|
}
|