Skip to content

How do you add stream.value to AIState in the server component? #1546

Closed Answered by doureyd
james-pratama asked this question in Help
Discussion options

You must be logged in to vote

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(),

Replies: 1 comment 1 reply

Comment options

You must be logged in to vote
1 reply
@james-pratama
Comment options

Answer selected by james-pratama
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Help
Labels
None yet
2 participants