Giter Club home page Giter Club logo

Comments (4)

Phoenix-Alpha avatar Phoenix-Alpha commented on June 3, 2024 1

For me done works but saveChat seems to be not working in some cases. I guess it's when the message content is large and I move to different chat page before saving finishes. What is the solution for this?

from ai.

jeremyphilemon avatar jeremyphilemon commented on June 3, 2024

@kaarthik108 done returns true only when .done() is called on the mutable ai state. Can you confirm you're seeing the same behavior after marking your state as done?

from ai.

kaarthik108 avatar kaarthik108 commented on June 3, 2024

Hey @jeremyphilemon , I do have aiState.done on all of my function call and text-delta methods. but the done is still giving 'False'

from ai.

kaarthik108 avatar kaarthik108 commented on June 3, 2024

I got a workaround to save it from inside the submit function, but would be good to do it on unstable_onsetaistate instead.



async function submitUserMessage(content: string) {
  "use server";
  const aiState = getMutableAIState();

  aiState.update({
    ...aiState.get(),
    messages: [
      ...aiState.get().messages,
      {
        id: nanoid(),
        role: "user",
        content: `${aiState.get().interactions.join("\n\n")}\n\n${content}`,
      },
    ],
  });

  const history = aiState.get().messages.map((message: any) => ({
    role: message.role,
    content: message.content,
  }));

  const textStream = createStreamableValue("");
  const spinnerStream = createStreamableUI(<BotCard>{spinner}</BotCard>);
  // const skeletonStream = createStreamableUI(<AreaSkeleton />);
  const messageStream = createStreamableUI(null);
  const uiStream = createStreamableUI();

  const getDDL = await getContext(content);

  (async () => {
    try {
      const result = await experimental_streamText({
        model: openai.chat("gpt-4-turbo"),
        temperature: 0,
        tools: {
          query_data: {
            description:
              "Query the data from the sqlite database and return the results.",
            parameters: querySchema,
          },
        },
        system: `
You are a Sqlite data analytics assistant. 
      `,
        messages: [...history],
      });

      let textContent = "";
      spinnerStream.done(null);

      for await (const delta of result.fullStream) {
        const { type } = delta;

        if (type === "text-delta") {
          const { textDelta } = delta;

          textContent += textDelta;

          messageStream.update(<BotMessage content={textContent} />);

          // aiState.update({
          //   ...aiState.get(),
          //   messages: [
          //     ...aiState.get().messages,
          //     {
          //       id: "1",
          //       role: "assistant",
          //       content: textContent,
          //     },
          //   ],
          // });

          aiState.done({
            ...aiState.get(),
            interactions: [],
            messages: [
              ...aiState.get().messages,
              {
                id: Date.now(),
                role: "assistant",
                content: textContent,
              },
            ],
          });
        } else if (type === "tool-call") {
          const { toolName, args } = delta;

          if (toolName === "query_data") {
            const {
              format,
              title,
              timeField,
              categories,
              index,
              yaxis,
              size,
              query,
            } = args;

            uiStream.update(
              <BotCard>
                <ChartWrapper props={args} />
              </BotCard>
            );

            aiState.done({
              ...aiState.get(),
              interactions: [],
              messages: [
                ...aiState.get().messages,
                {
                  id: nanoid(),
                  role: "assistant",
                  content: `[Sqlite query results for code: ${query} and chart format: ${format} with categories: ${categories} and data index: ${index} and yaxis: ${yaxis} and size: ${size}]`,
                  display: {
                    name: "query_data",
                    props: args,
                  },
                },
              ],
            });
          }
        }
      }
      const ms = aiState.get().messages;
      const id = aiState.get().chatId;
      // @ts-ignore
      const latestMessages: _Message[] = Array.from(
        new Map(
          ms.filter(isMessage).map((msg: Message) => [msg.role, msg])
        ).values()
      );
      await saveChat({
        id,
        title: latestMessages.map((msg) => msg.content).join("\n\n"),
        messages: latestMessages,
        path: `/chat/${id}`,
        userId: "test",
      });

      uiStream.done();
      textStream.done();
      messageStream.done();
    } catch (e) {
      console.error(e);

      const error = new Error("The AI got into some problem.");
      uiStream.error(error);
      textStream.error(error);
      messageStream.error(error);
      // @ts-ignore
      aiState.done();
    }
  })();

  return {
    id: nanoid(),
    attachments: uiStream.value,
    spinner: spinnerStream.value,
    display: messageStream.value,
  };
}

from ai.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.