@moss-dev/moss-web 1.5.1 → 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 +234 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.js +4 -0
- package/dist/inference/error.d.ts +61 -0
- package/dist/inference/error.js +103 -0
- package/dist/inference/index.d.ts +35 -0
- package/dist/inference/index.js +289 -0
- package/dist/inference/stream.d.ts +41 -0
- package/dist/inference/stream.js +375 -0
- package/dist/inference/types.d.ts +284 -0
- package/dist/inference/types.js +3 -0
- package/package.json +3 -2
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,
|
|
@@ -244,6 +244,239 @@ error.
|
|
|
244
244
|
client.dispose();
|
|
245
245
|
```
|
|
246
246
|
|
|
247
|
+
## Inference
|
|
248
|
+
|
|
249
|
+
`MossInference` answers OpenAI's `chat.completions.create`, with the same
|
|
250
|
+
arguments and return shapes as in `@moss-js/moss`, through the Moss inference
|
|
251
|
+
gateway. The gateway searches the `indexes` you pass and adds what it finds to
|
|
252
|
+
the prompt, so code written for OpenAI swaps its client for `MossInference` and
|
|
253
|
+
adds `indexes`.
|
|
254
|
+
|
|
255
|
+
A project key in page code is visible to every visitor of the page. So a page
|
|
256
|
+
passes `null` for both credentials and points `baseURL` at a route on its own
|
|
257
|
+
server that adds them, as [the proxy route](#the-proxy-route) shows:
|
|
258
|
+
|
|
259
|
+
```typescript
|
|
260
|
+
import { MossInference } from "@moss-dev/moss-web";
|
|
261
|
+
|
|
262
|
+
const client = new MossInference(null, null, { baseURL: "/moss/v1" });
|
|
263
|
+
const answer = document.querySelector("#answer")!;
|
|
264
|
+
const messages = [{ role: "user" as const, content: "Do you ship to Canada?" }];
|
|
265
|
+
|
|
266
|
+
const stream = await client.chat.completions.create({
|
|
267
|
+
messages,
|
|
268
|
+
indexes: ["faq"],
|
|
269
|
+
stream: true,
|
|
270
|
+
});
|
|
271
|
+
document.querySelector("#stop")!.addEventListener("click", () => stream.controller.abort());
|
|
272
|
+
for await (const chunk of stream) {
|
|
273
|
+
answer.textContent += chunk.choices[0]?.delta.content ?? "";
|
|
274
|
+
}
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
`model` is optional and defaults to `"moss"`, Moss's own model. Without
|
|
278
|
+
`stream: true` the call reads the whole stream and returns one completion:
|
|
279
|
+
|
|
280
|
+
```typescript
|
|
281
|
+
const completion = await client.chat.completions.create(
|
|
282
|
+
{ messages, indexes: ["faq"] },
|
|
283
|
+
{ timeout: 30_000 },
|
|
284
|
+
);
|
|
285
|
+
answer.textContent = completion.choices[0].message.content;
|
|
286
|
+
```
|
|
287
|
+
|
|
288
|
+
`baseURL` takes only a path on the page's origin, such as `/moss/v1`. An
|
|
289
|
+
absolute URL, or one that starts with `//`, throws `InferenceError`. Each call
|
|
290
|
+
resolves the path against the page's URL, so a module that builds the client
|
|
291
|
+
during server rendering, where there is no page, works once it runs in the
|
|
292
|
+
browser. A call made with no http or https page rejects with `InferenceError`.
|
|
293
|
+
Without `baseURL` the client calls the Moss inference gateway,
|
|
294
|
+
`https://inference.moss.dev`, which needs the project id and key.
|
|
295
|
+
|
|
296
|
+
`apiKey` is optional: your own OpenAI, Anthropic or Google key, for a vendor
|
|
297
|
+
model such as `gpt-4o-mini`. `moss` ignores it, and a vendor model without one
|
|
298
|
+
is refused. Set it on the client, or pass it with one call, where it wins over
|
|
299
|
+
the client's:
|
|
300
|
+
|
|
301
|
+
```typescript
|
|
302
|
+
const keyed = new MossInference("your-project-id", "your-project-key", {
|
|
303
|
+
apiKey: "your-openai-key",
|
|
304
|
+
});
|
|
305
|
+
const reply = await keyed.chat.completions.create(
|
|
306
|
+
{ model: "gpt-4o-mini", messages },
|
|
307
|
+
{ apiKey: "your-other-openai-key" },
|
|
308
|
+
);
|
|
309
|
+
```
|
|
310
|
+
|
|
311
|
+
Like a project key, a provider key in page code is visible to every visitor, so
|
|
312
|
+
a page that uses [the proxy route](#the-proxy-route) leaves it to the route.
|
|
313
|
+
|
|
314
|
+
The other client options are `timeout` for each whole call (no limit by
|
|
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), `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`.
|
|
328
|
+
|
|
329
|
+
Leaving the `for await` loop early, or calling `stream.controller.abort()`,
|
|
330
|
+
closes the connection, stops the model and ends the loop quietly. An abort with
|
|
331
|
+
any other reason, such as the `TimeoutError` of `AbortSignal.timeout()`, throws
|
|
332
|
+
that reason. Without `stream: true`, an abort rejects with the signal's reason,
|
|
333
|
+
an `AbortError` for a plain `abort()`. Every other failure throws
|
|
334
|
+
`InferenceError` with `status` and `type`, including an error the model reports
|
|
335
|
+
mid-stream, a stream that ends early (`incomplete_stream`), a broken connection
|
|
336
|
+
(`connection_error`) and a timeout (`timeout`). It also carries the gateway's
|
|
337
|
+
`errorCode`, the response's `requestId` and, for a `429` or another error that
|
|
338
|
+
sends `Retry-After`, `retryAfter` in milliseconds. A call straight to the
|
|
339
|
+
gateway gets `requestId` but no `retryAfter`, since the gateway's CORS headers
|
|
340
|
+
do not expose `Retry-After` to the page. [The proxy route](#the-proxy-route)
|
|
341
|
+
passes both headers back to the page. A browser may report a stream cut off
|
|
342
|
+
mid-reply as a network error, which is a `connection_error`. The client does
|
|
343
|
+
not follow redirects: a redirect throws `InferenceError`, with no `status` in a
|
|
344
|
+
browser, which hides it.
|
|
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
|
+
|
|
412
|
+
### The proxy route
|
|
413
|
+
|
|
414
|
+
With `null` credentials the client sends no `Authorization` header, and an
|
|
415
|
+
`Authorization` header you pass in `headers`, such as the visitor's session
|
|
416
|
+
token, reaches your route unchanged. The route checks the visitor, decides which
|
|
417
|
+
indexes the call may search, adds the project credentials and forwards the call
|
|
418
|
+
to the gateway. In a server framework whose handlers take a `Request` and return
|
|
419
|
+
a `Response`, it can look like this:
|
|
420
|
+
|
|
421
|
+
```typescript
|
|
422
|
+
// Serves POST /moss/v1/chat/completions. Check the visitor's session first,
|
|
423
|
+
// since every call through this route spends your project's quota.
|
|
424
|
+
import type { McpServer } from "@moss-dev/moss-web";
|
|
425
|
+
|
|
426
|
+
const GATEWAY = "https://inference.moss.dev/v1/chat/completions";
|
|
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
|
+
};
|
|
434
|
+
const FORWARD = ["content-type", "accept"];
|
|
435
|
+
const REPLY = ["content-type", "retry-after", "x-moss-request-id"];
|
|
436
|
+
|
|
437
|
+
export async function POST(request: Request): Promise<Response> {
|
|
438
|
+
const { MOSS_PROJECT_ID, MOSS_PROJECT_KEY, CRM_TOKEN } = process.env;
|
|
439
|
+
const indexes = request.headers.get("x-moss-indexes")?.split(",") ?? INDEXES;
|
|
440
|
+
if (!indexes.every((name) => INDEXES.includes(name))) {
|
|
441
|
+
return Response.json({ detail: "This page cannot search that index." }, { status: 403 });
|
|
442
|
+
}
|
|
443
|
+
const headers = new Headers();
|
|
444
|
+
for (const name of FORWARD) {
|
|
445
|
+
const value = request.headers.get(name);
|
|
446
|
+
if (value !== null) headers.set(name, value);
|
|
447
|
+
}
|
|
448
|
+
headers.set("X-Moss-Indexes", indexes.join(","));
|
|
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];
|
|
454
|
+
const reply = await fetch(GATEWAY, {
|
|
455
|
+
method: "POST",
|
|
456
|
+
headers,
|
|
457
|
+
body: JSON.stringify(body),
|
|
458
|
+
signal: request.signal,
|
|
459
|
+
redirect: "manual",
|
|
460
|
+
});
|
|
461
|
+
const replyHeaders = [...reply.headers].filter(([name]) => REPLY.includes(name));
|
|
462
|
+
return new Response(reply.body, { status: reply.status, headers: replyHeaders });
|
|
463
|
+
}
|
|
464
|
+
```
|
|
465
|
+
|
|
466
|
+
The page's headers reach the gateway only when the route forwards them by name,
|
|
467
|
+
since every visitor can set them. Back to the page it passes `Content-Type`,
|
|
468
|
+
`Retry-After` and `X-Moss-Request-Id`, so an `InferenceError` there carries
|
|
469
|
+
`retryAfter` and `requestId`. The route refuses an index that is not in its
|
|
470
|
+
list, and always sends `X-Moss-Indexes`, because a call without it searches
|
|
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.
|
|
476
|
+
|
|
477
|
+
Passing the project id and key instead of `null`, without `baseURL`, sends them
|
|
478
|
+
from the page straight to the gateway, which suits prototypes and internal tools.
|
|
479
|
+
|
|
247
480
|
## Telemetry
|
|
248
481
|
|
|
249
482
|
The browser SDK always sends usage telemetry to the Moss cloud, and there is no
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
export { MossClient } from "./client.js";
|
|
2
2
|
export type { IAuthenticator, AuthToken } from "./auth/authenticator.interface.js";
|
|
3
3
|
export { ModelDeliveryError } from "./model-delivery.js";
|
|
4
|
+
export { MossInference } from "./inference/index.js";
|
|
5
|
+
export type { ChatCompletions } from "./inference/index.js";
|
|
6
|
+
export { ChatCompletionStream } from "./inference/stream.js";
|
|
7
|
+
export { InferenceError } from "./inference/error.js";
|
|
8
|
+
export type { InferenceErrorType } from "./inference/error.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";
|
|
4
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";
|
package/dist/index.js
CHANGED
|
@@ -1,2 +1,6 @@
|
|
|
1
1
|
export { MossClient } from "./client.js";
|
|
2
2
|
export { ModelDeliveryError } from "./model-delivery.js";
|
|
3
|
+
// Chat completions through the Moss inference gateway, in OpenAI's shape
|
|
4
|
+
export { MossInference } from "./inference/index.js";
|
|
5
|
+
export { ChatCompletionStream } from "./inference/stream.js";
|
|
6
|
+
export { InferenceError } from "./inference/error.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
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" | "capacity" | "mcp_error" | "model_error" | "server_error" | "connection_error" | "timeout" | "incomplete_stream" | (string & {});
|
|
3
|
+
/**
|
|
4
|
+
* The error every inference call throws, before or during the stream.
|
|
5
|
+
* Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
|
|
6
|
+
* A caller's abort rejects with the signal's reason, or ends a stream quietly on an `AbortError`.
|
|
7
|
+
*/
|
|
8
|
+
export declare class InferenceError extends Error {
|
|
9
|
+
/** The HTTP status of a rejected request. Undefined for transport and stream failures. */
|
|
10
|
+
readonly status: number | undefined;
|
|
11
|
+
/** The gateway's `error.type`, or one derived from the status or the failure. */
|
|
12
|
+
readonly type: InferenceErrorType;
|
|
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
|
+
*/
|
|
21
|
+
readonly errorCode?: string;
|
|
22
|
+
/** The `X-Moss-Request-Id` of the response. Undefined when the call failed before one arrived. */
|
|
23
|
+
readonly requestId?: string;
|
|
24
|
+
/**
|
|
25
|
+
* The `Retry-After` of an error response in milliseconds, when it gives whole seconds.
|
|
26
|
+
* A direct gateway call gets none, since the gateway's CORS headers do not expose `Retry-After`.
|
|
27
|
+
*/
|
|
28
|
+
readonly retryAfter?: number;
|
|
29
|
+
constructor(message: string, init: {
|
|
30
|
+
type: InferenceErrorType;
|
|
31
|
+
status?: number;
|
|
32
|
+
errorCode?: string;
|
|
33
|
+
requestId?: string;
|
|
34
|
+
retryAfter?: number;
|
|
35
|
+
cause?: unknown;
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
/** What every {@link InferenceError} of a call takes from its response. */
|
|
39
|
+
export interface ResponseFields {
|
|
40
|
+
requestId?: string;
|
|
41
|
+
retryAfter?: number;
|
|
42
|
+
/** Set once the stream carries an MCP tool step. */
|
|
43
|
+
errorCode?: "failed_after_tool_call";
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* The request id of any response, and for an error response
|
|
47
|
+
* the `Retry-After` in milliseconds when the header holds delta-seconds.
|
|
48
|
+
*/
|
|
49
|
+
export declare function responseFields(response: Response): ResponseFields;
|
|
50
|
+
/**
|
|
51
|
+
* The gateway's `error.code` as text: a string as sent, a safe integer in decimal.
|
|
52
|
+
* A larger integer gives none, since `JSON.parse` can change its digits.
|
|
53
|
+
*/
|
|
54
|
+
export declare function codeText(code: unknown): string | undefined;
|
|
55
|
+
/** The error for a fetch or body read that failed in transport, a `timeout` or a `connection_error`. */
|
|
56
|
+
export declare function transportError(error: unknown, message: string, fields?: ResponseFields): InferenceError;
|
|
57
|
+
/**
|
|
58
|
+
* Builds the error for a non-2xx response from its status and body text.
|
|
59
|
+
* A body that is not JSON gives the message, and an empty one the status line.
|
|
60
|
+
*/
|
|
61
|
+
export declare function errorFromResponse(response: Response, text: string): InferenceError;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The error every inference call throws, before or during the stream.
|
|
3
|
+
* Arguments the SDK rejects before sending carry `invalid_request_error` and no status.
|
|
4
|
+
* A caller's abort rejects with the signal's reason, or ends a stream quietly on an `AbortError`.
|
|
5
|
+
*/
|
|
6
|
+
export class InferenceError extends Error {
|
|
7
|
+
constructor(message, init) {
|
|
8
|
+
super(message);
|
|
9
|
+
this.name = "InferenceError";
|
|
10
|
+
this.type = init.type;
|
|
11
|
+
this.status = init.status;
|
|
12
|
+
this.errorCode = init.errorCode;
|
|
13
|
+
this.requestId = init.requestId;
|
|
14
|
+
this.retryAfter = init.retryAfter;
|
|
15
|
+
if (init.cause !== undefined) {
|
|
16
|
+
Object.defineProperty(this, "cause", {
|
|
17
|
+
value: init.cause,
|
|
18
|
+
writable: true,
|
|
19
|
+
configurable: true,
|
|
20
|
+
});
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
/**
|
|
25
|
+
* The request id of any response, and for an error response
|
|
26
|
+
* the `Retry-After` in milliseconds when the header holds delta-seconds.
|
|
27
|
+
*/
|
|
28
|
+
export function responseFields(response) {
|
|
29
|
+
const retry = response.ok ? null : response.headers.get("Retry-After");
|
|
30
|
+
return {
|
|
31
|
+
requestId: response.headers.get("X-Moss-Request-Id") || undefined,
|
|
32
|
+
retryAfter: retry !== null && /^\d+$/.test(retry) ? Number(retry) * 1000 : undefined,
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
/**
|
|
36
|
+
* The gateway's `error.code` as text: a string as sent, a safe integer in decimal.
|
|
37
|
+
* A larger integer gives none, since `JSON.parse` can change its digits.
|
|
38
|
+
*/
|
|
39
|
+
export function codeText(code) {
|
|
40
|
+
if (typeof code === "string")
|
|
41
|
+
return code;
|
|
42
|
+
return Number.isSafeInteger(code) ? String(code) : undefined;
|
|
43
|
+
}
|
|
44
|
+
const TYPE_BY_STATUS = {
|
|
45
|
+
401: "authentication_error",
|
|
46
|
+
403: "permission_error",
|
|
47
|
+
404: "not_found_error",
|
|
48
|
+
429: "rate_limit_error",
|
|
49
|
+
};
|
|
50
|
+
/** The longest message a body that is not JSON gives, in characters. */
|
|
51
|
+
const MAX_BODY_MESSAGE = 300;
|
|
52
|
+
/** The body with its whitespace collapsed, cut to {@link MAX_BODY_MESSAGE} characters. */
|
|
53
|
+
function bodyMessage(text) {
|
|
54
|
+
const chars = Array.from(text.replace(/\s+/g, " ").trim());
|
|
55
|
+
if (chars.length <= MAX_BODY_MESSAGE)
|
|
56
|
+
return chars.join("") || undefined;
|
|
57
|
+
return `${chars.slice(0, MAX_BODY_MESSAGE - 3).join("")}...`;
|
|
58
|
+
}
|
|
59
|
+
/** undici's codes for the time limits of Node's fetch, including its 300 s limits on silence. */
|
|
60
|
+
const TIMEOUT_CODES = new Set([
|
|
61
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
62
|
+
"UND_ERR_HEADERS_TIMEOUT",
|
|
63
|
+
"UND_ERR_BODY_TIMEOUT",
|
|
64
|
+
]);
|
|
65
|
+
/** The error for a fetch or body read that failed in transport, a `timeout` or a `connection_error`. */
|
|
66
|
+
export function transportError(error, message, fields = {}) {
|
|
67
|
+
const cause = error?.cause;
|
|
68
|
+
const detail = typeof cause?.message === "string" ? cause.message : String(error);
|
|
69
|
+
const type = TIMEOUT_CODES.has(cause?.code) ? "timeout" : "connection_error";
|
|
70
|
+
return new InferenceError(`${message}: ${detail}`, { type, cause: error, ...fields });
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* Builds the error for a non-2xx response from its status and body text.
|
|
74
|
+
* A body that is not JSON gives the message, and an empty one the status line.
|
|
75
|
+
*/
|
|
76
|
+
export function errorFromResponse(response, text) {
|
|
77
|
+
let body;
|
|
78
|
+
let message = `HTTP ${response.status}${response.statusText ? ` ${response.statusText}` : ""}`;
|
|
79
|
+
try {
|
|
80
|
+
body = JSON.parse(text);
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
message = bodyMessage(text) ?? message;
|
|
84
|
+
}
|
|
85
|
+
const { error, detail } = (body ?? {});
|
|
86
|
+
if (typeof error?.message === "string")
|
|
87
|
+
message = error.message;
|
|
88
|
+
else if (typeof detail === "string")
|
|
89
|
+
message = detail;
|
|
90
|
+
else if (detail !== undefined)
|
|
91
|
+
message = JSON.stringify(detail);
|
|
92
|
+
return new InferenceError(message, {
|
|
93
|
+
type: typeof error?.type === "string"
|
|
94
|
+
? error.type
|
|
95
|
+
: (TYPE_BY_STATUS[response.status] ??
|
|
96
|
+
(response.status >= 400 && response.status < 500
|
|
97
|
+
? "invalid_request_error"
|
|
98
|
+
: "server_error")),
|
|
99
|
+
status: response.status,
|
|
100
|
+
errorCode: codeText(error?.code),
|
|
101
|
+
...responseFields(response),
|
|
102
|
+
});
|
|
103
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { ChatCompletionStream } from "./stream.js";
|
|
2
|
+
import type { ChatCompletion, ChatCompletionCreateParams, ChatCompletionCreateParamsNonStreaming, ChatCompletionCreateParamsStreaming, InferenceRequestOptions, MossInferenceOptions } from "./types.js";
|
|
3
|
+
/** The `chat.completions` namespace of a {@link MossInference} client, shaped like OpenAI's. */
|
|
4
|
+
export interface ChatCompletions {
|
|
5
|
+
/**
|
|
6
|
+
* Sends a chat completion through the Moss inference gateway.
|
|
7
|
+
*
|
|
8
|
+
* The gateway searches `indexes` and adds what it finds to the prompt.
|
|
9
|
+
* Failures reject with {@link InferenceError}. With `stream: true` this
|
|
10
|
+
* resolves to a {@link ChatCompletionStream} once the gateway accepts the request,
|
|
11
|
+
* and otherwise to one {@link ChatCompletion} built from the whole stream.
|
|
12
|
+
*/
|
|
13
|
+
create(params: ChatCompletionCreateParamsStreaming, options?: InferenceRequestOptions): Promise<ChatCompletionStream>;
|
|
14
|
+
create(params: ChatCompletionCreateParamsNonStreaming, options?: InferenceRequestOptions): Promise<ChatCompletion>;
|
|
15
|
+
create(params: ChatCompletionCreateParams, options?: InferenceRequestOptions): Promise<ChatCompletionStream | ChatCompletion>;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
19
|
+
*
|
|
20
|
+
* The constructor throws {@link InferenceError} with `invalid_request_error`
|
|
21
|
+
* when the credentials, provider key, headers, timeouts or `baseURL` are wrong.
|
|
22
|
+
* A call through a `baseURL` path rejects the same way without an http or https page.
|
|
23
|
+
* Null credentials send no `Authorization` header, for a route on your server that adds it.
|
|
24
|
+
*/
|
|
25
|
+
export declare class MossInference {
|
|
26
|
+
#private;
|
|
27
|
+
/** OpenAI's `chat.completions`, answered by the Moss inference gateway. */
|
|
28
|
+
readonly chat: {
|
|
29
|
+
readonly completions: ChatCompletions;
|
|
30
|
+
};
|
|
31
|
+
constructor(projectId: string, projectKey: string, options?: MossInferenceOptions);
|
|
32
|
+
constructor(projectId: null, projectKey: null, options: MossInferenceOptions & {
|
|
33
|
+
baseURL: string;
|
|
34
|
+
});
|
|
35
|
+
}
|