modelfusion 0.33.1 → 0.35.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 +47 -1
- package/{model-function/generate-text → event-source}/AsyncQueue.cjs +11 -10
- package/event-source/AsyncQueue.d.ts +8 -0
- package/{model-function/generate-text → event-source}/AsyncQueue.js +11 -10
- package/event-source/EventSourceParserStream.cjs +34 -0
- package/event-source/EventSourceParserStream.d.ts +15 -0
- package/event-source/EventSourceParserStream.js +30 -0
- package/event-source/convertReadableStreamToAsyncIterable.cjs +19 -0
- package/event-source/convertReadableStreamToAsyncIterable.d.ts +1 -0
- package/event-source/convertReadableStreamToAsyncIterable.js +15 -0
- package/event-source/createEventSourceStream.cjs +15 -0
- package/event-source/createEventSourceStream.d.ts +1 -0
- package/event-source/createEventSourceStream.js +11 -0
- package/event-source/index.cjs +19 -0
- package/event-source/index.d.ts +3 -0
- package/event-source/index.js +3 -0
- package/event-source/parseEventSourceStream.cjs +12 -0
- package/event-source/parseEventSourceStream.d.ts +4 -0
- package/event-source/parseEventSourceStream.js +8 -0
- package/event-source/readEventSourceStream.cjs +33 -0
- package/event-source/readEventSourceStream.d.ts +6 -0
- package/event-source/readEventSourceStream.js +26 -0
- package/index.cjs +1 -0
- package/index.d.ts +1 -0
- package/index.js +1 -0
- package/model-function/AsyncIterableResultPromise.cjs +37 -0
- package/model-function/AsyncIterableResultPromise.d.ts +16 -0
- package/model-function/AsyncIterableResultPromise.js +33 -0
- package/model-function/{generate-text/DeltaEvent.d.ts → DeltaEvent.d.ts} +1 -1
- package/model-function/ModelCallEvent.d.ts +3 -2
- package/model-function/generate-structure/StructureFromTextGenerationModel.d.ts +1 -1
- package/model-function/generate-structure/StructureGenerationModel.d.ts +10 -1
- package/model-function/generate-structure/StructureStreamingEvent.cjs +2 -0
- package/model-function/generate-structure/StructureStreamingEvent.d.ts +7 -0
- package/model-function/generate-structure/StructureStreamingEvent.js +1 -0
- package/model-function/generate-structure/fixJson.cjs +215 -0
- package/model-function/generate-structure/fixJson.d.ts +1 -0
- package/model-function/generate-structure/fixJson.js +211 -0
- package/model-function/generate-structure/fixJson.test.cjs +130 -0
- package/model-function/generate-structure/fixJson.test.d.ts +1 -0
- package/model-function/generate-structure/fixJson.test.js +128 -0
- package/model-function/generate-structure/generateStructure.cjs +3 -1
- package/model-function/generate-structure/generateStructure.d.ts +1 -1
- package/model-function/generate-structure/generateStructure.js +3 -1
- package/model-function/generate-structure/parsePartialJson.cjs +29 -0
- package/model-function/generate-structure/parsePartialJson.d.ts +1 -0
- package/model-function/generate-structure/parsePartialJson.js +22 -0
- package/model-function/generate-structure/streamStructure.cjs +167 -0
- package/model-function/generate-structure/streamStructure.d.ts +17 -0
- package/model-function/generate-structure/streamStructure.js +160 -0
- package/model-function/generate-text/TextGenerationModel.d.ts +4 -4
- package/model-function/generate-text/streamText.cjs +47 -68
- package/model-function/generate-text/streamText.d.ts +3 -18
- package/model-function/generate-text/streamText.js +46 -66
- package/model-function/index.cjs +3 -2
- package/model-function/index.d.ts +3 -2
- package/model-function/index.js +3 -2
- package/model-provider/cohere/CohereTextGenerationModel.cjs +3 -3
- package/model-provider/cohere/CohereTextGenerationModel.d.ts +3 -3
- package/model-provider/cohere/CohereTextGenerationModel.js +3 -3
- package/model-provider/huggingface/HuggingFaceTextGenerationModel.cjs +0 -12
- package/model-provider/huggingface/HuggingFaceTextGenerationModel.d.ts +0 -2
- package/model-provider/huggingface/HuggingFaceTextGenerationModel.js +0 -12
- package/model-provider/llamacpp/LlamaCppTextGenerationModel.cjs +23 -23
- package/model-provider/llamacpp/LlamaCppTextGenerationModel.d.ts +3 -3
- package/model-provider/llamacpp/LlamaCppTextGenerationModel.js +23 -23
- package/model-provider/openai/OpenAITextGenerationModel.cjs +27 -25
- package/model-provider/openai/OpenAITextGenerationModel.d.ts +3 -3
- package/model-provider/openai/OpenAITextGenerationModel.js +27 -25
- package/model-provider/openai/chat/OpenAIChatModel.cjs +23 -2
- package/model-provider/openai/chat/OpenAIChatModel.d.ts +4 -2
- package/model-provider/openai/chat/OpenAIChatModel.js +23 -2
- package/model-provider/openai/chat/OpenAIChatStreamIterable.cjs +27 -24
- package/model-provider/openai/chat/OpenAIChatStreamIterable.d.ts +1 -1
- package/model-provider/openai/chat/OpenAIChatStreamIterable.js +27 -24
- package/package.json +9 -5
- package/prompt/PromptFormatTextGenerationModel.d.ts +1 -1
- package/tool/useTool.cjs +3 -4
- package/tool/useTool.d.ts +1 -1
- package/tool/useTool.js +3 -4
- package/model-function/generate-text/AsyncQueue.d.ts +0 -17
- package/model-function/generate-text/TextDeltaEventSource.cjs +0 -54
- package/model-function/generate-text/TextDeltaEventSource.d.ts +0 -5
- package/model-function/generate-text/TextDeltaEventSource.js +0 -46
- package/model-function/generate-text/extractTextDeltas.cjs +0 -23
- package/model-function/generate-text/extractTextDeltas.d.ts +0 -7
- package/model-function/generate-text/extractTextDeltas.js +0 -19
- package/model-function/generate-text/parseEventSourceReadableStream.cjs +0 -30
- package/model-function/generate-text/parseEventSourceReadableStream.d.ts +0 -8
- package/model-function/generate-text/parseEventSourceReadableStream.js +0 -26
- /package/model-function/{generate-text/DeltaEvent.cjs → DeltaEvent.cjs} +0 -0
- /package/model-function/{generate-text/DeltaEvent.js → DeltaEvent.js} +0 -0
package/README.md
CHANGED
@@ -133,7 +133,7 @@ for (const choice of response.choices) {
|
|
133
133
|
console.log(`Duration: ${metadata.durationInMs}ms`);
|
134
134
|
```
|
135
135
|
|
136
|
-
### [Generate Structure](https://modelfusion.dev/guide/function/generate-structure)
|
136
|
+
### [Generate Structure](https://modelfusion.dev/guide/function/generate-structure#generatestructure)
|
137
137
|
|
138
138
|
Generate a structure that matches a schema.
|
139
139
|
|
@@ -168,6 +168,52 @@ const sentiment = await generateStructure(
|
|
168
168
|
|
169
169
|
Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai)
|
170
170
|
|
171
|
+
### [Stream Structure](https://modelfusion.dev/guide/function/generate-structure#streamstructure)
|
172
|
+
|
173
|
+
Stream a structure that matches a schema. Partial structures before the final part are untyped JSON.
|
174
|
+
|
175
|
+
```ts
|
176
|
+
const structureStream = await streamStructure(
|
177
|
+
new OpenAIChatModel({
|
178
|
+
model: "gpt-3.5-turbo",
|
179
|
+
temperature: 0,
|
180
|
+
maxCompletionTokens: 2000,
|
181
|
+
}),
|
182
|
+
new ZodStructureDefinition({
|
183
|
+
name: "generateCharacter" as const,
|
184
|
+
description: "Generate character descriptions.",
|
185
|
+
schema: z.object({
|
186
|
+
characters: z.array(
|
187
|
+
z.object({
|
188
|
+
name: z.string(),
|
189
|
+
class: z
|
190
|
+
.string()
|
191
|
+
.describe("Character class, e.g. warrior, mage, or thief."),
|
192
|
+
description: z.string(),
|
193
|
+
})
|
194
|
+
),
|
195
|
+
}),
|
196
|
+
}),
|
197
|
+
[
|
198
|
+
OpenAIChatMessage.user(
|
199
|
+
"Generate 3 character descriptions for a fantasy role playing game."
|
200
|
+
),
|
201
|
+
]
|
202
|
+
);
|
203
|
+
|
204
|
+
for await (const part of structureStream) {
|
205
|
+
if (!part.isComplete) {
|
206
|
+
const unknownPartialStructure = part.value;
|
207
|
+
console.log("partial value", unknownPartialStructure);
|
208
|
+
} else {
|
209
|
+
const fullyTypedStructure = part.value;
|
210
|
+
console.log("final value", fullyTypedStructure);
|
211
|
+
}
|
212
|
+
}
|
213
|
+
```
|
214
|
+
|
215
|
+
Providers: [OpenAI](https://modelfusion.dev/integration/model-provider/openai)
|
216
|
+
|
171
217
|
### [Generate Structure or Text](https://modelfusion.dev/guide/function/generate-structure-or-text)
|
172
218
|
|
173
219
|
Generate a structure (or text as a fallback) using a prompt and multiple schemas.
|
@@ -1,16 +1,13 @@
|
|
1
1
|
"use strict";
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
3
3
|
exports.AsyncQueue = void 0;
|
4
|
-
/**
|
5
|
-
* @internal
|
6
|
-
*/
|
7
4
|
class AsyncQueue {
|
8
5
|
constructor() {
|
9
6
|
Object.defineProperty(this, "queue", {
|
10
7
|
enumerable: true,
|
11
8
|
configurable: true,
|
12
9
|
writable: true,
|
13
|
-
value:
|
10
|
+
value: []
|
14
11
|
});
|
15
12
|
Object.defineProperty(this, "resolvers", {
|
16
13
|
enumerable: true,
|
@@ -22,11 +19,8 @@ class AsyncQueue {
|
|
22
19
|
enumerable: true,
|
23
20
|
configurable: true,
|
24
21
|
writable: true,
|
25
|
-
value:
|
22
|
+
value: false
|
26
23
|
});
|
27
|
-
this.queue = [];
|
28
|
-
this.resolvers = [];
|
29
|
-
this.closed = false;
|
30
24
|
}
|
31
25
|
push(value) {
|
32
26
|
if (this.closed) {
|
@@ -43,6 +37,7 @@ class AsyncQueue {
|
|
43
37
|
close() {
|
44
38
|
while (this.resolvers.length) {
|
45
39
|
const resolve = this.resolvers.shift();
|
40
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
46
41
|
resolve?.({ value: undefined, done: true });
|
47
42
|
}
|
48
43
|
this.closed = true;
|
@@ -51,13 +46,19 @@ class AsyncQueue {
|
|
51
46
|
return {
|
52
47
|
next: () => {
|
53
48
|
if (this.queue.length > 0) {
|
54
|
-
return Promise.resolve({
|
49
|
+
return Promise.resolve({
|
50
|
+
value: this.queue.shift(),
|
51
|
+
done: false,
|
52
|
+
});
|
55
53
|
}
|
56
54
|
else if (this.closed) {
|
55
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
57
56
|
return Promise.resolve({ value: undefined, done: true });
|
58
57
|
}
|
59
58
|
else {
|
60
|
-
return new Promise((resolve) =>
|
59
|
+
return new Promise((resolve) => {
|
60
|
+
this.resolvers.push(resolve);
|
61
|
+
});
|
61
62
|
}
|
62
63
|
},
|
63
64
|
};
|
@@ -1,13 +1,10 @@
|
|
1
|
-
/**
|
2
|
-
* @internal
|
3
|
-
*/
|
4
1
|
export class AsyncQueue {
|
5
2
|
constructor() {
|
6
3
|
Object.defineProperty(this, "queue", {
|
7
4
|
enumerable: true,
|
8
5
|
configurable: true,
|
9
6
|
writable: true,
|
10
|
-
value:
|
7
|
+
value: []
|
11
8
|
});
|
12
9
|
Object.defineProperty(this, "resolvers", {
|
13
10
|
enumerable: true,
|
@@ -19,11 +16,8 @@ export class AsyncQueue {
|
|
19
16
|
enumerable: true,
|
20
17
|
configurable: true,
|
21
18
|
writable: true,
|
22
|
-
value:
|
19
|
+
value: false
|
23
20
|
});
|
24
|
-
this.queue = [];
|
25
|
-
this.resolvers = [];
|
26
|
-
this.closed = false;
|
27
21
|
}
|
28
22
|
push(value) {
|
29
23
|
if (this.closed) {
|
@@ -40,6 +34,7 @@ export class AsyncQueue {
|
|
40
34
|
close() {
|
41
35
|
while (this.resolvers.length) {
|
42
36
|
const resolve = this.resolvers.shift();
|
37
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
43
38
|
resolve?.({ value: undefined, done: true });
|
44
39
|
}
|
45
40
|
this.closed = true;
|
@@ -48,13 +43,19 @@ export class AsyncQueue {
|
|
48
43
|
return {
|
49
44
|
next: () => {
|
50
45
|
if (this.queue.length > 0) {
|
51
|
-
return Promise.resolve({
|
46
|
+
return Promise.resolve({
|
47
|
+
value: this.queue.shift(),
|
48
|
+
done: false,
|
49
|
+
});
|
52
50
|
}
|
53
51
|
else if (this.closed) {
|
52
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
54
53
|
return Promise.resolve({ value: undefined, done: true });
|
55
54
|
}
|
56
55
|
else {
|
57
|
-
return new Promise((resolve) =>
|
56
|
+
return new Promise((resolve) => {
|
57
|
+
this.resolvers.push(resolve);
|
58
|
+
});
|
58
59
|
}
|
59
60
|
},
|
60
61
|
};
|
@@ -0,0 +1,34 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.EventSourceParserStream = void 0;
|
4
|
+
const eventsource_parser_1 = require("eventsource-parser");
|
5
|
+
/**
|
6
|
+
* A TransformStream that ingests a stream of strings and produces a stream of ParsedEvents.
|
7
|
+
*
|
8
|
+
* @example
|
9
|
+
* ```
|
10
|
+
* const eventStream =
|
11
|
+
* response.body
|
12
|
+
* .pipeThrough(new TextDecoderStream())
|
13
|
+
* .pipeThrough(new EventSourceParserStream())
|
14
|
+
* ```
|
15
|
+
*/
|
16
|
+
// Copied from https://github.com/rexxars/eventsource-parser/blob/main/src/stream.ts to avoid issues with the commonjs build.
|
17
|
+
class EventSourceParserStream extends TransformStream {
|
18
|
+
constructor() {
|
19
|
+
let parser;
|
20
|
+
super({
|
21
|
+
start(controller) {
|
22
|
+
parser = (0, eventsource_parser_1.createParser)((event) => {
|
23
|
+
if (event.type === "event") {
|
24
|
+
controller.enqueue(event);
|
25
|
+
}
|
26
|
+
});
|
27
|
+
},
|
28
|
+
transform(chunk) {
|
29
|
+
parser.feed(chunk);
|
30
|
+
},
|
31
|
+
});
|
32
|
+
}
|
33
|
+
}
|
34
|
+
exports.EventSourceParserStream = EventSourceParserStream;
|
@@ -0,0 +1,15 @@
|
|
1
|
+
import { ParsedEvent } from "eventsource-parser";
|
2
|
+
/**
|
3
|
+
* A TransformStream that ingests a stream of strings and produces a stream of ParsedEvents.
|
4
|
+
*
|
5
|
+
* @example
|
6
|
+
* ```
|
7
|
+
* const eventStream =
|
8
|
+
* response.body
|
9
|
+
* .pipeThrough(new TextDecoderStream())
|
10
|
+
* .pipeThrough(new EventSourceParserStream())
|
11
|
+
* ```
|
12
|
+
*/
|
13
|
+
export declare class EventSourceParserStream extends TransformStream<string, ParsedEvent> {
|
14
|
+
constructor();
|
15
|
+
}
|
@@ -0,0 +1,30 @@
|
|
1
|
+
import { createParser, } from "eventsource-parser";
|
2
|
+
/**
|
3
|
+
* A TransformStream that ingests a stream of strings and produces a stream of ParsedEvents.
|
4
|
+
*
|
5
|
+
* @example
|
6
|
+
* ```
|
7
|
+
* const eventStream =
|
8
|
+
* response.body
|
9
|
+
* .pipeThrough(new TextDecoderStream())
|
10
|
+
* .pipeThrough(new EventSourceParserStream())
|
11
|
+
* ```
|
12
|
+
*/
|
13
|
+
// Copied from https://github.com/rexxars/eventsource-parser/blob/main/src/stream.ts to avoid issues with the commonjs build.
|
14
|
+
export class EventSourceParserStream extends TransformStream {
|
15
|
+
constructor() {
|
16
|
+
let parser;
|
17
|
+
super({
|
18
|
+
start(controller) {
|
19
|
+
parser = createParser((event) => {
|
20
|
+
if (event.type === "event") {
|
21
|
+
controller.enqueue(event);
|
22
|
+
}
|
23
|
+
});
|
24
|
+
},
|
25
|
+
transform(chunk) {
|
26
|
+
parser.feed(chunk);
|
27
|
+
},
|
28
|
+
});
|
29
|
+
}
|
30
|
+
}
|
@@ -0,0 +1,19 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.convertReadableStreamToAsyncIterable = void 0;
|
4
|
+
async function* convertReadableStreamToAsyncIterable(stream) {
|
5
|
+
const reader = stream.getReader();
|
6
|
+
try {
|
7
|
+
while (true) {
|
8
|
+
const { done, value } = await reader.read();
|
9
|
+
if (done) {
|
10
|
+
return; // This will close the generator
|
11
|
+
}
|
12
|
+
yield value;
|
13
|
+
}
|
14
|
+
}
|
15
|
+
finally {
|
16
|
+
reader.releaseLock();
|
17
|
+
}
|
18
|
+
}
|
19
|
+
exports.convertReadableStreamToAsyncIterable = convertReadableStreamToAsyncIterable;
|
@@ -0,0 +1 @@
|
|
1
|
+
export declare function convertReadableStreamToAsyncIterable<T>(stream: ReadableStream<T>): AsyncIterable<T>;
|
@@ -0,0 +1,15 @@
|
|
1
|
+
export async function* convertReadableStreamToAsyncIterable(stream) {
|
2
|
+
const reader = stream.getReader();
|
3
|
+
try {
|
4
|
+
while (true) {
|
5
|
+
const { done, value } = await reader.read();
|
6
|
+
if (done) {
|
7
|
+
return; // This will close the generator
|
8
|
+
}
|
9
|
+
yield value;
|
10
|
+
}
|
11
|
+
}
|
12
|
+
finally {
|
13
|
+
reader.releaseLock();
|
14
|
+
}
|
15
|
+
}
|
@@ -0,0 +1,15 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.createEventSourceStream = void 0;
|
4
|
+
const textEncoder = new TextEncoder();
|
5
|
+
function createEventSourceStream(events) {
|
6
|
+
return new ReadableStream({
|
7
|
+
async start(controller) {
|
8
|
+
for await (const event of events) {
|
9
|
+
controller.enqueue(textEncoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
10
|
+
}
|
11
|
+
controller.close();
|
12
|
+
},
|
13
|
+
});
|
14
|
+
}
|
15
|
+
exports.createEventSourceStream = createEventSourceStream;
|
@@ -0,0 +1 @@
|
|
1
|
+
export declare function createEventSourceStream(events: AsyncIterable<unknown>): ReadableStream<any>;
|
@@ -0,0 +1,11 @@
|
|
1
|
+
const textEncoder = new TextEncoder();
|
2
|
+
export function createEventSourceStream(events) {
|
3
|
+
return new ReadableStream({
|
4
|
+
async start(controller) {
|
5
|
+
for await (const event of events) {
|
6
|
+
controller.enqueue(textEncoder.encode(`data: ${JSON.stringify(event)}\n\n`));
|
7
|
+
}
|
8
|
+
controller.close();
|
9
|
+
},
|
10
|
+
});
|
11
|
+
}
|
@@ -0,0 +1,19 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
3
|
+
if (k2 === undefined) k2 = k;
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
7
|
+
}
|
8
|
+
Object.defineProperty(o, k2, desc);
|
9
|
+
}) : (function(o, m, k, k2) {
|
10
|
+
if (k2 === undefined) k2 = k;
|
11
|
+
o[k2] = m[k];
|
12
|
+
}));
|
13
|
+
var __exportStar = (this && this.__exportStar) || function(m, exports) {
|
14
|
+
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
|
15
|
+
};
|
16
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
17
|
+
__exportStar(require("./AsyncQueue.cjs"), exports);
|
18
|
+
__exportStar(require("./createEventSourceStream.cjs"), exports);
|
19
|
+
__exportStar(require("./readEventSourceStream.cjs"), exports);
|
@@ -0,0 +1,12 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.parseEventSourceStream = void 0;
|
4
|
+
const convertReadableStreamToAsyncIterable_js_1 = require("./convertReadableStreamToAsyncIterable.cjs");
|
5
|
+
const EventSourceParserStream_js_1 = require("./EventSourceParserStream.cjs");
|
6
|
+
async function parseEventSourceStream({ stream, }) {
|
7
|
+
const eventStream = stream
|
8
|
+
.pipeThrough(new TextDecoderStream())
|
9
|
+
.pipeThrough(new EventSourceParserStream_js_1.EventSourceParserStream());
|
10
|
+
return (0, convertReadableStreamToAsyncIterable_js_1.convertReadableStreamToAsyncIterable)(eventStream);
|
11
|
+
}
|
12
|
+
exports.parseEventSourceStream = parseEventSourceStream;
|
@@ -0,0 +1,8 @@
|
|
1
|
+
import { convertReadableStreamToAsyncIterable } from "./convertReadableStreamToAsyncIterable.js";
|
2
|
+
import { EventSourceParserStream } from "./EventSourceParserStream.js";
|
3
|
+
export async function parseEventSourceStream({ stream, }) {
|
4
|
+
const eventStream = stream
|
5
|
+
.pipeThrough(new TextDecoderStream())
|
6
|
+
.pipeThrough(new EventSourceParserStream());
|
7
|
+
return convertReadableStreamToAsyncIterable(eventStream);
|
8
|
+
}
|
@@ -0,0 +1,33 @@
|
|
1
|
+
"use strict";
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
4
|
+
};
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
6
|
+
exports.readEventSourceStream = void 0;
|
7
|
+
const secure_json_parse_1 = __importDefault(require("secure-json-parse"));
|
8
|
+
const AsyncQueue_js_1 = require("./AsyncQueue.cjs");
|
9
|
+
const parseEventSourceStream_js_1 = require("./parseEventSourceStream.cjs");
|
10
|
+
function readEventSourceStream({ stream, schema, errorHandler, }) {
|
11
|
+
const queue = new AsyncQueue_js_1.AsyncQueue();
|
12
|
+
// run async (no await on purpose):
|
13
|
+
(0, parseEventSourceStream_js_1.parseEventSourceStream)({ stream })
|
14
|
+
.then(async (events) => {
|
15
|
+
try {
|
16
|
+
for await (const event of events) {
|
17
|
+
queue.push(schema.parse(secure_json_parse_1.default.parse(event.data)));
|
18
|
+
}
|
19
|
+
}
|
20
|
+
catch (error) {
|
21
|
+
errorHandler?.(error);
|
22
|
+
}
|
23
|
+
finally {
|
24
|
+
queue.close();
|
25
|
+
}
|
26
|
+
})
|
27
|
+
.catch((error) => {
|
28
|
+
errorHandler?.(error);
|
29
|
+
queue.close();
|
30
|
+
});
|
31
|
+
return queue;
|
32
|
+
}
|
33
|
+
exports.readEventSourceStream = readEventSourceStream;
|
@@ -0,0 +1,26 @@
|
|
1
|
+
import SecureJSON from "secure-json-parse";
|
2
|
+
import { AsyncQueue } from "./AsyncQueue.js";
|
3
|
+
import { parseEventSourceStream } from "./parseEventSourceStream.js";
|
4
|
+
export function readEventSourceStream({ stream, schema, errorHandler, }) {
|
5
|
+
const queue = new AsyncQueue();
|
6
|
+
// run async (no await on purpose):
|
7
|
+
parseEventSourceStream({ stream })
|
8
|
+
.then(async (events) => {
|
9
|
+
try {
|
10
|
+
for await (const event of events) {
|
11
|
+
queue.push(schema.parse(SecureJSON.parse(event.data)));
|
12
|
+
}
|
13
|
+
}
|
14
|
+
catch (error) {
|
15
|
+
errorHandler?.(error);
|
16
|
+
}
|
17
|
+
finally {
|
18
|
+
queue.close();
|
19
|
+
}
|
20
|
+
})
|
21
|
+
.catch((error) => {
|
22
|
+
errorHandler?.(error);
|
23
|
+
queue.close();
|
24
|
+
});
|
25
|
+
return queue;
|
26
|
+
}
|
package/index.cjs
CHANGED
@@ -17,6 +17,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
17
17
|
__exportStar(require("./composed-function/index.cjs"), exports);
|
18
18
|
__exportStar(require("./core/index.cjs"), exports);
|
19
19
|
__exportStar(require("./cost/index.cjs"), exports);
|
20
|
+
__exportStar(require("./event-source/index.cjs"), exports);
|
20
21
|
__exportStar(require("./model-function/index.cjs"), exports);
|
21
22
|
__exportStar(require("./model-provider/index.cjs"), exports);
|
22
23
|
__exportStar(require("./observability/index.cjs"), exports);
|
package/index.d.ts
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
export * from "./composed-function/index.js";
|
2
2
|
export * from "./core/index.js";
|
3
3
|
export * from "./cost/index.js";
|
4
|
+
export * from "./event-source/index.js";
|
4
5
|
export * from "./model-function/index.js";
|
5
6
|
export * from "./model-provider/index.js";
|
6
7
|
export * from "./observability/index.js";
|
package/index.js
CHANGED
@@ -1,6 +1,7 @@
|
|
1
1
|
export * from "./composed-function/index.js";
|
2
2
|
export * from "./core/index.js";
|
3
3
|
export * from "./cost/index.js";
|
4
|
+
export * from "./event-source/index.js";
|
4
5
|
export * from "./model-function/index.js";
|
5
6
|
export * from "./model-provider/index.js";
|
6
7
|
export * from "./observability/index.js";
|
@@ -0,0 +1,37 @@
|
|
1
|
+
"use strict";
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
3
|
+
exports.AsyncIterableResultPromise = void 0;
|
4
|
+
class AsyncIterableResultPromise extends Promise {
|
5
|
+
constructor(fullPromise) {
|
6
|
+
super((resolve) => {
|
7
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
8
|
+
resolve(null); // we override the resolve function
|
9
|
+
});
|
10
|
+
Object.defineProperty(this, "fullPromise", {
|
11
|
+
enumerable: true,
|
12
|
+
configurable: true,
|
13
|
+
writable: true,
|
14
|
+
value: fullPromise
|
15
|
+
});
|
16
|
+
Object.defineProperty(this, "outputPromise", {
|
17
|
+
enumerable: true,
|
18
|
+
configurable: true,
|
19
|
+
writable: true,
|
20
|
+
value: void 0
|
21
|
+
});
|
22
|
+
this.outputPromise = fullPromise.then((result) => result.output);
|
23
|
+
}
|
24
|
+
asFullResponse() {
|
25
|
+
return this.fullPromise;
|
26
|
+
}
|
27
|
+
then(onfulfilled, onrejected) {
|
28
|
+
return this.outputPromise.then(onfulfilled, onrejected);
|
29
|
+
}
|
30
|
+
catch(onrejected) {
|
31
|
+
return this.outputPromise.catch(onrejected);
|
32
|
+
}
|
33
|
+
finally(onfinally) {
|
34
|
+
return this.outputPromise.finally(onfinally);
|
35
|
+
}
|
36
|
+
}
|
37
|
+
exports.AsyncIterableResultPromise = AsyncIterableResultPromise;
|
@@ -0,0 +1,16 @@
|
|
1
|
+
import { ModelCallMetadata } from "./executeCall.js";
|
2
|
+
export declare class AsyncIterableResultPromise<T> extends Promise<AsyncIterable<T>> {
|
3
|
+
private fullPromise;
|
4
|
+
private outputPromise;
|
5
|
+
constructor(fullPromise: Promise<{
|
6
|
+
output: AsyncIterable<T>;
|
7
|
+
metadata: Omit<ModelCallMetadata, "durationInMs" | "finishTimestamp">;
|
8
|
+
}>);
|
9
|
+
asFullResponse(): Promise<{
|
10
|
+
output: AsyncIterable<T>;
|
11
|
+
metadata: Omit<ModelCallMetadata, "durationInMs" | "finishTimestamp">;
|
12
|
+
}>;
|
13
|
+
then<TResult1 = AsyncIterable<T>, TResult2 = never>(onfulfilled?: ((value: AsyncIterable<T>) => TResult1 | PromiseLike<TResult1>) | undefined | null, onrejected?: ((reason: unknown) => TResult2 | PromiseLike<TResult2>) | undefined | null): Promise<TResult1 | TResult2>;
|
14
|
+
catch<TResult = never>(onrejected?: ((reason: unknown) => TResult | PromiseLike<TResult>) | undefined | null): Promise<AsyncIterable<T> | TResult>;
|
15
|
+
finally(onfinally?: (() => void) | undefined | null): Promise<AsyncIterable<T>>;
|
16
|
+
}
|
@@ -0,0 +1,33 @@
|
|
1
|
+
export class AsyncIterableResultPromise extends Promise {
|
2
|
+
constructor(fullPromise) {
|
3
|
+
super((resolve) => {
|
4
|
+
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
5
|
+
resolve(null); // we override the resolve function
|
6
|
+
});
|
7
|
+
Object.defineProperty(this, "fullPromise", {
|
8
|
+
enumerable: true,
|
9
|
+
configurable: true,
|
10
|
+
writable: true,
|
11
|
+
value: fullPromise
|
12
|
+
});
|
13
|
+
Object.defineProperty(this, "outputPromise", {
|
14
|
+
enumerable: true,
|
15
|
+
configurable: true,
|
16
|
+
writable: true,
|
17
|
+
value: void 0
|
18
|
+
});
|
19
|
+
this.outputPromise = fullPromise.then((result) => result.output);
|
20
|
+
}
|
21
|
+
asFullResponse() {
|
22
|
+
return this.fullPromise;
|
23
|
+
}
|
24
|
+
then(onfulfilled, onrejected) {
|
25
|
+
return this.outputPromise.then(onfulfilled, onrejected);
|
26
|
+
}
|
27
|
+
catch(onrejected) {
|
28
|
+
return this.outputPromise.catch(onrejected);
|
29
|
+
}
|
30
|
+
finally(onfinally) {
|
31
|
+
return this.outputPromise.finally(onfinally);
|
32
|
+
}
|
33
|
+
}
|
@@ -4,6 +4,7 @@ import { ImageDescriptionFinishedEvent, ImageDescriptionStartedEvent } from "./d
|
|
4
4
|
import { TextEmbeddingFinishedEvent, TextEmbeddingStartedEvent } from "./embed-text/TextEmbeddingEvent.js";
|
5
5
|
import { ImageGenerationFinishedEvent, ImageGenerationStartedEvent } from "./generate-image/ImageGenerationEvent.js";
|
6
6
|
import { StructureGenerationFinishedEvent, StructureGenerationStartedEvent } from "./generate-structure/StructureGenerationEvent.js";
|
7
|
+
import { StructureStreamingFinishedEvent, StructureStreamingStartedEvent } from "./generate-structure/StructureStreamingEvent.js";
|
7
8
|
import { TextGenerationFinishedEvent, TextGenerationStartedEvent } from "./generate-text/TextGenerationEvent.js";
|
8
9
|
import { TextStreamingFinishedEvent, TextStreamingStartedEvent } from "./generate-text/TextStreamingEvent.js";
|
9
10
|
import { SpeechSynthesisFinishedEvent, SpeechSynthesisStartedEvent } from "./synthesize-speech/SpeechSynthesisEvent.js";
|
@@ -48,5 +49,5 @@ export interface BaseModelCallFinishedEvent extends BaseFunctionFinishedEvent {
|
|
48
49
|
*/
|
49
50
|
result: BaseModelCallFinishedEventResult;
|
50
51
|
}
|
51
|
-
export type ModelCallStartedEvent = ImageDescriptionStartedEvent | ImageGenerationStartedEvent | StructureGenerationStartedEvent | SpeechSynthesisStartedEvent | TextEmbeddingStartedEvent | TextGenerationStartedEvent | TextStreamingStartedEvent | TranscriptionStartedEvent;
|
52
|
-
export type ModelCallFinishedEvent = ImageDescriptionFinishedEvent | ImageGenerationFinishedEvent | StructureGenerationFinishedEvent | SpeechSynthesisFinishedEvent | TextEmbeddingFinishedEvent | TextGenerationFinishedEvent | TextStreamingFinishedEvent | TranscriptionFinishedEvent;
|
52
|
+
export type ModelCallStartedEvent = ImageDescriptionStartedEvent | ImageGenerationStartedEvent | StructureGenerationStartedEvent | StructureStreamingStartedEvent | SpeechSynthesisStartedEvent | TextEmbeddingStartedEvent | TextGenerationStartedEvent | TextStreamingStartedEvent | TranscriptionStartedEvent;
|
53
|
+
export type ModelCallFinishedEvent = ImageDescriptionFinishedEvent | ImageGenerationFinishedEvent | StructureGenerationFinishedEvent | StructureStreamingFinishedEvent | SpeechSynthesisFinishedEvent | TextEmbeddingFinishedEvent | TextGenerationFinishedEvent | TextStreamingFinishedEvent | TranscriptionFinishedEvent;
|
@@ -6,7 +6,7 @@ export type StructureFromTextPromptFormat<PROMPT> = {
|
|
6
6
|
createPrompt: (prompt: PROMPT, structure: StructureDefinition<string, unknown>) => string;
|
7
7
|
extractStructure: (response: string) => unknown;
|
8
8
|
};
|
9
|
-
export declare class StructureFromTextGenerationModel<PROMPT, MODEL extends TextGenerationModel<string, any, any, TextGenerationModelSettings>> implements StructureGenerationModel<PROMPT, string, MODEL["settings"]> {
|
9
|
+
export declare class StructureFromTextGenerationModel<PROMPT, MODEL extends TextGenerationModel<string, any, any, TextGenerationModelSettings>> implements StructureGenerationModel<PROMPT, string, undefined, MODEL["settings"]> {
|
10
10
|
private readonly model;
|
11
11
|
private readonly format;
|
12
12
|
constructor({ model, format, }: {
|
@@ -1,9 +1,10 @@
|
|
1
1
|
import { StructureDefinition } from "../../core/structure/StructureDefinition.js";
|
2
|
+
import { DeltaEvent } from "../DeltaEvent.js";
|
2
3
|
import { Model, ModelSettings } from "../Model.js";
|
3
4
|
import { ModelFunctionOptions } from "../ModelFunctionOptions.js";
|
4
5
|
export interface StructureGenerationModelSettings extends ModelSettings {
|
5
6
|
}
|
6
|
-
export interface StructureGenerationModel<PROMPT, RESPONSE, SETTINGS extends StructureGenerationModelSettings> extends Model<SETTINGS> {
|
7
|
+
export interface StructureGenerationModel<PROMPT, RESPONSE, FULL_DELTA, SETTINGS extends StructureGenerationModelSettings> extends Model<SETTINGS> {
|
7
8
|
generateStructureResponse(structure: StructureDefinition<string, unknown>, prompt: PROMPT, options?: ModelFunctionOptions<SETTINGS>): PromiseLike<RESPONSE>;
|
8
9
|
extractStructure(response: RESPONSE): unknown;
|
9
10
|
extractUsage?(response: RESPONSE): {
|
@@ -11,4 +12,12 @@ export interface StructureGenerationModel<PROMPT, RESPONSE, SETTINGS extends Str
|
|
11
12
|
completionTokens: number;
|
12
13
|
totalTokens: number;
|
13
14
|
};
|
15
|
+
/**
|
16
|
+
* Optional. Implement for streaming support.
|
17
|
+
*/
|
18
|
+
readonly generateStructureStreamResponse?: (structureDefinition: StructureDefinition<string, unknown>, prompt: PROMPT, options?: ModelFunctionOptions<SETTINGS>) => PromiseLike<AsyncIterable<DeltaEvent<FULL_DELTA>>>;
|
19
|
+
/**
|
20
|
+
* Optional. Implement for streaming support.
|
21
|
+
*/
|
22
|
+
readonly extractPartialStructure?: (fullDelta: FULL_DELTA) => unknown | undefined;
|
14
23
|
}
|