/
storyTellerFlow.ts
219 lines (194 loc) · 7.06 KB
/
storyTellerFlow.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import {
generateImage,
generateSpeech,
generateText,
generateTranscription,
openai,
stability,
streamObject,
zodSchema,
} from "modelfusion";
import { DefaultFlow } from "modelfusion-experimental/fastify-server";
import { z } from "zod";
import { VoiceManager } from "./VoiceManager";
import { storytellerSchema } from "./storytellerSchema";
export const storyTellerFlow = new DefaultFlow({
schema: storytellerSchema,
async process({ input: { mimeType, audioData }, run }) {
// Transcribe the user voice input:
const transcription = await generateTranscription({
functionId: "transcribe",
model: openai.Transcriber({ model: "whisper-1" }),
mimeType,
audioData,
});
run.publishEvent({ type: "transcribed-input", input: transcription });
// Generate a story based on the transcription:
const story = await generateText({
functionId: "generate-story",
model: openai.CompletionTextGenerator({
model: "gpt-3.5-turbo-instruct",
temperature: 1.2,
maxGenerationTokens: 1000,
}),
prompt:
"Generate a story aimed at preschoolers on the following topic: \n" +
`'${transcription}'.`,
});
// Run in parallel:
await Promise.allSettled([
// Generate title:
(async () => {
const title = await generateText({
functionId: "generate-title",
model: openai.CompletionTextGenerator({
model: "gpt-3.5-turbo-instruct",
temperature: 0.7,
maxGenerationTokens: 200,
stopSequences: ['"'],
}),
prompt:
"Generate a short title for the following story for pre-school children: \n\n" +
`'${story}'.\n\n` +
'Title: "',
});
run.publishEvent({ type: "generated-title", title });
})(),
// Generate image that represents story:
(async () => {
const imagePrompt = await generateText({
functionId: "generate-story-image-prompt",
model: openai
.ChatTextGenerator({
model: "gpt-4",
temperature: 0,
maxGenerationTokens: 500,
})
.withTextPrompt(),
prompt:
"Generate a short image generation prompt " +
"(only abstract keywords, max 8 keywords) for the following story: " +
story,
});
const storyImage = await generateImage({
functionId: "generate-story-image",
model: stability
.ImageGenerator({
model: "stable-diffusion-xl-1024-v1-0",
cfgScale: 7,
height: 1024,
width: 1024,
steps: 30,
})
.withTextPrompt(),
prompt: `${imagePrompt} style of colorful illustration for a preschooler story`,
});
const imagePath = await run.storeBinaryAsset({
name: "story.png",
data: Buffer.from(storyImage),
contentType: "image/png",
});
run.publishEvent({ type: "generated-image", url: imagePath });
})(),
// expand and narrate story:
(async () => {
const voiceManager = await VoiceManager.fromFile({
voicesPath: "./data/voices.index.json",
narrator: {
voiceId: "c8ea4f2a-06e6-4d7b-9484-db941bf7c657",
name: "Joe",
provider: "lmnt",
gender: "M",
description: "Male voice. Middle-aged.",
},
});
const narratedStoryPartSchema = z.object({
type: z
.enum(["narration", "dialogue"])
.describe("Type of story part. Either 'narration' or 'dialogue'."),
speaker: z
.string()
.describe(
"Speaker of a dialogue (direct speech) part. Must be a single speaker."
),
content: z.string().describe("Content of the story part"),
});
type NarratedStoryPart = z.infer<typeof narratedStoryPartSchema>;
const structuredStorySchema = z.object({
parts: z.array(narratedStoryPartSchema),
});
const processedParts: Array<NarratedStoryPart> = [];
const { objectStream: audioStoryStream, objectPromise } =
await streamObject({
functionId: "generate-audio-story",
model: openai
.ChatTextGenerator({
model: "gpt-4",
temperature: 0,
})
.asFunctionCallObjectGenerationModel({
fnName: "story",
fnDescription: "Kids story with narration.",
})
.withTextPrompt(),
schema: zodSchema(structuredStorySchema),
prompt: [
"Expand the following story into a longer, narrated audio story for preschoolers.",
"",
"The audio story should include interesting dialogue by the main characters.",
"The language should be understandable by a preschooler.",
"",
"Add details and dialog to make the story parts longer.",
"Add the speaker to each dialogue part. A dialogue part can only have one speaker.",
"There must only be one narrator.",
"Each spoken part must be a dialogue part with a speaker.",
"",
"Story:",
story,
].join("\n"),
fullResponse: true,
});
for await (const { partialObject } of audioStoryStream) {
if (partialObject.parts == null) {
continue;
}
// the last story part might not be complete yet:
const partialParts = partialObject.parts.slice(0, -1);
// ensure that the remaining story parts are complete:
const partialPartsParseResult = z
.array(narratedStoryPartSchema)
.safeParse(partialParts);
if (partialPartsParseResult.success) {
await processNewParts(partialPartsParseResult.data);
}
}
// process the remaining parts:
const audioStory = await objectPromise;
await processNewParts(audioStory.parts);
async function processNewParts(parts: NarratedStoryPart[]) {
const newParts = parts.slice(processedParts.length);
processedParts.push(...newParts);
for (const part of newParts) {
const index = processedParts.indexOf(part);
const speaker = part.speaker;
const narrationAudio = await generateSpeech({
functionId: "narrate-story-part",
model: await voiceManager.getSpeechModel({ speaker, story }),
text: part.content,
});
const path = await run.storeBinaryAsset({
name: `story-part-${index}.mp3`,
data: Buffer.from(narrationAudio),
contentType: "audio/mpeg",
});
run.publishEvent({
type: "generated-audio-part",
index,
url: path,
});
}
}
})(),
]);
},
});