logoassistant-ui
Custom

ExternalStoreRuntime

Overview

If you need full control over the state of the messages on the frontend, use ExternalStoreRuntime.

With LocalRuntime, the chat history state is managed by assistant-ui. This gives you built-in support for thread management, message editing, reloading and branch switching.

Use the ExternalStoreRuntime if you want to manage the message state yourself via any react state management library.

This runtime requires a ExternalStoreAdapter<TMessage> handles communication between assistant-uiand your state. Unless you are storing messages as ThreadMessage, you need to define a convertMessage function to convert your messages to ThreadMessage.

@/app/MyRuntimeProvider.tsx
import { ,  } from "react";
import {
  ,
  ,
  ,
  ,
} from "@assistant-ui/react";
 
const  = (: ):  => {
  return {
    : .,
    : [{ : "text", : . }],
  };
};
 
export function ({
  ,
}: <{
  : ;
}>) {
  const [, ] = (false);
  const [, ] = <[]>([]);
 
  const  = async (: ) => {
    if (.[0]?. !== "text")
      throw new ("Only text messages are supported");
 
    const  = .[0].;
    (() => [
      ...,
      { : "user", :  },
    ]);
 
    (true);
    const  = await ();
    (() => [
      ...,
      ,
    ]);
    (false);
  };
 
  const  = ({
    ,
    ,
    ,
    ,
  });
 
  return (
    < ={}>
      {}
    </>
  );
}

Accessing External Store Messages

You can use the getExternalStoreMessages utility to convert ThreadMessages back to your own message type.

const MyAssistantMessage = () => {
  const myMessages = useMessage((m) => getExternalStoreMessages(m));
  // ...
};

Keep in mind that getExternalStoreMessages may return multiple messages. This is because assistant-ui merges adjacent assistant and tool messages into a single assistant message.

You can do the same operation for individual content parts as well:

const WeatherToolUI = makeAssistantToolUI({
  render: () => {
    const myMessages = useContentPart((p) => getExternalStoreMessages(p));
    // ...
  },
});

On this page

Edit on Github