tambo-ai

Message Threads

Get all the hooks you need for managing AI message threads with tambo.

Message threads are the core building block for creating interactive AI experiences with Tambo. They provide a structured way to manage conversations between users and AI.

Tambo provides hooks to easily interact with the current thread state and its messages, generation stage, and other values.

import { useTamboThread } from "@tambo-ai/react";
 
const { thread } = useTamboThread();

This thread state value is updated automatically by tambo as user messages are sent, and as response messages from tambo are received.

Sending thread messages

We recommend using the useTamboThreadInput hook to send messages to the thread.

import { useTamboThreadInput } from "@tambo-ai/react";
 
const { value, setValue, submit } = useTamboThreadInput(contextKey);

The contextKey is developer generated and is used to identify the thread group.

The value is the value of the message that you want to send.

The setValue is the function that you can use to update the value of the message.

To send a user's message to tambo, you can use the submit function:

You can also pass in an optional options object to the submit function.

setValue("What is the weather like today?");
 
await submit({
  streamResponse: true, // We recommend streaming the response to the user
});

You can use isPending and error to show a loading state or an error state:

if (isPending) {
  return <div>Loading...</div>;
}
if (error) {
  return <div>Error: {error.message}</div>;
}

You can also use the sendThreadMessage function to send messages to the thread:

const { sendThreadMessage } = useTamboThread();
 
await sendThreadMessage("What is the weather like today?", {
  streamResponse: true,
});

Showing thread messages

Since tambo keeps the thread state updated, all you need to do is show the thread's messages somewhere:

const { thread } = useTamboThread()
 
...
 
thread.messages.map((message) => (
<div>
  <p>Sent by: {message.role}</p>
  <p>message text: {message.content[0]?.text}</p>
  <p>component: {message.renderedComponent}</p>
</div>
))

Setting the current thread

By default, tambo will create a new thread for you and use that thread for the thread state value.

If you want to switch to another thread you can use the switchCurrentThread function:

const { switchCurrentThread } = useTamboThread()
 
...
 
switchCurrentThread(threadId)

The thread state will be updated, and anywhere you are rendering the threads list of messages will now be showing the new thread's messages!

On this page