How do you add stream.value to AIState in the server component? #1546
-
Hi! The only way to immediately stream responses to the frontend seems to be to wrap the model call around the immediately invoked (async () =>, which will then return the stream.value and be ingested by readStreamableValue. However, readStreamableValue only works in the client. Since AIState cannot be manipulated client side, how can the model's streamed responses also be accumulated and added to the AIState on the server? Below are examples from the docs.
|
Beta Was this translation helpful? Give feedback.
Answered by
doureyd
May 10, 2024
Replies: 1 comment 1 reply
-
Hi, you can do it like this : export async function generate(input: string) {
'use server';
// 1. Get a mutable reference to the AI state
const aiState = getMutableAIState<typeof AI>()
const stream = createStreamableValue('');
(async () => {
const { textStream } = await streamText({
model: openai('gpt-3.5-turbo'),
prompt: input,
});
// 2. Create a message variable
let message = "";
for await (const delta of textStream) {
stream.update(delta);
// 3. Update the message with the new delta
message += delta;
}
// 4. Add the message to the AI state
aiState.done([
...aiState.get(),
{
id: nanoid(),
role: 'user',
content: stream.value as string
}
])
stream.done();
})();
return { output: stream.value };
} |
Beta Was this translation helpful? Give feedback.
1 reply
Answer selected by
james-pratama
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, you can do it like this :