@moss-dev/moss-web 1.7.0 → 1.8.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 +95 -71
- package/dist/index.d.ts +3 -3
- package/dist/index.js +2 -2
- package/dist/inference/error.d.ts +3 -3
- package/dist/inference/index.d.ts +12 -14
- package/dist/inference/index.js +7 -9
- package/dist/inference/stream.d.ts +17 -15
- package/dist/inference/stream.js +75 -176
- package/dist/inference/types.d.ts +171 -159
- 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.8.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,
|
|
@@ -246,11 +246,11 @@ client.dispose();
|
|
|
246
246
|
|
|
247
247
|
## Inference
|
|
248
248
|
|
|
249
|
-
`MossInference` answers OpenAI's `
|
|
250
|
-
|
|
251
|
-
gateway. The gateway searches the `indexes` you pass and adds
|
|
252
|
-
the prompt, so code written for OpenAI swaps its client for
|
|
253
|
-
adds `indexes`.
|
|
249
|
+
`MossInference` answers OpenAI's `responses.create`, with the arguments and
|
|
250
|
+
return shapes of OpenAI's Responses API, as in `@moss-js/moss`, through the
|
|
251
|
+
Moss inference gateway. The gateway searches the `indexes` you pass and adds
|
|
252
|
+
what it finds to the prompt, so code written for OpenAI swaps its client for
|
|
253
|
+
`MossInference` and adds `indexes`.
|
|
254
254
|
|
|
255
255
|
A project key in page code is visible to every visitor of the page. So a page
|
|
256
256
|
passes `null` for both credentials and points `baseURL` at a route on its own
|
|
@@ -261,30 +261,39 @@ import { MossInference } from "@moss-dev/moss-web";
|
|
|
261
261
|
|
|
262
262
|
const client = new MossInference(null, null, { baseURL: "/moss/v1" });
|
|
263
263
|
const answer = document.querySelector("#answer")!;
|
|
264
|
-
const messages = [{ role: "user" as const, content: "Do you ship to Canada?" }];
|
|
265
264
|
|
|
266
|
-
const stream = await client.
|
|
267
|
-
|
|
265
|
+
const stream = await client.responses.create({
|
|
266
|
+
input: "Do you ship to Canada?",
|
|
268
267
|
indexes: ["faq"],
|
|
269
268
|
stream: true,
|
|
270
269
|
});
|
|
271
270
|
document.querySelector("#stop")!.addEventListener("click", () => stream.controller.abort());
|
|
272
|
-
for await (const
|
|
273
|
-
answer.textContent +=
|
|
271
|
+
for await (const event of stream) {
|
|
272
|
+
if (event.type === "response.output_text.delta") answer.textContent += event.delta ?? "";
|
|
274
273
|
}
|
|
275
274
|
```
|
|
276
275
|
|
|
277
276
|
`model` is optional and defaults to `"moss"`, Moss's own model. Without
|
|
278
|
-
`stream: true` the call reads the whole stream and returns
|
|
277
|
+
`stream: true` the call reads the whole stream and returns the `Response` of its
|
|
278
|
+
last event, whose `output_text` joins the text of its messages:
|
|
279
279
|
|
|
280
280
|
```typescript
|
|
281
|
-
const
|
|
282
|
-
{
|
|
281
|
+
const response = await client.responses.create(
|
|
282
|
+
{ instructions: "Answer in one sentence.", input: "Do you ship to Canada?", indexes: ["faq"] },
|
|
283
283
|
{ timeout: 30_000 },
|
|
284
284
|
);
|
|
285
|
-
answer.textContent =
|
|
285
|
+
answer.textContent = response.output_text;
|
|
286
286
|
```
|
|
287
287
|
|
|
288
|
+
`input` is a string, or the conversation so far as a list of items: messages
|
|
289
|
+
such as `{ role: "user", content: "Hi" }`, and the `output` items of earlier
|
|
290
|
+
responses. Moss stores nothing, so send the whole conversation each time.
|
|
291
|
+
`store` is ignored, and `previous_response_id`, `background`, `include` and
|
|
292
|
+
OpenAI's built-in tools, such as `web_search`, are refused with
|
|
293
|
+
`invalid_request_error` and the `errorCode` `unsupported_parameter`. Other
|
|
294
|
+
OpenAI parameters, such as `temperature`, `text: { format }` for structured
|
|
295
|
+
output or `reasoning: { effort: "low" }`, reach the gateway unchanged.
|
|
296
|
+
|
|
288
297
|
`baseURL` takes only a path on the page's origin, such as `/moss/v1`. An
|
|
289
298
|
absolute URL, or one that starts with `//`, throws `InferenceError`. Each call
|
|
290
299
|
resolves the path against the page's URL, so a module that builds the client
|
|
@@ -302,8 +311,8 @@ the client's:
|
|
|
302
311
|
const keyed = new MossInference("your-project-id", "your-project-key", {
|
|
303
312
|
apiKey: "your-openai-key",
|
|
304
313
|
});
|
|
305
|
-
const reply = await keyed.
|
|
306
|
-
{ model: "gpt-4o-mini",
|
|
314
|
+
const reply = await keyed.responses.create(
|
|
315
|
+
{ model: "gpt-4o-mini", input: "Hi" },
|
|
307
316
|
{ apiKey: "your-other-openai-key" },
|
|
308
317
|
);
|
|
309
318
|
```
|
|
@@ -323,79 +332,94 @@ starts, after a `Retry-After` of up to 60 s, else a backoff of 0.5 s doubling
|
|
|
323
332
|
up to 8 s, within `timeout`. `retrieve: false` or `indexes: []` skips the
|
|
324
333
|
search, and leaving `indexes` out searches every index. Moss can answer an
|
|
325
334
|
identical request from its reply cache; `cache: false` always asks the model.
|
|
326
|
-
`stream.requestId` and a
|
|
335
|
+
`stream.requestId` and a response's `requestId`, which `JSON.stringify` leaves
|
|
327
336
|
out, hold the response's `X-Moss-Request-Id`.
|
|
328
337
|
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
`
|
|
335
|
-
|
|
336
|
-
(
|
|
337
|
-
`
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
browser
|
|
338
|
+
A stream ends after `response.completed`, or after `response.incomplete` for a
|
|
339
|
+
response cut by `max_output_tokens`, whose `status` is then `incomplete`, with
|
|
340
|
+
the reason in `incomplete_details`. Leaving the `for await` loop early, or
|
|
341
|
+
calling `stream.controller.abort()`, closes the connection, stops the model and
|
|
342
|
+
ends the loop quietly. An abort with any other reason, such as the
|
|
343
|
+
`TimeoutError` of `AbortSignal.timeout()`, throws that reason. Without
|
|
344
|
+
`stream: true`, an abort rejects with the signal's reason, an `AbortError` for a
|
|
345
|
+
plain `abort()`. Every other failure throws `InferenceError` with `status` and
|
|
346
|
+
`type`, including a `response.failed` event, a stream that ends before its last
|
|
347
|
+
event (`incomplete_stream`), a broken connection (`connection_error`) and a
|
|
348
|
+
timeout (`timeout`). It also carries the gateway's `errorCode`, the response's
|
|
349
|
+
`requestId` and, for a `429` or another error that sends `Retry-After`,
|
|
350
|
+
`retryAfter` in milliseconds. A call straight to the gateway gets `requestId`
|
|
351
|
+
but no `retryAfter`, since the gateway's CORS headers do not expose
|
|
352
|
+
`Retry-After` to the page. [The proxy route](#the-proxy-route) passes both
|
|
353
|
+
headers back to the page. A browser may report a stream cut off mid-response as
|
|
354
|
+
a network error, which is a `connection_error`. The client does not follow
|
|
355
|
+
redirects: a redirect throws `InferenceError`, with no `status` in a browser,
|
|
356
|
+
which hides it.
|
|
345
357
|
|
|
346
358
|
### Tool calls
|
|
347
359
|
|
|
348
|
-
`tools`, `tool_choice` and `parallel_tool_calls` take
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
360
|
+
`tools`, `tool_choice` and `parallel_tool_calls` take the shapes of OpenAI's
|
|
361
|
+
Responses API, where a function tool is flat, and your code runs each call. Each
|
|
362
|
+
call comes as a `function_call` item of `output`, which keeps fields beyond
|
|
363
|
+
OpenAI's, such as Gemini's `extra_content`, which the model needs back. After
|
|
364
|
+
streaming the text, `finalResponse()` gives the whole response. Push its
|
|
365
|
+
`output` items onto `input` as they are, add one `function_call_output` item
|
|
366
|
+
per call, and ask again:
|
|
353
367
|
|
|
354
368
|
```typescript
|
|
355
|
-
import type {
|
|
369
|
+
import type { FunctionTool, ResponseInputItem } from "@moss-dev/moss-web";
|
|
356
370
|
|
|
357
|
-
const tools:
|
|
371
|
+
const tools: FunctionTool[] = [
|
|
358
372
|
{
|
|
359
373
|
type: "function",
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
|
|
363
|
-
},
|
|
374
|
+
name: "order_status",
|
|
375
|
+
parameters: { type: "object", properties: { id: { type: "string" } }, required: ["id"] },
|
|
364
376
|
},
|
|
365
377
|
];
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
const
|
|
373
|
-
|
|
378
|
+
const input: ResponseInputItem[] = [{ role: "user", content: "Where is order A1?" }];
|
|
379
|
+
for (;;) {
|
|
380
|
+
const stream = await client.responses.create({ input, tools, stream: true });
|
|
381
|
+
for await (const event of stream) {
|
|
382
|
+
if (event.type === "response.output_text.delta") answer.textContent += event.delta ?? "";
|
|
383
|
+
}
|
|
384
|
+
const { output } = await stream.finalResponse();
|
|
385
|
+
input.push(...output);
|
|
386
|
+
const calls = output.filter((item) => item.type === "function_call");
|
|
387
|
+
if (calls.length === 0) break;
|
|
388
|
+
for (const call of calls) {
|
|
389
|
+
const status = await orderStatus(JSON.parse(call.arguments).id);
|
|
390
|
+
input.push({ type: "function_call_output", call_id: call.call_id, output: status });
|
|
391
|
+
}
|
|
374
392
|
}
|
|
375
|
-
const reply = await client.chat.completions.create({ messages: history, tools });
|
|
376
393
|
```
|
|
377
394
|
|
|
395
|
+
`finalResponse()` reads what the loop has not read. If the stream was closed
|
|
396
|
+
before its last event, it rejects, so it never returns part of a response.
|
|
397
|
+
|
|
378
398
|
### MCP servers
|
|
379
399
|
|
|
380
400
|
A `tools` entry of type `mcp`, typed `McpServer`, asks the gateway to call that
|
|
381
|
-
MCP server for the model during the
|
|
401
|
+
MCP server for the model during the response. The server's `headers` hold its
|
|
382
402
|
credentials, and like a project key they are visible to every visitor in page
|
|
383
403
|
code, so [the proxy route](#the-proxy-route) adds the entry and the page sends
|
|
384
|
-
none.
|
|
385
|
-
|
|
404
|
+
none. Each call comes as an `mcp_call` item, in `response.output_item.added`
|
|
405
|
+
when it starts and `response.output_item.done` when it ends:
|
|
386
406
|
|
|
387
407
|
```typescript
|
|
388
|
-
const stream = await client.
|
|
389
|
-
for await (const
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
408
|
+
const stream = await client.responses.create({ input: "Where is order A1?", stream: true });
|
|
409
|
+
for await (const event of stream) {
|
|
410
|
+
if (event.type === "response.output_item.done" && event.item?.type === "mcp_call") {
|
|
411
|
+
console.log(event.item.name, event.item.status, event.item.duration_ms);
|
|
412
|
+
} else if (event.type === "response.output_text.delta") {
|
|
413
|
+
answer.textContent += event.delta ?? "";
|
|
414
|
+
}
|
|
393
415
|
}
|
|
394
|
-
const { moss_tool_steps } = await stream.finalChatCompletion();
|
|
395
|
-
console.log(moss_tool_steps?.map((step) => `${step.type} ${step.name}`));
|
|
396
416
|
```
|
|
397
417
|
|
|
398
|
-
|
|
418
|
+
An `mcp_call` item has the `server_label`, `name` and `arguments` of the call,
|
|
419
|
+
and once it ended its `status`, `output` or `error`, and `duration_ms`. Without
|
|
420
|
+
`stream: true`, the same items are in the response's `output`, in order.
|
|
421
|
+
Sending the `output` items back in `input`, `mcp_call` items included, gives the
|
|
422
|
+
model the earlier tool results. A response with tools can run for a few minutes.
|
|
399
423
|
|
|
400
424
|
| `status` | `type` | `errorCode` | When |
|
|
401
425
|
| --- | --- | --- | --- |
|
|
@@ -404,10 +428,10 @@ A turn with tools can run for a few minutes.
|
|
|
404
428
|
| 400, 424 | `mcp_error` | `mcp_server_error` | The URL was refused, or the server failed |
|
|
405
429
|
| 400 | `invalid_request_error` | (none) | A bad `tools` entry, or a label or tool name used twice |
|
|
406
430
|
|
|
407
|
-
After
|
|
408
|
-
the SDK never retries. Nor does it retry any stream that fails after it
|
|
409
|
-
The tool may have changed data, and so may a call you abort or time out
|
|
410
|
-
|
|
431
|
+
After an `mcp_call` item every failure has `errorCode` `failed_after_tool_call`,
|
|
432
|
+
and the SDK never retries. Nor does it retry any stream that fails after it
|
|
433
|
+
started. The tool may have changed data, and so may a call you abort or time out
|
|
434
|
+
after such an item, so do not replay such a call blindly.
|
|
411
435
|
|
|
412
436
|
### The proxy route
|
|
413
437
|
|
|
@@ -419,11 +443,11 @@ to the gateway. In a server framework whose handlers take a `Request` and return
|
|
|
419
443
|
a `Response`, it can look like this:
|
|
420
444
|
|
|
421
445
|
```typescript
|
|
422
|
-
// Serves POST /moss/v1/
|
|
446
|
+
// Serves POST /moss/v1/responses. Check the visitor's session first,
|
|
423
447
|
// since every call through this route spends your project's quota.
|
|
424
448
|
import type { McpServer } from "@moss-dev/moss-web";
|
|
425
449
|
|
|
426
|
-
const GATEWAY = "https://inference.moss.dev/v1/
|
|
450
|
+
const GATEWAY = "https://inference.moss.dev/v1/responses";
|
|
427
451
|
const INDEXES = ["faq"];
|
|
428
452
|
const CRM: McpServer = {
|
|
429
453
|
type: "mcp",
|
package/dist/index.d.ts
CHANGED
|
@@ -2,9 +2,9 @@ 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
4
|
export { MossInference } from "./inference/index.js";
|
|
5
|
-
export type {
|
|
6
|
-
export {
|
|
5
|
+
export type { Responses } from "./inference/index.js";
|
|
6
|
+
export { ResponseStream } from "./inference/stream.js";
|
|
7
7
|
export { InferenceError } from "./inference/error.js";
|
|
8
8
|
export type { InferenceErrorType } from "./inference/error.js";
|
|
9
|
-
export type {
|
|
9
|
+
export type { EasyInputMessage, FunctionCallOutput, FunctionTool, InferenceRequestOptions, McpCall, McpServer, MossInferenceOptions, Response, ResponseCreateParams, ResponseCreateParamsBase, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming, ResponseFunctionToolCall, ResponseInputItem, ResponseOutputItem, ResponseReasoningItem, ResponseOutputMessage, ResponseOutputText, ResponseStreamEvent, ResponseUsage, } 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";
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
export { MossClient } from "./client.js";
|
|
2
2
|
export { ModelDeliveryError } from "./model-delivery.js";
|
|
3
|
-
//
|
|
3
|
+
// Responses through the Moss inference gateway, in the shape of OpenAI's Responses API
|
|
4
4
|
export { MossInference } from "./inference/index.js";
|
|
5
|
-
export {
|
|
5
|
+
export { ResponseStream } from "./inference/stream.js";
|
|
6
6
|
export { InferenceError } from "./inference/error.js";
|
|
@@ -13,9 +13,9 @@ export declare class InferenceError extends Error {
|
|
|
13
13
|
/**
|
|
14
14
|
* The gateway's `error.code`, a string or a safe integer in decimal. Undefined otherwise.
|
|
15
15
|
*
|
|
16
|
-
* `failed_after_tool_call` once the stream carried an
|
|
16
|
+
* `failed_after_tool_call` once the stream carried an `mcp_call` item.
|
|
17
17
|
* The tool may have changed data, so do not replay the call blindly.
|
|
18
|
-
* The same holds for a call you abort after
|
|
18
|
+
* The same holds for a call you abort after such an item, which has no such code,
|
|
19
19
|
* as with `stream.controller.abort()` or a signal such as `AbortSignal.timeout()`.
|
|
20
20
|
*/
|
|
21
21
|
readonly errorCode?: string;
|
|
@@ -39,7 +39,7 @@ export declare class InferenceError extends Error {
|
|
|
39
39
|
export interface ResponseFields {
|
|
40
40
|
requestId?: string;
|
|
41
41
|
retryAfter?: number;
|
|
42
|
-
/** Set once the stream carries an
|
|
42
|
+
/** Set once the stream carries an `mcp_call` item. */
|
|
43
43
|
errorCode?: "failed_after_tool_call";
|
|
44
44
|
}
|
|
45
45
|
/**
|
|
@@ -1,18 +1,18 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import type {
|
|
3
|
-
/** The `
|
|
4
|
-
export interface
|
|
1
|
+
import { ResponseStream } from "./stream.js";
|
|
2
|
+
import type { InferenceRequestOptions, MossInferenceOptions, Response as MossResponse, ResponseCreateParams, ResponseCreateParamsNonStreaming, ResponseCreateParamsStreaming } from "./types.js";
|
|
3
|
+
/** The `responses` namespace of a {@link MossInference} client, shaped like OpenAI's. */
|
|
4
|
+
export interface Responses {
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
6
|
+
* Creates a response through the Moss inference gateway.
|
|
7
7
|
*
|
|
8
8
|
* The gateway searches `indexes` and adds what it finds to the prompt.
|
|
9
9
|
* Failures reject with {@link InferenceError}. With `stream: true` this
|
|
10
|
-
* resolves to a {@link
|
|
11
|
-
* and otherwise to
|
|
10
|
+
* resolves to a {@link ResponseStream} once the gateway accepts the request,
|
|
11
|
+
* and otherwise to the `Response` of the stream's last event.
|
|
12
12
|
*/
|
|
13
|
-
create(params:
|
|
14
|
-
create(params:
|
|
15
|
-
create(params:
|
|
13
|
+
create(params: ResponseCreateParamsStreaming, options?: InferenceRequestOptions): Promise<ResponseStream>;
|
|
14
|
+
create(params: ResponseCreateParamsNonStreaming, options?: InferenceRequestOptions): Promise<MossResponse>;
|
|
15
|
+
create(params: ResponseCreateParams, options?: InferenceRequestOptions): Promise<ResponseStream | MossResponse>;
|
|
16
16
|
}
|
|
17
17
|
/**
|
|
18
18
|
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
@@ -24,10 +24,8 @@ export interface ChatCompletions {
|
|
|
24
24
|
*/
|
|
25
25
|
export declare class MossInference {
|
|
26
26
|
#private;
|
|
27
|
-
/** OpenAI's `
|
|
28
|
-
readonly
|
|
29
|
-
readonly completions: ChatCompletions;
|
|
30
|
-
};
|
|
27
|
+
/** OpenAI's `responses`, answered by the Moss inference gateway. */
|
|
28
|
+
readonly responses: Responses;
|
|
31
29
|
constructor(projectId: string, projectKey: string, options?: MossInferenceOptions);
|
|
32
30
|
constructor(projectId: null, projectKey: null, options: MossInferenceOptions & {
|
|
33
31
|
baseURL: string;
|
package/dist/inference/index.js
CHANGED
|
@@ -11,7 +11,7 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
|
|
|
11
11
|
};
|
|
12
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 {
|
|
14
|
+
import { ResponseStream, 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";
|
|
@@ -104,7 +104,7 @@ function proxyPath(baseURL) {
|
|
|
104
104
|
throw invalid("baseURL must not hold a query or a fragment.");
|
|
105
105
|
return baseURL;
|
|
106
106
|
}
|
|
107
|
-
/** The
|
|
107
|
+
/** The Responses URL under `path` on the origin of the current page. */
|
|
108
108
|
function onPage(path) {
|
|
109
109
|
let url;
|
|
110
110
|
try {
|
|
@@ -115,7 +115,7 @@ function onPage(path) {
|
|
|
115
115
|
}
|
|
116
116
|
if (!url || !["http:", "https:"].includes(url.protocol))
|
|
117
117
|
throw invalid("baseURL is a path on the page's origin, so it needs an http or https page.");
|
|
118
|
-
return `${url.origin}${url.pathname.replace(/\/+$/, "")}/
|
|
118
|
+
return `${url.origin}${url.pathname.replace(/\/+$/, "")}/responses`;
|
|
119
119
|
}
|
|
120
120
|
/**
|
|
121
121
|
* A drop-in for OpenAI's client that answers from your Moss indexes.
|
|
@@ -160,13 +160,11 @@ export class MossInference {
|
|
|
160
160
|
__classPrivateFieldSet(this, _MossInference_headers, headersOf(options.headers), "f");
|
|
161
161
|
__classPrivateFieldSet(this, _MossInference_apiKey, options.apiKey == null ? undefined : credential("apiKey", options.apiKey), "f");
|
|
162
162
|
const create = (params, call) => __classPrivateFieldGet(this, _MossInference_instances, "m", _MossInference_create).call(this, params, call);
|
|
163
|
-
this.
|
|
164
|
-
completions: Object.freeze({ create: create }),
|
|
165
|
-
});
|
|
163
|
+
this.responses = Object.freeze({ create: create });
|
|
166
164
|
}
|
|
167
165
|
}
|
|
168
166
|
_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 = {}) {
|
|
169
|
-
const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/
|
|
167
|
+
const url = __classPrivateFieldGet(this, _MossInference_path, "f") === undefined ? `${DEFAULT_URL}/responses` : onPage(__classPrivateFieldGet(this, _MossInference_path, "f"));
|
|
170
168
|
const { indexes, retrieve, cache, model = DEFAULT_MODEL, ...body } = params;
|
|
171
169
|
if (body.apiKey !== undefined || body.api_key !== undefined)
|
|
172
170
|
throw invalid("Pass the provider key as apiKey in the options of create, not in params.");
|
|
@@ -284,6 +282,6 @@ _MossInference_path = new WeakMap(), _MossInference_headers = new WeakMap(), _Mo
|
|
|
284
282
|
throw controller.signal.reason;
|
|
285
283
|
throw errorFromResponse(response, text);
|
|
286
284
|
}
|
|
287
|
-
const stream = new
|
|
288
|
-
return params.stream ? stream : stream.
|
|
285
|
+
const stream = new ResponseStream(response, controller, idle, settle, fields);
|
|
286
|
+
return params.stream ? stream : stream.finalResponse();
|
|
289
287
|
};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Response as MossResponse, ResponseStreamEvent } from "./types.js";
|
|
2
2
|
/** A timer that runs only while armed, so a slow reader never trips it. */
|
|
3
3
|
interface IdleTimer {
|
|
4
4
|
arm(): void;
|
|
@@ -12,30 +12,32 @@ export declare function idleTimer(ms: number | null, onIdle: () => void): IdleTi
|
|
|
12
12
|
*/
|
|
13
13
|
export declare function errorText(response: Response, idle: IdleTimer): Promise<string>;
|
|
14
14
|
/**
|
|
15
|
-
* The streamed
|
|
15
|
+
* The streamed response of `responses.create` with `stream: true`.
|
|
16
16
|
*
|
|
17
|
-
* Iterate it once with `for await`.
|
|
18
|
-
* `controller.abort()`, ends the loop quietly,
|
|
19
|
-
* An abort with any other reason,
|
|
20
|
-
*
|
|
21
|
-
*
|
|
17
|
+
* Iterate it once with `for await`. It ends after `response.completed` or `response.incomplete`.
|
|
18
|
+
* Leaving the loop early, or calling `controller.abort()`, ends the loop quietly,
|
|
19
|
+
* closes the connection and stops the model. An abort with any other reason,
|
|
20
|
+
* such as the `TimeoutError` of `AbortSignal.timeout()`, throws that reason.
|
|
21
|
+
* A failure inside the stream, such as `response.failed`, throws an {@link InferenceError}
|
|
22
|
+
* after the events before it, with `errorCode` `failed_after_tool_call` once an event carried an `mcp_call` item.
|
|
22
23
|
*/
|
|
23
|
-
export declare class
|
|
24
|
+
export declare class ResponseStream implements AsyncIterable<ResponseStreamEvent> {
|
|
24
25
|
#private;
|
|
25
26
|
/** Aborts the request. */
|
|
26
27
|
readonly controller: AbortController;
|
|
27
28
|
/** The `X-Moss-Request-Id` of the response, undefined when it has none. */
|
|
28
29
|
readonly requestId: string | undefined;
|
|
29
|
-
/** Iterates the
|
|
30
|
-
[Symbol.asyncIterator](): AsyncIterator<
|
|
30
|
+
/** Iterates the events once. Its `return()` closes the connection, even before the first event. */
|
|
31
|
+
[Symbol.asyncIterator](): AsyncIterator<ResponseStreamEvent>;
|
|
31
32
|
/**
|
|
32
|
-
* The
|
|
33
|
+
* The `response` of the last event, as a call without `stream: true` returns.
|
|
33
34
|
*
|
|
34
|
-
* Every call returns the same
|
|
35
|
+
* Every call returns the same response.
|
|
35
36
|
* Call it after the loop ends, or instead of one.
|
|
36
|
-
* It reads the
|
|
37
|
-
* It rejects with what the loop throws, or with the signal's reason
|
|
37
|
+
* It reads the events the loop has not read.
|
|
38
|
+
* It rejects with what the loop throws, or with the signal's reason
|
|
39
|
+
* after an abort that came before the last event.
|
|
38
40
|
*/
|
|
39
|
-
|
|
41
|
+
finalResponse(): Promise<MossResponse>;
|
|
40
42
|
}
|
|
41
43
|
export {};
|
package/dist/inference/stream.js
CHANGED
|
@@ -9,7 +9,7 @@ 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
|
|
12
|
+
var _ResponseStream_instances, _ResponseStream_events, _ResponseStream_next, _ResponseStream_failure, _ResponseStream_response, _ResponseStream_final, _ResponseStream_drain;
|
|
13
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;
|
|
@@ -115,42 +115,43 @@ async function* sseData(body, idle, fields) {
|
|
|
115
115
|
}
|
|
116
116
|
}
|
|
117
117
|
/**
|
|
118
|
-
* The streamed
|
|
118
|
+
* The streamed response of `responses.create` with `stream: true`.
|
|
119
119
|
*
|
|
120
|
-
* Iterate it once with `for await`.
|
|
121
|
-
* `controller.abort()`, ends the loop quietly,
|
|
122
|
-
* An abort with any other reason,
|
|
123
|
-
*
|
|
124
|
-
*
|
|
120
|
+
* Iterate it once with `for await`. It ends after `response.completed` or `response.incomplete`.
|
|
121
|
+
* Leaving the loop early, or calling `controller.abort()`, ends the loop quietly,
|
|
122
|
+
* closes the connection and stops the model. An abort with any other reason,
|
|
123
|
+
* such as the `TimeoutError` of `AbortSignal.timeout()`, throws that reason.
|
|
124
|
+
* A failure inside the stream, such as `response.failed`, throws an {@link InferenceError}
|
|
125
|
+
* after the events before it, with `errorCode` `failed_after_tool_call` once an event carried an `mcp_call` item.
|
|
125
126
|
*/
|
|
126
|
-
export class
|
|
127
|
+
export class ResponseStream {
|
|
127
128
|
/** @internal */
|
|
128
|
-
constructor(response, controller, idle, onSettled, fields
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
129
|
+
constructor(response, controller, idle, onSettled, fields) {
|
|
130
|
+
_ResponseStream_instances.add(this);
|
|
131
|
+
_ResponseStream_events.set(this, void 0);
|
|
132
|
+
_ResponseStream_next.set(this, void 0);
|
|
133
|
+
/** What reading the events threw, which the final response throws again. */
|
|
134
|
+
_ResponseStream_failure.set(this, void 0);
|
|
135
|
+
/** The `response` of the last event, once it came. */
|
|
136
|
+
_ResponseStream_response.set(this, void 0);
|
|
137
|
+
_ResponseStream_final.set(this, void 0);
|
|
136
138
|
this.controller = controller;
|
|
137
139
|
this.requestId = fields.requestId;
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
__classPrivateFieldSet(this, _ChatCompletionStream_next, async () => {
|
|
140
|
+
const generator = events(response, controller, idle, onSettled, fields);
|
|
141
|
+
__classPrivateFieldSet(this, _ResponseStream_next, async () => {
|
|
141
142
|
try {
|
|
142
143
|
const result = await generator.next();
|
|
143
|
-
if (!result.done)
|
|
144
|
-
|
|
144
|
+
if (!result.done && isLast(result.value))
|
|
145
|
+
__classPrivateFieldSet(this, _ResponseStream_response, result.value.response, "f");
|
|
145
146
|
return result;
|
|
146
147
|
}
|
|
147
148
|
catch (error) {
|
|
148
|
-
__classPrivateFieldSet(this,
|
|
149
|
+
__classPrivateFieldSet(this, _ResponseStream_failure, { error }, "f");
|
|
149
150
|
throw error;
|
|
150
151
|
}
|
|
151
152
|
}, "f");
|
|
152
|
-
__classPrivateFieldSet(this,
|
|
153
|
-
next: __classPrivateFieldGet(this,
|
|
153
|
+
__classPrivateFieldSet(this, _ResponseStream_events, {
|
|
154
|
+
next: __classPrivateFieldGet(this, _ResponseStream_next, "f"),
|
|
154
155
|
return: (value) => {
|
|
155
156
|
controller.abort();
|
|
156
157
|
onSettled();
|
|
@@ -158,37 +159,41 @@ export class ChatCompletionStream {
|
|
|
158
159
|
},
|
|
159
160
|
}, "f");
|
|
160
161
|
}
|
|
161
|
-
/** Iterates the
|
|
162
|
-
[(
|
|
163
|
-
const iterator = __classPrivateFieldGet(this,
|
|
162
|
+
/** Iterates the events once. Its `return()` closes the connection, even before the first event. */
|
|
163
|
+
[(_ResponseStream_events = new WeakMap(), _ResponseStream_next = new WeakMap(), _ResponseStream_failure = new WeakMap(), _ResponseStream_response = new WeakMap(), _ResponseStream_final = new WeakMap(), _ResponseStream_instances = new WeakSet(), Symbol.asyncIterator)]() {
|
|
164
|
+
const iterator = __classPrivateFieldGet(this, _ResponseStream_events, "f");
|
|
164
165
|
if (!iterator)
|
|
165
|
-
throw new Error("A
|
|
166
|
-
__classPrivateFieldSet(this,
|
|
166
|
+
throw new Error("A ResponseStream can be iterated only once.");
|
|
167
|
+
__classPrivateFieldSet(this, _ResponseStream_events, undefined, "f");
|
|
167
168
|
return iterator;
|
|
168
169
|
}
|
|
169
170
|
/**
|
|
170
|
-
* The
|
|
171
|
+
* The `response` of the last event, as a call without `stream: true` returns.
|
|
171
172
|
*
|
|
172
|
-
* Every call returns the same
|
|
173
|
+
* Every call returns the same response.
|
|
173
174
|
* Call it after the loop ends, or instead of one.
|
|
174
|
-
* It reads the
|
|
175
|
-
* It rejects with what the loop throws, or with the signal's reason
|
|
175
|
+
* It reads the events the loop has not read.
|
|
176
|
+
* It rejects with what the loop throws, or with the signal's reason
|
|
177
|
+
* after an abort that came before the last event.
|
|
176
178
|
*/
|
|
177
|
-
|
|
178
|
-
return (__classPrivateFieldSet(this,
|
|
179
|
+
finalResponse() {
|
|
180
|
+
return (__classPrivateFieldSet(this, _ResponseStream_final, __classPrivateFieldGet(this, _ResponseStream_final, "f") ?? __classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_drain).call(this), "f"));
|
|
179
181
|
}
|
|
180
182
|
}
|
|
181
|
-
|
|
182
|
-
while (!(await __classPrivateFieldGet(this,
|
|
183
|
+
_ResponseStream_drain = async function _ResponseStream_drain() {
|
|
184
|
+
while (!(await __classPrivateFieldGet(this, _ResponseStream_next, "f").call(this)).done)
|
|
183
185
|
;
|
|
184
|
-
if (__classPrivateFieldGet(this,
|
|
185
|
-
throw __classPrivateFieldGet(this,
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
return Object.defineProperty(__classPrivateFieldGet(this, _ChatCompletionStream_join, "f").build(), "requestId", { value: this.requestId });
|
|
186
|
+
if (__classPrivateFieldGet(this, _ResponseStream_failure, "f"))
|
|
187
|
+
throw __classPrivateFieldGet(this, _ResponseStream_failure, "f").error;
|
|
188
|
+
if (__classPrivateFieldGet(this, _ResponseStream_response, "f"))
|
|
189
|
+
return __classPrivateFieldGet(this, _ResponseStream_response, "f");
|
|
190
|
+
throw this.controller.signal.reason;
|
|
190
191
|
};
|
|
191
|
-
|
|
192
|
+
/** True for a JSON object, not null or an array. */
|
|
193
|
+
const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
194
|
+
/** True for the last event of a stream, which holds the whole response. */
|
|
195
|
+
const isLast = (event) => ["response.completed", "response.incomplete"].includes(event.type) && isObject(event.response);
|
|
196
|
+
async function* events(response, controller, idle, onSettled, fields) {
|
|
192
197
|
const notObject = "The gateway sent an event that is not a JSON object.";
|
|
193
198
|
let done = false;
|
|
194
199
|
try {
|
|
@@ -199,10 +204,8 @@ async function* chunks(response, controller, idle, onSettled, fields) {
|
|
|
199
204
|
});
|
|
200
205
|
}
|
|
201
206
|
for await (const data of sseData(response.body, idle, fields)) {
|
|
202
|
-
if (data === "[DONE]")
|
|
203
|
-
|
|
204
|
-
return;
|
|
205
|
-
}
|
|
207
|
+
if (data === "[DONE]")
|
|
208
|
+
break;
|
|
206
209
|
let event;
|
|
207
210
|
try {
|
|
208
211
|
event = JSON.parse(data);
|
|
@@ -210,22 +213,37 @@ async function* chunks(response, controller, idle, onSettled, fields) {
|
|
|
210
213
|
catch (cause) {
|
|
211
214
|
throw new InferenceError(notObject, { type: "server_error", cause, ...fields });
|
|
212
215
|
}
|
|
213
|
-
if (
|
|
216
|
+
if (!isObject(event)) {
|
|
214
217
|
throw new InferenceError(notObject, { type: "server_error", ...fields });
|
|
215
218
|
}
|
|
216
|
-
if (event.error) {
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
219
|
+
if (event.type === "response.failed" || event.type === "error") {
|
|
220
|
+
const failed = event.type === "response.failed";
|
|
221
|
+
const error = failed
|
|
222
|
+
? (event.response?.error ?? {})
|
|
223
|
+
: event;
|
|
224
|
+
throw new InferenceError(typeof error.message === "string" ? error.message : "The model failed during the stream.", {
|
|
225
|
+
type: failed && typeof error.type === "string" ? error.type : "model_error",
|
|
226
|
+
errorCode: codeText(error.code),
|
|
221
227
|
...fields,
|
|
222
228
|
});
|
|
223
229
|
}
|
|
224
|
-
if (event.
|
|
230
|
+
if (event.item?.type === "mcp_call")
|
|
225
231
|
fields.errorCode = "failed_after_tool_call";
|
|
232
|
+
if (isObject(event.response)) {
|
|
233
|
+
const output = Array.isArray(event.response.output) ? event.response.output : [];
|
|
234
|
+
event.response.output_text = output
|
|
235
|
+
.flatMap((item) => item?.type === "message" && Array.isArray(item.content) ? item.content : [])
|
|
236
|
+
.filter((part) => part?.type === "output_text" && typeof part.text === "string")
|
|
237
|
+
.map((part) => part.text)
|
|
238
|
+
.join("");
|
|
239
|
+
Object.defineProperty(event.response, "requestId", { value: fields.requestId });
|
|
240
|
+
}
|
|
241
|
+
done = isLast(event);
|
|
226
242
|
yield event;
|
|
243
|
+
if (done)
|
|
244
|
+
return;
|
|
227
245
|
}
|
|
228
|
-
throw new InferenceError("The stream ended before
|
|
246
|
+
throw new InferenceError("The stream ended before response.completed.", {
|
|
229
247
|
type: "incomplete_stream",
|
|
230
248
|
...fields,
|
|
231
249
|
});
|
|
@@ -240,7 +258,7 @@ async function* chunks(response, controller, idle, onSettled, fields) {
|
|
|
240
258
|
throw reason;
|
|
241
259
|
}
|
|
242
260
|
if (socketEnded(error)) {
|
|
243
|
-
throw new InferenceError("The connection closed before
|
|
261
|
+
throw new InferenceError("The connection closed before response.completed.", {
|
|
244
262
|
type: "incomplete_stream",
|
|
245
263
|
cause: error,
|
|
246
264
|
...fields,
|
|
@@ -254,122 +272,3 @@ async function* chunks(response, controller, idle, onSettled, fields) {
|
|
|
254
272
|
onSettled();
|
|
255
273
|
}
|
|
256
274
|
}
|
|
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);
|
|
276
|
-
if (chunk.usage)
|
|
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;
|
|
283
|
-
const index = choice.index ?? 0;
|
|
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
|
-
}
|
|
295
|
-
const delta = choice.delta ?? {};
|
|
296
|
-
if (delta.content)
|
|
297
|
-
state.content = (state.content ?? "") + delta.content;
|
|
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) ?? {
|
|
323
|
-
id: "",
|
|
324
|
-
type: "function",
|
|
325
|
-
function: { name: "", arguments: "" },
|
|
326
|
-
};
|
|
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);
|
|
347
|
-
}
|
|
348
|
-
if (choice.finish_reason != null)
|
|
349
|
-
state.finishReason = choice.finish_reason;
|
|
350
|
-
}
|
|
351
|
-
}
|
|
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
|
-
}
|
|
375
|
-
}
|
|
@@ -1,43 +1,38 @@
|
|
|
1
|
-
/**
|
|
2
|
-
export interface
|
|
3
|
-
type
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
*/
|
|
11
|
-
export interface ChatCompletionMessageToolCall {
|
|
12
|
-
id: string;
|
|
13
|
-
type: "function";
|
|
14
|
-
function: {
|
|
15
|
-
name: string;
|
|
16
|
-
arguments: string;
|
|
17
|
-
};
|
|
1
|
+
/** A message of the conversation, such as `{ role: "user", content: "Hi" }`. */
|
|
2
|
+
export interface EasyInputMessage {
|
|
3
|
+
type?: "message";
|
|
4
|
+
role: "user" | "assistant" | "system" | "developer";
|
|
5
|
+
/** Text, or a list of parts such as `{ type: "input_text", text }`. */
|
|
6
|
+
content: string | {
|
|
7
|
+
type: string;
|
|
8
|
+
[key: string]: any;
|
|
9
|
+
}[];
|
|
18
10
|
[key: string]: any;
|
|
19
11
|
}
|
|
20
|
-
/**
|
|
21
|
-
export interface
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
12
|
+
/** The result of a {@link ResponseFunctionToolCall}, for the `input` of the next request. */
|
|
13
|
+
export interface FunctionCallOutput {
|
|
14
|
+
type: "function_call_output";
|
|
15
|
+
/** The `call_id` of the call. */
|
|
16
|
+
call_id: string;
|
|
17
|
+
/** Text, or a list of parts such as `{ type: "input_text", text }`. */
|
|
18
|
+
output: string | {
|
|
26
19
|
type: string;
|
|
27
20
|
[key: string]: any;
|
|
28
|
-
}
|
|
29
|
-
tool_call_id?: string;
|
|
21
|
+
}[];
|
|
30
22
|
[key: string]: any;
|
|
31
23
|
}
|
|
24
|
+
/**
|
|
25
|
+
* An item of `input`: a message, the result of a function call,
|
|
26
|
+
* or an item of an earlier response's `output`, sent back unchanged.
|
|
27
|
+
*/
|
|
28
|
+
export type ResponseInputItem = EasyInputMessage | FunctionCallOutput | ResponseOutputItem;
|
|
32
29
|
/** A function the model may call. Your code runs it and sends back the result. */
|
|
33
|
-
export interface
|
|
30
|
+
export interface FunctionTool {
|
|
34
31
|
type: "function";
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
strict?: boolean | null;
|
|
40
|
-
};
|
|
32
|
+
name: string;
|
|
33
|
+
description?: string | null;
|
|
34
|
+
parameters?: Record<string, unknown> | null;
|
|
35
|
+
strict?: boolean | null;
|
|
41
36
|
}
|
|
42
37
|
/** An MCP server the gateway calls for the model during the turn. */
|
|
43
38
|
export interface McpServer {
|
|
@@ -58,37 +53,17 @@ export interface McpServer {
|
|
|
58
53
|
transport?: "streamable_http" | "sse";
|
|
59
54
|
}
|
|
60
55
|
/**
|
|
61
|
-
*
|
|
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
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* OpenAI's chat completion parameters plus the Moss options.
|
|
56
|
+
* OpenAI's Responses parameters plus the Moss options.
|
|
85
57
|
* `indexes`, `retrieve` and `cache` travel as headers, the rest in the body
|
|
86
58
|
* unchanged, including parameters this type does not name. The body always says `stream: true`.
|
|
87
59
|
*/
|
|
88
|
-
export interface
|
|
60
|
+
export interface ResponseCreateParamsBase {
|
|
89
61
|
/** `moss` by default, Moss's own model. A vendor model such as `gpt-4o-mini` needs `apiKey`. */
|
|
90
62
|
model?: string;
|
|
91
|
-
|
|
63
|
+
/** The text to answer, or the whole conversation so far, since Moss stores none. */
|
|
64
|
+
input: string | ResponseInputItem[];
|
|
65
|
+
/** The system message, before `input`. */
|
|
66
|
+
instructions?: string | null;
|
|
92
67
|
stream?: boolean | null;
|
|
93
68
|
/**
|
|
94
69
|
* Moss indexes to search, every index when left out and none when empty.
|
|
@@ -99,45 +74,50 @@ export interface ChatCompletionCreateParamsBase {
|
|
|
99
74
|
retrieve?: boolean;
|
|
100
75
|
/** False always asks the model instead of the gateway's reply cache. */
|
|
101
76
|
cache?: boolean;
|
|
102
|
-
temperature?: number | null;
|
|
103
|
-
top_p?: number | null;
|
|
104
|
-
max_tokens?: number | null;
|
|
105
|
-
max_completion_tokens?: number | null;
|
|
106
|
-
stop?: string | string[] | null;
|
|
107
|
-
seed?: number | null;
|
|
108
77
|
/** Functions your code runs, MCP servers the gateway calls, or any other tool object. */
|
|
109
|
-
tools?: (
|
|
78
|
+
tools?: (FunctionTool | McpServer | {
|
|
110
79
|
type: string;
|
|
111
80
|
[key: string]: any;
|
|
112
81
|
})[];
|
|
113
|
-
/** Whether and which tool the model calls, such as `{ type: "function",
|
|
82
|
+
/** Whether and which tool the model calls, such as `{ type: "function", name }`. */
|
|
114
83
|
tool_choice?: "none" | "auto" | "required" | {
|
|
115
84
|
type: string;
|
|
116
85
|
[key: string]: any;
|
|
117
86
|
};
|
|
118
|
-
/** False asks the model for at most one tool call per
|
|
87
|
+
/** False asks the model for at most one tool call per response. */
|
|
119
88
|
parallel_tool_calls?: boolean | null;
|
|
120
|
-
|
|
121
|
-
|
|
89
|
+
/** The most tokens the response can have. A longer one ends `incomplete`. */
|
|
90
|
+
max_output_tokens?: number | null;
|
|
91
|
+
temperature?: number | null;
|
|
92
|
+
top_p?: number | null;
|
|
93
|
+
/** Such as `{ format: { type: "json_schema", name, schema } }` for structured output. */
|
|
94
|
+
text?: {
|
|
95
|
+
format?: {
|
|
96
|
+
type: string;
|
|
97
|
+
[key: string]: any;
|
|
98
|
+
};
|
|
122
99
|
[key: string]: any;
|
|
123
|
-
};
|
|
124
|
-
stream_options?: {
|
|
125
|
-
include_usage?: boolean;
|
|
126
100
|
} | null;
|
|
101
|
+
/** Such as `{ effort: "low" }`. */
|
|
102
|
+
reasoning?: {
|
|
103
|
+
effort?: string | null;
|
|
104
|
+
[key: string]: any;
|
|
105
|
+
} | null;
|
|
106
|
+
metadata?: Record<string, string> | null;
|
|
127
107
|
user?: string;
|
|
128
108
|
/** Any other OpenAI parameter. */
|
|
129
109
|
[param: string]: any;
|
|
130
110
|
}
|
|
131
|
-
/** Parameters that return a {@link
|
|
132
|
-
export interface
|
|
111
|
+
/** Parameters that return a {@link ResponseStream}. */
|
|
112
|
+
export interface ResponseCreateParamsStreaming extends ResponseCreateParamsBase {
|
|
133
113
|
stream: true;
|
|
134
114
|
}
|
|
135
|
-
/** Parameters that return one
|
|
136
|
-
export interface
|
|
115
|
+
/** Parameters that return one {@link Response}. */
|
|
116
|
+
export interface ResponseCreateParamsNonStreaming extends ResponseCreateParamsBase {
|
|
137
117
|
stream?: false | null;
|
|
138
118
|
}
|
|
139
|
-
/** Parameters of `
|
|
140
|
-
export type
|
|
119
|
+
/** Parameters of `responses.create`. */
|
|
120
|
+
export type ResponseCreateParams = ResponseCreateParamsStreaming | ResponseCreateParamsNonStreaming;
|
|
141
121
|
/**
|
|
142
122
|
* Settings of a `MossInference` client.
|
|
143
123
|
* Timeouts are in milliseconds, and `null` or `Infinity` removes the limit.
|
|
@@ -182,103 +162,135 @@ export interface InferenceRequestOptions {
|
|
|
182
162
|
/** Headers for this call, over the client's. The SDK's own headers win over both. */
|
|
183
163
|
headers?: Record<string, string>;
|
|
184
164
|
}
|
|
185
|
-
/** Token counts for one call, with every field the gateway sent
|
|
186
|
-
export interface
|
|
187
|
-
|
|
188
|
-
|
|
165
|
+
/** Token counts for one call, with every field the gateway sent, such as `moss`. */
|
|
166
|
+
export interface ResponseUsage {
|
|
167
|
+
input_tokens: number;
|
|
168
|
+
input_tokens_details: {
|
|
169
|
+
cached_tokens: number;
|
|
170
|
+
[key: string]: any;
|
|
171
|
+
};
|
|
172
|
+
output_tokens: number;
|
|
173
|
+
output_tokens_details: {
|
|
174
|
+
reasoning_tokens: number;
|
|
175
|
+
[key: string]: any;
|
|
176
|
+
};
|
|
189
177
|
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
178
|
[key: string]: any;
|
|
195
179
|
}
|
|
196
|
-
/** The
|
|
197
|
-
export interface
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
top_logprobs: {
|
|
202
|
-
token: string;
|
|
203
|
-
logprob: number;
|
|
204
|
-
bytes: number[] | null;
|
|
205
|
-
}[];
|
|
180
|
+
/** The text of a message, with its annotations. */
|
|
181
|
+
export interface ResponseOutputText {
|
|
182
|
+
type: "output_text";
|
|
183
|
+
text: string;
|
|
184
|
+
annotations: any[];
|
|
206
185
|
[key: string]: any;
|
|
207
186
|
}
|
|
208
|
-
/**
|
|
209
|
-
export interface
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
index: number;
|
|
216
|
-
id?: string;
|
|
217
|
-
type?: "function";
|
|
218
|
-
function?: {
|
|
219
|
-
name?: string;
|
|
220
|
-
arguments?: string;
|
|
221
|
-
};
|
|
187
|
+
/** A message of the model, an item of `output`. */
|
|
188
|
+
export interface ResponseOutputMessage {
|
|
189
|
+
type: "message";
|
|
190
|
+
id: string;
|
|
191
|
+
role: "assistant";
|
|
192
|
+
status: "in_progress" | "completed" | "incomplete";
|
|
193
|
+
content: ResponseOutputText[];
|
|
222
194
|
[key: string]: any;
|
|
223
195
|
}
|
|
224
|
-
/** What one chunk adds to a choice. */
|
|
225
|
-
export interface ChatCompletionChunkDelta {
|
|
226
|
-
role?: string;
|
|
227
|
-
content?: string | null;
|
|
228
|
-
tool_calls?: ChatCompletionChunkToolCall[];
|
|
229
|
-
}
|
|
230
|
-
/** One choice inside a streamed chunk. */
|
|
231
|
-
export interface ChatCompletionChunkChoice {
|
|
232
|
-
index: number;
|
|
233
|
-
delta: ChatCompletionChunkDelta;
|
|
234
|
-
logprobs?: ChatCompletionLogprobs | null;
|
|
235
|
-
finish_reason: string | null;
|
|
236
|
-
}
|
|
237
196
|
/**
|
|
238
|
-
*
|
|
239
|
-
*
|
|
240
|
-
* so
|
|
241
|
-
* The last chunk may carry `usage` with an empty `choices` list.
|
|
197
|
+
* A call of one of your function tools, an item of `output`.
|
|
198
|
+
* Fields the model adds, such as Gemini's `extra_content`, stay on the object,
|
|
199
|
+
* so it goes back into `input` unchanged, before its {@link FunctionCallOutput}.
|
|
242
200
|
*/
|
|
243
|
-
export interface
|
|
201
|
+
export interface ResponseFunctionToolCall {
|
|
202
|
+
type: "function_call";
|
|
244
203
|
id: string;
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
204
|
+
/** The id its {@link FunctionCallOutput} names. */
|
|
205
|
+
call_id: string;
|
|
206
|
+
name: string;
|
|
207
|
+
/** The arguments as JSON text. */
|
|
208
|
+
arguments: string;
|
|
209
|
+
status: "in_progress" | "completed" | "incomplete";
|
|
210
|
+
[key: string]: any;
|
|
252
211
|
}
|
|
253
212
|
/**
|
|
254
|
-
*
|
|
255
|
-
*
|
|
213
|
+
* A call that the gateway ran on one of your MCP servers, an item of `output`.
|
|
214
|
+
* Sent back in `input` with the rest of `output`, it gives the model the tool's earlier result.
|
|
256
215
|
*/
|
|
257
|
-
export interface
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
216
|
+
export interface McpCall {
|
|
217
|
+
type: "mcp_call";
|
|
218
|
+
id: string;
|
|
219
|
+
/** The label of the MCP server, as sent in `tools`. */
|
|
220
|
+
server_label: string;
|
|
221
|
+
/** The tool's name on its server. */
|
|
222
|
+
name: string;
|
|
223
|
+
/** The arguments as JSON text. */
|
|
224
|
+
arguments: string;
|
|
225
|
+
/** The tool's result, cut when long, once it succeeded. */
|
|
226
|
+
output?: string | null;
|
|
227
|
+
/** What failed, once the tool failed. */
|
|
228
|
+
error?: {
|
|
229
|
+
type: string;
|
|
230
|
+
[key: string]: any;
|
|
231
|
+
} | null;
|
|
232
|
+
status: "in_progress" | "completed" | "failed";
|
|
233
|
+
/** How long the call took in milliseconds, once it ended. */
|
|
234
|
+
duration_ms?: number;
|
|
235
|
+
[key: string]: any;
|
|
263
236
|
}
|
|
264
|
-
/**
|
|
265
|
-
export interface
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
logprobs: ChatCompletionLogprobs | null;
|
|
270
|
-
finish_reason: string | null;
|
|
237
|
+
/** The reasoning of a reasoning model, an item of `output`, kept as the gateway sent it. */
|
|
238
|
+
export interface ResponseReasoningItem {
|
|
239
|
+
type: "reasoning";
|
|
240
|
+
id: string;
|
|
241
|
+
[key: string]: any;
|
|
271
242
|
}
|
|
272
|
-
/**
|
|
273
|
-
export
|
|
243
|
+
/** An item of `output`. An item of another type comes as the gateway sent it. */
|
|
244
|
+
export type ResponseOutputItem = ResponseOutputMessage | ResponseFunctionToolCall | McpCall | ResponseReasoningItem;
|
|
245
|
+
/**
|
|
246
|
+
* A response, the JSON the gateway sent, plus `output_text`.
|
|
247
|
+
* `JSON.stringify` keeps `output_text` and leaves out `requestId`.
|
|
248
|
+
* A call without `stream: true`, and `finalResponse()`, return the one of the last event.
|
|
249
|
+
*/
|
|
250
|
+
export interface Response {
|
|
251
|
+
/** Such as `resp_...`. */
|
|
274
252
|
id: string;
|
|
275
|
-
object: "
|
|
276
|
-
|
|
253
|
+
object: "response";
|
|
254
|
+
/** In seconds since the epoch. */
|
|
255
|
+
created_at: number;
|
|
256
|
+
/** `incomplete` when `max_output_tokens` or a content filter cut the response. */
|
|
257
|
+
status: "completed" | "incomplete" | "failed" | "in_progress" | (string & {});
|
|
277
258
|
model: string;
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
259
|
+
output: ResponseOutputItem[];
|
|
260
|
+
/** The text of every `output_text` part of every message in `output`, joined. */
|
|
261
|
+
output_text: string;
|
|
262
|
+
usage: ResponseUsage | null;
|
|
263
|
+
error: {
|
|
264
|
+
code: string;
|
|
265
|
+
message: string;
|
|
266
|
+
[key: string]: any;
|
|
267
|
+
} | null;
|
|
268
|
+
incomplete_details: {
|
|
269
|
+
reason: "max_output_tokens" | "content_filter" | (string & {});
|
|
270
|
+
} | null;
|
|
271
|
+
instructions: string | null;
|
|
272
|
+
metadata: Record<string, string> | null;
|
|
273
|
+
/** The `X-Moss-Request-Id` of the HTTP response. */
|
|
283
274
|
readonly requestId?: string;
|
|
275
|
+
/** The other request fields the gateway repeats, such as `temperature`. */
|
|
276
|
+
[key: string]: any;
|
|
277
|
+
}
|
|
278
|
+
/**
|
|
279
|
+
* One event of a streamed response, the JSON the gateway sent.
|
|
280
|
+
* Each type sets its own fields, such as `delta` on `response.output_text.delta`,
|
|
281
|
+
* `item` on `response.output_item.added` and `.done`, and `response` on
|
|
282
|
+
* `response.created`, `response.completed` and `response.incomplete`.
|
|
283
|
+
*/
|
|
284
|
+
export interface ResponseStreamEvent {
|
|
285
|
+
type: string;
|
|
286
|
+
sequence_number?: number;
|
|
287
|
+
response?: Response;
|
|
288
|
+
output_index?: number;
|
|
289
|
+
item_id?: string;
|
|
290
|
+
item?: ResponseOutputItem;
|
|
291
|
+
content_index?: number;
|
|
292
|
+
delta?: string;
|
|
293
|
+
text?: string;
|
|
294
|
+
arguments?: string;
|
|
295
|
+
[key: string]: any;
|
|
284
296
|
}
|